Professional Documents
Culture Documents
DSA Assignment
DSA Assignment
DSA Assignment
M.G.D.S.Hiruwinda
Student’s name
List which assessment criteria Pass Merit Distinction
the Assessor has awarded.
Give details:
Programme Leader
signature (if required) Date
LO2 Discuss the advantages, complexity of Abstract Data Type and importance concepts of
Object orientation.
LO4 Examine the advantages of Independent data structures and discuss the need of
asymptotic analysis to assess the effectiveness of an algorithm.
Pass, Merit & P6 P7 M5 D4
Distinction Descripts
Assignment Feedback
Formative Feedback: Assessor to Student
Action Plan
IV
Summative feedback
Assessor Date
signature
hiruwindasahan@gmail.co
Student m Date
signature
V
General Guidelines
• A Cover page or title page – You should always attach a title page to your assignment.
Use previous page as your cover sheet and make sure all the details are accurately filled.
• All the assignments should be printed on A4 sized papers. Use single side printing.
• Allow 1” for top, bottom , right margins and 1.25” for the left margin of each page.
• The font size should be 12 point, and should be in the style of Time New Roman.
• Ensure that all the headings are consistent in terms of the font size and font style.
• Use footer function in the word processor to insert Your Name, Subject, Assignment
No, and Page Number on each page. This is useful if individual sheets become detached
for any reason.
• Use word processing application spell check and grammar check function to help editing
your assignment.
Important Points:
• It is strictly prohibited to use textboxes to add texts in the assignments, except for the
compulsory information. eg: Figures, tables of comparison etc. Adding text boxes in the
body except for the before mentioned compulsory information will result in rejection of
your work.
• Carefully check the hand in date and the instructions given in the assignment. Late
submissions will not be accepted.
VI
• Ensure that you give yourself enough time to complete the assignment by the due date.
• Excuses of any nature will not be accepted for failure to hand in the work on time.
• You must take responsibility for managing your own time effectively.
• If you are unable to hand in your assignment on time and have valid reasons such as
illness, you may apply (in writing) for an extension.
• Non-submission of work without valid reasons will lead to an automatic RE FERRAL. You
will then be asked to complete an alternative assignment.
• If you use other people’s work or ideas in your assignment, reference them properly
using HARVARD referencing system to avoid plagiarism. You have to provide both in-
text citation and a reference list.
• If you are proven to be guilty of plagiarism or any academic misconduct, your grade
could be reduced to A REFERRAL or at worst you could be expelled from the course
Student Declaration
I hereby, declare that I know what plagiarism entails, namely to use another’s work and to
present it as my own without attributing the sources in the correct form. I further understand
what it means to copy another’s work.
Submission format
The submission should be in the form of a report, which contains code snippets
(which must be described well), text-based descriptions, and diagrams where
appropriate. References to external sources of knowledge must be cited (reference
VIII
list supported by in-text citations) using the Harvard Referencing style.
LO1. Examine abstract data types, concrete data structures and algorithms.
LO2. Specify abstract data types and algorithms in a formal notation.
LO3. Implement complex data structures and algorithms.
LO4. Assess the effectiveness of data structures and algorithms.
In order to manage this particular event ABC Pvt Ltd decided to develop an
Application.
Application functions are listed down.
IX
3.Insert 3 Rounds Results.
4.Find out the winners (1st,2nd,3rd)
5.Search for a particular car
Task 1: Examine and create data structure by simulating the above scenario and
explain the valid operations that can be carried out on this data structure.
Determine the operations of a queue and critically review how it is used to
implement function calls related to the above scenario.
Task 2: Implement the above scenario using the selected data structure and its valid
operations for the design specification given in task 1 by using java programming.
Use suitable error handling and Test the application using suitable test cases and
illustrate the system. Provide evidence of the test cases and the test results.
Task 3 : Registered Car details are stored from oldest to newest. Management of
ABC Pvt Ltd should be able to find from the newest to oldest registered car details.
Using an imperative definition, specify the abstract data type for the above scenario
and implement specified ADT using java programming and briefly discuss the
complexity of chosen ADT algorithm. List down the advantages of Encapsulation and
Information hiding when using an ADT selected for the above scenario.
“Imperative ADTs are basis for object orientation.” Discuss the above view stating
whether you agree or not. Justify your answer.
Task 4: ABC Pvt Ltd plans to visit all of these participants through the shortest path
within a day.
Analyse the above operation by using illustrations, of two shortest path algorithms,
specify how it operates using a sample graph diagram. Sort the cars based on
numbers with two different sorting algorithms and critically review the
performances of those two algorithms by comparing them.
X
Task 5: Evaluate how Asymptotic analysis can be used to assess the effectiveness of
an algorithm and critically evaluate the different ways in which the efficiency of an
algorithm can be measured.
Critically review the sort of trade-offs exists when you use an ADT for implementing
programs. You also need to evaluate the benefits of using independent data
structures for implementing programs.
Grading Rubric
XI
M1 Illustrate, with an example, a concrete
data structure for a First In First out (FIFO)
queue.
XII
test results.
XIII
Table of Contents
Task 01.......................................................................................................................................
1.1 Examine abstract data types, concrete data structures and algorithms.......................1
1.1.1 Data Structures........................................................................................................1
1.1.2. Why data structures important?..............................................................................2
1.1.3 How are Data structures used?................................................................................2
1.1.4 Types of Data structures..........................................................................................4
Algorithm for Linked list.................................................................................................5
1.2 Concrete data structures and algorithms................................................................7
1.3 Determine the operations of a memory stack........................................................9
Task 02.....................................................................................................................................
The Java code for the "Car" class with the specified attributes...............................................
1. Define an array of type "Car" with a fixed size of 6 to store the car details...........13
The Use Of Try-Catch Blocks To Handle Any Errors.............................................................
Test cases to ensure that the application works as expected..........................................21
The implementation of the solution in Java programming language.......................................
Task 03.....................................................................................................................................
Abstract Data Type (ADT) I. Abstract Data Type (ADT).......................................................
Complexity Analysis of the Chosen ADT Algorithm..............................................................
Task 04.....................................................................................................................................
4.1 Assess the effectiveness of data structures and algorithms......................................35
4.1.1 Compare the performance of two sorting algorithms....................................................35
4.2 Analyze the operation, using illustrations, of two network shortest path algorithms,
providing an example of each........................................................................................39
Task 05.....................................................................................................................................
5.1 Discuss how asymptotic analysis can be used to assess the effectiveness of an
algorithm........................................................................................................................51
5.1.1 What is Algorithm Analysis?................................................................................51
5.1.2 Why is Algorithm Analysis Important?................................................................51
5.1.3 Experimental and Asymptotic Analysis................................................................52
5.2 Types of Asymptotic Notations in Complexity Analysis of Algorithms.................52
Theta Notation (Θ-Notation):.........................................................................................52
5.2.1 How to measure the efficiency of algorithms.......................................................55
1
An expertly designed format for arranging, processing, accessing, and storing data is
called a data structure. Data structures come in both simple and complex forms, all of
which are made to organize data for a certain use. Users find it simple to access the data
they need and use it appropriately thanks to data structures. The organizing of information
is framed by data structures in a way that both machines and people can better grasp.
For instance, the data structure and the accompanying methods are tied together as part of
the class definition in an object-oriented programming language. Although they may be
designed to operate with the data structure in non-object-oriented languages, these
functions are not considered to be a part of the data structure.
3 Data Structures
Figure 1:
When it comes to communicating the logical meaning behind data processing and
application, the typical fundamental data types present in most computer programming
languages, such as integers or floating-point numbers, are frequently insufficient.
Applications that ingest, manipulate, and output information must understand how data
should be arranged in order to make processing easier. Data structures logically combine
various data components to enable effective data consumption, persistence, and exchange.
They offer a formal model that specifies how the data elements should be arranged.
For more complicated applications, data structures serve as the foundation. They are
produced by combining data elements into coherent units that reflect abstract data types
pertinent to the algorithm or application under development. "Customer name" is an
illustration of an abstract data type. It is made up of character strings that stand in for the
"first name," "middle name," and "last name."
To construct the physical representations of abstract data types, data structures are
frequently utilized. Data structures must be carefully considered when developing
software. They are essential to the development of algorithms and their use in real-world
computer programs.
Usually, data structures are used to create the physical representations of abstract data
types. Using the right data structures is necessary for developing efficient applications.
They are essential for both designing algorithms and putting them to use in computer
applications.The data structures that software developers use, such as lists, queues, and
mappings that pair up different sets of values, are strongly related to the algorithms they
use. The management of record collections in a relational database and the creation of an
index of those records using the binary tree data structure are two applications where this
method is useful.
Ordering and Sorting: Data structures like priority queues and binary search trees offer
effective ways for ordering and sorting data components, such as character strings used as
tags, enabling programmers to manage the priority of objects.
Indexing: In databases, complex data structures like B-trees are used to index things,
improving the effectiveness of search operations and retrieval.
Searching: To create indexes that speed up the process of finding specific objects within a
dataset, methods like B-trees, hash tables, and binary search trees are frequently
employed.
Scalability: To allocate and manage data storage across distributed storage sites while
ensuring performance and scalability, data structures are essential in big data applications.
Data structures that duplicate the underlying structure of database records are offered by
programming environments like Apache Spark, making querying simpler.
Overall, data structures are crucial for many areas of data management because they make
it possible for information to be stored, processed, and retrieved in a variety of
applications and systems in an efficient manner.
5
The precise operations or algorithms necessary in a given circumstance dictate the sort of
data structure to be used. Various data structure types are listed below:
An array keeps a group of things in close proximity to one another in memory. Items of
the same type are gathered together to facilitate simple index-based retrieval. Array
lengths can be either fixed or variable.
Stack: Depending on the chosen layout, a stack arranges objects in a linear series that
follows the "first in, first out" (FIFO) or "last in, first out" (LIFO) order.
Queue: A queue stores a group of items similarly to a stack, but all actions are always
carried out according to the principle of "first in, first out."
Linked list: A linked list keeps track of the items in a logical order. The linked list's
elements and nodes each contain data items and references to the subsequent items.
Tree: A tree organizes a group of things into an arbitrary hierarchy. Each node has a
unique key value, and parent nodes and child nodes (subnodes) are connected. All nodes
in the tree have their roots as their common ancestor.
Heap: In a heap, each parent node's key value is higher than or on par with that of its
offspring. Tree-based data structures are heaps.
Graph: A graph is a nonlinear way to store a group of elements. There are a finite
number of nodes (vertices) and lines (edges) that make up the structure. Graphs can be
used to model real systems, including computer networks.
Trie: A trie, commonly referred to as a keyword tree, organizes strings into a visible
graph-like structure and stores them as data objects.
Hash table: Also known as a hash map, a hash table is a type of data structure that is used
to store a variety of things in an associative array that maps keys to values. An index is
6
The operations and algorithms necessary for a certain situation determine the data
structure to be used.
Display "OVERFLOW"
Proceed to Step 7
[End of Condition]
It is essential to choose the right data structures and algorithms for the task at hand when
creating software applications. The effectiveness of an application can be considerably
impacted by the choice of data structure and algorithm. Making decisions based on the
particular needs of the application demands a thorough understanding of concrete data
structures and algorithms.
The idea that the first assets purchased or generated should be sold, utilized, or disposed
of first is the guiding idea behind the First In, First Out (FIFO) method, a technique used
to manage and evaluate assets.
The FIFO technique makes the fiscal assumption that the costs associated with the oldest
inventory items are included in the cost of goods sold (COGS) on the income statement. It
contrasts the remaining inventory items with those that were just purchased or created.
Initializing a queue, using it, and permanently deleting the data from memory are all
considered basic operations. The queue abstract data type (ADT) depends on these
operations.
Enqueue(), dequeue(), peek(), isFull(), and isEmpty() are the queue ADT's five most
important operations. These built-in operations allow for data processing while
determining the queue's status.
The queue makes use of front and rear pointers to aid enqueuing. While the front pointer
accesses data from the front end of the queue, the rear pointer accesses data from the back
end. The right order of data insertion and retrieval is maintained with the help of this
method.
enqueue ()
Using two data pointers at the front and back of the queue, the enqueue() process includes
adding data to the queue. Compared to stack operations, enqueue operations can be more
difficult to implement. The procedure for putting data into a queue is outlined in the steps
below:
Dequeue
The dequeue procedure comprises accessing the data pointed to by the front pointer and
then removing the accessed data to get data from a queue in two phases. To execute a
dequeue action, adhere to the instructions below:
10
Data is arranged and kept in linear data structures called memory stacks or lines in
computer memory. Stacks work in a certain order and are intended to hold data of the
same type. The most recent item added is the first one to be withdrawn since they use the
Last-In, First-Out (LIFO) mechanism. The stack functions according to a set of
established insertion and removal methods,which guarantee that the data is accessed and
managed in a methodical way. The various stack manipulation operations will be covered
in this section.
The management and access of data in a stack are governed by the "last-in, first-out"
(LIFO) concept. With LIFO, the computer handles data requests within its memory in a
certain way. This principle states that the data that was added or placed in the stack most
recently is the first to be erased. It is significant to notice that applying LIFO to a movie
queue would result in anarchy, as seen in the previous figure. We shall examine the
actions carried out on a stack using the figure shown below in the sections that follow.
Adding data items to a stack is the main goal of the push operation. In our second
example of the restaurant plate dispenser, adding plates (or data items) to the dispenser
(stack) is the push operation. The first plate is moved to the bottom of the stack and is
followed by each additional plate. The first new piece of data is placed at the bottom of
the arrangement, making it the least visible.
11
A populated stack of data objects can be cleared out using the pop function. In the
analogy of the plate dispenser, the most current plate (piece of data) is placed on top of
the stack. This top-most data item will be the first thing eliminated when using the pop
operation. By thinking about the spring loading system at the plate dispenser's base, you
may picture this procedure. Every time a plate is removed, the stack of plates rises, which
causes succeeding items to appear in the same sequence in the memory.
We then do the push and pop operations before completing the stacks' peek operation. A
"peek" is a brief observation or examination of anything that is present in a specific
region. It entails searching for a certain piece within a stack at a particular location.
Before adding an element to the top of a stack, make sure it isn't already full by
increasing the value. Make sure the stack is not empty before peeking at it. You can
access the top element without changing its value if it's not empty.
A letter or string used to limit the results of a search is referred to as a search operator or
search parameter. In computer science and mathematics, operators carry out operations.
Boolean operators like AND, NOT, and OR, which are frequently employed in search
operations, have particular purposes. AND demands that the search results contain both
the words or phrases that come before and after it. NOT filter out particular words or
phrases from the outcomes. OR incorporates both terms as well as any others. Before a
query word or phrase, other search operators are used. Multiple operators can be
combined to further refine the search emphasis.
12
Because the activation record of the most recently run function is at the top of the stack,
the stack-based approach makes sure that it receives precedence in memory. A dynamic
and effective memory management system is produced by adding and removing the
necessary activation records from the stack when functions are called and returned.
Function-related data can be stored and retrieved effectively using this strategy, giving
programs the structure they need to run.
Task 02.
The Java code for the "Car" class with the specified attributes
public class Car {
private int carNumber;
private String brand;
13
14
1. Define an array of type "Car" with a fixed size of 6 to store the car details.
This creates an array of type "Car" with a fixed size of 6 and initializes all elements to
null. You can then store Car objects in the array by assigning them to the appropriate
index. For example, to store a Car object at index 0:
This creates a new Car object with the specified attributes and stores it in the first element
of the carArray.
• registerCarDetails(): This method takes input from the user and registers the car
details by creating a new Car object and storing it in the array.
• deleteCar(): This method takes input from the user and deletes a car from the array
based on the car number.
• insertRoundResults(): This method takes input from the user and updates the
round results for each car in the array.
• findWinners(): This method finds the winners of the race based on the round
results and displays them to the user.
15
The Java code for the "CarRace" class with the specified methods
import java.util.Scanner;
if (numCars == 6) {
return;
carArray[numCars] = car;
numCars++;
if (numCars == 0) {
17
return;
if (carArray[i].getCarNumber() == carNumber) {
carArray[j] = carArray[j+1];
roundResults[j] = roundResults[j+1];
carArray[numCars-1] = null;
roundResults[numCars-1] = 0;
numCars--;
return;
18
if (numCars == 0) {
return;
roundResults[i] = input.nextInt();
if (numCars == 0) {
return;
19
Arrays.sort(sortedResults);
System.out.println("Winners:");
if (roundResults[j] == result) {
break;
if (numCars == 0) {
for (int
We can use try-catch blocks to handle any errors that may occur during input or
processing as follows:
1. Place the code that may generate an exception inside a try block.
2. If an exception occurs during the execution of the code inside the try block, it is
caught by the catch block.
3. In the catch block, we can handle the exception by displaying an error message to
the user or taking appropriate action to recover from the exception.
4. If no exception occurs, the catch block is skipped and the program continues to
execute normally.
try {
21
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please enter a valid integer for car number.");
}
• Register 6 cars with unique car numbers, brands, sponsors, and driver details.
Verify that the cars are added to the array and the correct details are stored.
• Delete a car from the array by entering its car number. Verify that the car is
removed from the array and the remaining cars are shifted to fill the empty spot.
• Enter round results for all 6 cars. Verify that the round results are stored correctly
for each car.
• Enter round results for all 6 cars and find the winners. Verify that the winners are
correctly identified based on the round results.
22
• Try to delete a car that does not exist by entering an invalid car number. Verify
that an appropriate error message is displayed.
7. Test entering round results for a car that does not exist:
• Try to enter round results for a car that does not exist by entering an invalid car
number. Verify that an appropriate error message is displayed.
• Try to enter invalid round results (e.g., negative or non-numeric values). Verify
that an appropriate error message is displayed.
• Try to register more than 6 cars. Verify that an appropriate error message is
displayed and the extra cars are not added to the array.
Car.java
23
CarRace.java
import java.util.Scanner;
for (int
5. Provide evidence of the test cases and their results, including any screenshots or
output logs.
Task 03.
Abstract Data Type (ADT) is a high-level description of a set of data values and the
operations that can be performed on them. It provides an abstract view of a data structure
independent of its implementation. ADT is a useful tool in software development as it
helps in creating efficient algorithms, promotes code reuse, and simplifies code
maintenance.
28
1. addCar(Car car): Adds a Car object to the end of the linked list.
2. deleteCar(int carNumber): Deletes a Car object from the linked list based on the
car number.
3. getCar(int carNumber): Searches for and returns a Car object from the linked list
based on the car number.
4. displayAllCars(): Displays all Car objects in the linked list from the newest to
oldest registered.
To implement the linked list ADT, we will create two classes: "Car" and
"LinkedListNode". The "LinkedListNode" class will contain a reference to a "Car" object
and a reference to the next "LinkedListNode". The "Car" class will contain attributes such
as carNumber, brand, sponsor, and driverDetails.
Next, we will create a "LinkedList" class that contains methods to perform the operations
listed in the imperative definition of the ADT. The "LinkedList" class will contain a
reference to the first "LinkedListNode" in the list.
29
// Constructor
public LinkedListNode(Car car) {
this.car = car;
this.next = null;
}
// Constructor
public LinkedList() {
31
if (head == null) {
head = newNode;
} else {
LinkedListNode currentNode = head;
while (currentNode.getNext() != null) {
currentNode = currentNode.getNext();
}
currentNode.setNext(newNode);
}
}
// Method to delete a Car object from the linked list based on the car number
public void deleteCar(int
A. Time complexity:
32
2. Deletion: The time complexity for deleting a node from the beginning of the
linked list is O(1). Deleting a node from the end of the linked list takes O(n) time
complexity where n is the number of nodes in the linked list.
3. Searching: The time complexity for searching a node in the linked list is O(n)
where n is the number of nodes in the linked list.
B. Space complexity: The space complexity of the linked list algorithm depends on the
number of nodes in the linked list. For each node, a fixed amount of memory is required
to store the node's data and a reference to the next node. Therefore, the space complexity
of the linked list is O(n) where n is the number of nodes in the linked list.
Overall, the time complexity for the operations performed on the linked list is efficient,
while the space complexity is directly proportional to the number of nodes in the linked
list.
33
In the chosen ADT for the scenario, encapsulation and information hiding provide the
following advantages:
1. Data Protection: Encapsulation and information hiding ensure that the data stored
in the ADT is protected from unauthorized access and modification, as access to the data
is controlled through the class interface. This helps to prevent errors and maintain data
integrity.
34
• Imperative ADTs are a type of data structure that is defined by the operations that
can be performed on it. These operations are often expressed in an imperative
programming style.
Agreement or disagreement with the statement that "Imperative ADTs are basis for object
orientation": I would disagree with the statement that "Imperative ADTs are basis for
object orientation" because while imperative ADTs can be used as building blocks for
object-oriented programming, they are not the only basis for object orientation. Object
orientation involves much more than just data structures, it encompasses the entire design
and architecture of a program, including things like inheritance, polymorphism, and
encapsulation.
C. Justification of the answer: Object orientation is a broader concept than just data
structures, as it involves designing and implementing classes and objects that interact
with each other to solve complex problems. While data structures are an important part of
object-oriented programming, they are just one piece of the puzzle. Object-oriented
35
Task 04
4.1 Assess the effectiveness of data structures and algorithms.
4.1.1 Compare the performance of two sorting algorithms.
Sorting Algorithms
Bubble Sort: A straightforward sorting method called bubble sort compares nearby list
items and swaps them if they are in the wrong order. Up until the complete list is sorted,
this procedure is repeated. However, because Bubble Sort has an O(n2) time complexity,
it is ineffective when dealing with big lists.
Step 8 - end if
Step 4 − Shift all the elements in the sorted sub-list that is greater than the
value to be sorted
In a selection sort, the initial element is switched out for the smallest one in the list. The
next step in this process is to choose the second-smallest element and swap it with the
37
A divide-and-conquer strategy known as merge sort separates the list into smaller
sublists, sorts them recursively, and then merges the sublists back together. Large lists can
be efficiently sorted using this method thanks to its O(n log n) time complexity. To store
the sublists, merge sort needs extra RAM.
Quick Sort is another divide-and-conquer algorithm that divides the list around a pivot
element that is chosen. Recursive sorting is then performed on the two resulting sublists.
Quick Sort typically has a time complexity of O(n log n), but in the worst-case scenario, it
might have an O(n2) time complexity due to improperly chosen pivots.
Heap Sort:
Heap sorting is a sorting method that compares elements using a binary heap data
structure. The largest piece is regularly taken out of the heap and added to the end of the
sorted list. Heap sort is frequently used when the worst-case performance is better than
quicksort. It takes O(n log n) amount of time to complete.
The smallest (or largest) element from the unsorted part of the list is regularly chosen and
moved to the sorted part of the list using the straightforward and effective sorting
algorithm known as selection sort. The algorithm repeatedly chooses the smallest (or
largest) element from the list's unsorted section and swaps it with the unsorted section's
initial member. Up until the complete list is sorted, this procedure is repeated for the last
unsorted section of the list. A selection sort variant known as "bidirectional selection sort"
38
Quick Sort is a sorting method based on the Divide and Conquer algorithm that chooses
an element as a pivot and divides the given array around the picked pivot by placing the
pivot in the correct location in the sorted array.
Merge sort is a sorting method that breaks up a large array into smaller subarrays, sorts
each subarray separately, and then combines the sorted subarrays to form the final sorted
array.
39
Step 2 − divide the list recursively into two halves until it can no more be divided.
Step 3 − merge the smaller lists into new list in sorted order.
4.2 Analyze the operation, using illustrations, of two network shortest path
algorithms, providing an example of each.
There are numerous shortest path algorithms that can be used to find the shortest route
between two nodes in a network. In this response, we'll discuss two of the best-known
algorithms: the Dijkstra algorithm and the Bellman-Ford algorithm.
Dijkstra's Algorithm
The greedy Dijkstra's approach is used in a weighted network to find the shortest path
between a source node and every other node. The method records all nodes, both accessed
and unaccessed. The distance to the source node is initially set to zero, while the distance
to every other node is initially set to infinite. At each step, the technique selects the
unexplored node with the least distance and explores its neighbors. Each neighbor's
distance through the current node is calculated, and if it is smaller than the previously
calculated distance, the distance is updated. The process continues until either the target
node is reached or each node has been visited once.
Before delving into the detailed use of Dijkstra's algorithm, let's take a closer look at
some of its key features. The first step in Dijkstra's method is to choose a source node,
after which it searches the complete graph for the shortest route between that node and
every other node.
The method keeps track of the current shortest path from the source node to each
individual node throughout the process, updating these values if a new, shorter path is
found.
40
This iterative procedure keeps going until all of the nodes in the graph are covered by the
path, making sure that a thorough path connecting every node is established while giving
the best and logically shortest paths priority.
The section above describes the step-by-step process of the Dijkstra algorithm. Let's
investigate the algorithm using an illustrated example.
The graph's shortest path between node C and the other nodes will be found.
41
Because node C has been selected, the least distance between each node and node C will
be recorded during algorithm execution.
In this case, the minimum distance to node C is 0. The remaining nodes will all be labeled
as infinite (), since we are unsure of their exact distances, with the exception of node C
(now shown as a red dot).
We'll now look at nodes A, B, and D, which are node C's neighbors. We will now start
with B and add the weight of the edge connecting nodes C and B (seven) to the lowest
distance of the current node (zero), resulting in the equation 0+ 7 = 7.
The smallest value still corresponds to the lowest distance to node B, which is now being
compared to this value, in this case 7, because it is less than infinite.
42
With neighbor A, the same procedure is now confirmed. The weight of the edge joining
nodes C and A, 1, is added to 0 to get 1. 1 is the smallest value when compared to A's
infinity-minimum distance once more.
43
Node C is shown as visited with a green check mark because all its neighbors have
verified that they have visited.
44
Using the same procedure, we only check node B while ignoring the visited node and
looking at the node's neighbor.
The edge between nodes A and B has a weight of 3, and when we add 1 to it, we get 4 for
node B. Following comparison with the minimum distance at B, which is 7, the lowest
value at B will be noted as 4.
45
46
There is no need to check anything because it doesn't have any unchecked neighbors. A
green mark indicates that Node E has been visited.
47
Bellman-Ford Algorithm
Given a graph and a source vertex, find the shortest paths between each vertex in the
graph and the source vertex. The graph could have edges that have negative weights.
We have already discussed Dijkstra's approach to this problem. The Dijkstra algorithm,
which uses the Fibonacci heap, has a time complexity of O((V+E) LogV). For graphs
with negative weights, Bellman-Ford works well, but Dijkstra does not. Bellman-Ford is
perfect for distributed systems and is less complicated than Dijkstra. However, Bellman-
Ford's temporal complexity is higher than Dijkstra's at O (V * E).
The algorithm, like earlier dynamic programming problems, finds the shortest paths from
the bottom up. First, we find the shortest pathways with a maximum of one edge. Then it
establishes the shortest paths that have no more than two edges, and so on. After the i-th
iteration of the outer loop, the shortest paths with at most i edges are identified. The outer
loop repeats |v| - 1 times since any simple path can only have |V| - 1 edges. The idea is as
follows, assuming there is no negative weight cycle: If we have identified shortest paths
with at most i edges, an iteration over all edges guarantees that the shortest path with at
most (i+1) edges will be generated.
Step 1: Permit setting the source vertex to zero. All distances, with the exception of the
distance to the source, should be initialized as infinite. Each edge must be processed four
times because there are five total vertices in the graph.
48
49
Step 4: The second iteration ensures that all shortest paths have a maximum of two edges.
All edges are processed twice more by the algorithm. After the second iteration, the
distances are minimized, and the third and fourth iterations do not update the distances.
The result contains the vertices which contains The result contains the vertices containing whole
the information about the other vertices they information about the network, not only the
are connected to. vertices they are connected to.
50
It is more time consuming than Dijkstra’s It is less time consuming. The time complexity is
algorithm. Its time complexity is O(VE). O(E logV).
Task 05
5.1 Discuss how asymptotic analysis can be used to assess the effectiveness of an
algorithm.
51
Assessing the performance of an algorithm can be done using two main methods: experimental
analysis and asymptotic analysis. Experimental analysis involves running the algorithm on
different inputs and evaluating its performance. This method can provide a more accurate
understanding of how the algorithm performs, but it can be time-consuming and impractical for
large input quantities. It helps identify code bottlenecks and areas where the algorithm is slow or
inefficient. However, experimental analysis has limitations as it requires writing a corresponding
program for measurement. On the other hand, asymptotic analysis allows us to compare the
52
Asymptotic analysis and the worst, average, and best cases of algorithms have been
discussed. Asymptotic analysis's main objective is to offer a gauge of algorithm
efficiency that does not rely on machine-specific constants, does not require the
construction of algorithms, and does not compare the execution times of various
programs. Mathematicians employ asymptotic notations to convey the time complexity of
asymptotic analysis methods.
Theta notation is used to surround the function from above and below. Because it reflects
the upper and lower ranges of an algorithm's execution time, it is used to assess the
average-case complexity of an algorithm.
Let g and f denote the function from the set of natural numbers to itself. The function f is
referred to as being (g) if constants c1, c2, and a natural number n0 exist such that c1*
g(n) f(n) c2* g(n) for every n n0.
53
If f(n), which stands for an algorithm's running time, is a positive constant and n0 is such
that f(n) cg(n) for all n n0, then f(n) is O(g(n)).
It returns the largest possible output value (big-O) for a given input.
The execution time sets a limit on the algorithm's complexity.
54
In omega notation, the execution time of an algorithm is displayed at its lowest bound. It
provides an algorithm's best-case complexity as a result.
Let g and f denote the function from the set of natural numbers to itself. The function f is
referred to as being (g) if there is a constant c > 0 and a natural number n0 such that
c*g(n) f(n) for all n n0.
55
Just like other areas of life, computer programming has a variety of problem-solving
techniques. Because these various ways could show different times, processing power, or
any other metric you pick, we need to evaluate the performance of several strategies
before selecting the best one.
They can carry out the same task in the present era extremely differently because of how
much they have changed. In the worst case (which happens very frequently), different
machines with different hardware and operating systems may be instructed by different
algorithms implemented in different programming languages to carry out the same task in
different ways. What an absurd notion, huh?
The time complexity of an algorithm is not determined by the actual time required to run
a piece of code because that depends on other factors like the operating system,
programming language, processor speed, etc. The idea behind time complexity is that it
can only estimate how long an algorithm will take to execute based purely on the method
and its input.
To express how time-consuming a method is, we use a method called "Big O notation".
We use the Big O notation, a language, to describe how time-consuming an algorithm is.
56
Big O notation describes an algorithm's run time in terms of how quickly the input (referred to as
"n") expands in comparison to the algorithm. Thus, if we were to assert, for instance, that an
algorithm's runtime increases "on the order of the size of the input," we would write it as "O(n)".
If we want to state that an algorithm's execution time increases "on the order of the square of
the size of the input," we would use the notation "O(n2)". But exactly what does that mean?
Knowing the speeds at which things might increase is essential to comprehending time
complexity. Time taken per input size is the unit of measurement here. There are various time
complexity kinds, so let's look at the most fundamental ones first.
An algorithm or operation is said to have "constant complexity" if it always takes the
same amount of time or space to complete, regardless of the size of the input. In other
words, the time or space needs of the algorithm or operation are independent of the size
of the input.
For instance, no matter how much input was provided, an algorithm with a constant time
complexity of O(1) would always require five steps to complete. Such a data structure
always uses 10 bytes of memory, regardless of the number of components it includes, and
has a constant space complexity of O(1).
Space Complexity
Consider the list ADT, which may be used either as an array or a linked list. If we choose
to implement the list as an array, we can gain constant-time access to every entry. It can,
however, take O(n) time to move every element after a middle-of-the-list element in order
to insert or remove it.
This is an example of how spatial and temporal complexity can be traded off. While the
array solution provides faster access times but requires more capacity to retain the entire
list, the linked list technique uses less storage space but compromises access speeds for
elements in the middle of the list.
When developing an ADT, it's crucial to assess the benefits and drawbacks of several
implementation options and select the one that best meets the demands of the application.
For instance, if quick access times are crucial, the array solution would be chosen,
whereas the linked list technique might be more appropriate if memory usage is an issue.
58
References:
Harvard References:
Goodrich, M.T., Tamassia, R. and Goldwasser, M.H. (2014). Data Structures and
Algorithms in Java. Wiley.
Cormen, T.H., Leiserson, C.E., Rivest, R.L. and Stein, C. (2009). Introduction to
Algorithms, 3rd ed. The MIT Press.
Karumanchi, N. (2011). Data Structures and Algorithms Made Easy: Data
Structures and Algorithmic Puzzles. CareerMonk Publications.
59
60