Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Data Structures and Algorithms - ASM 1 - Grade D, Study Guides, Projects, Research of Data Structures and Algorithms

Data Structures and Algorithms - ASM 1 - Grade D

Typology: Study Guides, Projects, Research

2022/2023

Uploaded on 06/15/2023

Phan-Nhat-Linh-11
Phan-Nhat-Linh-11 🇻🇳

4.8

(108)

34 documents

1 / 55

Toggle sidebar

Often downloaded together


Related documents


Partial preview of the text

Download Data Structures and Algorithms - ASM 1 - Grade D and more Study Guides, Projects, Research Data Structures and Algorithms in PDF only on Docsity! 1 ASSIGNMENT 1 FRONT SHEET Qualification BTEC Level 5 HND Diploma in Computing Unit number and title Unit 19: Data Structures and Algorithms Submission date Date Received 1st submission Re-submission Date Date Received 2nd submission Student Name Phan Nhat Linh Student ID GCD201635 Class GCD0905 Assessor name Pham Thanh Son Student declaration I certify that the assignment submission is entirely my own work and I fully understand the consequences of plagiarism. I understand that making a false declaration is a form of malpractice. Student’s signature Linh Grading grid P1 P2 P3 M1 M2 M3 D1 D2 2  Summative Feedback:  Resubmission Feedback: Grade: Assessor Signature: Date: Internal Verifier’s Comments: IV Signature: 5 Table of Figures Figure 1: Abstract data type model ................................................................................................................ 7 Figure 2: System design with ADTs .............................................................................................................. 10 Figure 3: ArrayList ......................................................................................................................................... 10 Figure 4: Fields and add method in ArrayList ............................................................................................... 11 Figure 5: add method in ArrayList ................................................................................................................ 12 Figure 6: insert method in ArrayList ............................................................................................................. 12 Figure 7: get method in ArrayList ................................................................................................................. 13 Figure 8: set method in ArrayList ................................................................................................................. 13 Figure 9: Remove and shift method in ArrayList .......................................................................................... 14 Figure 10: get method in ArrayList ............................................................................................................... 14 Figure 11: Size method in ArrayList .............................................................................................................. 14 Figure 12: indexOf method in ArrayList ....................................................................................................... 15 Figure 13: contains method in ArrayList ...................................................................................................... 15 Figure 14: isEmpty method in ArrayList ....................................................................................................... 15 Figure 15: Using ArrayList manage Employee .............................................................................................. 17 Figure 16: Result of using ArrayList to managa Employee ........................................................................... 18 Figure 17: How data is organized in a stack ................................................................................................. 19 Figure 18: How a function calls is implemented with the stack .................................................................. 20 Figure 19: Example of function calls with the stack ..................................................................................... 21 Figure 20: Doubly-Linked Lists ...................................................................................................................... 22 Figure 21: Fields in DoublyLinkedList ........................................................................................................... 23 Figure 22: addFirst in DoublyLinkedList ....................................................................................................... 24 Figure 23: addIndex in DoublyLinkedList ..................................................................................................... 25 Figure 24: addLast in DoublyLinkedList ........................................................................................................ 26 Figure 25: removeFirst in DoublyLinkedList ................................................................................................. 26 Figure 26: removeElement in DoublyLinkedList........................................................................................... 27 Figure 27: removeLast method in DoublyLinkedList .................................................................................... 28 Figure 28: getFirst method in DoublyLinkedList .......................................................................................... 28 Figure 29: getIndex method in DoublyLinkedList ......................................................................................... 29 Figure 30: getLast method in DoublyLinkedList ........................................................................................... 29 Figure 31: size method in DoublyLinkedList ................................................................................................. 29 Figure 32: isEmpty method in DoublyLinkedList .......................................................................................... 29 Figure 33: Queue .......................................................................................................................................... 31 Figure 34: FIFO .............................................................................................................................................. 31 Figure 35: Fields in Queue ............................................................................................................................ 32 Figure 36: offer method in Queue ................................................................................................................ 33 6 Figure 37: poll method in Queue ................................................................................................................. 33 Figure 39: peek method in Queue ................................................................................................................ 34 Figure 40: size method in Queue ................................................................................................................. 34 Figure 41: isEmpty method in Queue ........................................................................................................... 34 Figure 42: Encapsulation .............................................................................................................................. 35 Figure 43: Discussion .................................................................................................................................... 36 Figure 44: Bubble sort .................................................................................................................................. 37 Figure 45: What Does a Bubble Sort Look Like? .......................................................................................... 38 Figure 46: Bubble Sort .................................................................................................................................. 41 Figure 47: Example of using Bubble Sort...................................................................................................... 41 Figure 48: Result of using Bubble Sort ......................................................................................................... 42 Figure 49: Quick sort .................................................................................................................................... 42 Figure 50: partition code .............................................................................................................................. 45 Figure 51: quickSort code ............................................................................................................................. 45 Figure 52: Using quicksort ............................................................................................................................ 46 Figure 53: The result of using quickSort ....................................................................................................... 46 Figure 54: Dijkstra’s algorithm ..................................................................................................................... 46 Figure 55: Example of Dijkstra Algorithm..................................................................................................... 49 Figure 56: Perform Dijkstra Algorithm ......................................................................................................... 49 Figure 57: Bellman Ford’s algorithm ............................................................................................................ 50 Figure 58: Example of Bellman Ford’s algorithm ......................................................................................... 52 Figure 59: Perform Bellman Ford’s algorithm - First time ........................................................................... 52 Figure 60: Perform Bellman Ford’s algorithm - Second time ....................................................................... 53 7 I/ DATA STRUCTURES 1. Abstract data type (P1) 1.1 Definition Figure 1: Abstract data type model An abstract data type is an abstraction of a data structure that provides only the interface to which the data structure must adhere. The interface does not give any specific details about something should be implemented or in what programming language. In other words, we can say that abstract data types are the entities that are definitions of data and operations but do not have implementation details. In this case, we know the data that we are storing and the operations that can be performed on the data, but we don't know about the implementation details. The reason for not having implementation details is that every programming language has a different implementation strategy for example; a C data structure is implemented using structures while a C++ data structure is implemented using objects and classes. Before knowing about the abstract data type model, we should know about abstraction and encapsulation. Abstraction: It is a technique of hiding the internal details from the user and only showing the necessary details to the user. 10 Figure 2: System design with ADTs 1.2 Example ArrayList is the implementation of ADS list, built atop an array, which is able to dynamically grow and shrink as you add/remove elements, Stores the elements inside an array. Figure 3: ArrayList Problem: A programmer is assigned the task of managing the list of all employees in the company. So he chose ArrayList to do the job, because ArrayList provides what he needs. 11 Figure 4: Fields and add method in ArrayList ArrayList will consist of a list of Objects as elements and size as the size of the arraylist. The add method will take an input parameter. It first checks that if size is equal to the length of the array then the length of the array will be doubled. Then assign to the object with index equal to size + 1 as the element passed. This method will always return True. The Grow method doubles the length of the array. 12 Figure 5: add method in ArrayList Next will be the add method that takes two parameters, the position you want to add and the element. First will check if the index is valid. Next will use the insert method to add the element to the arraylist and return True. Figure 6: insert method in ArrayList The insert method will get the index and the element you want to add. The first step will check that if size is equal to the length of the array then the length of the array will be doubled. First we move the elements after the index to the back using a for loop. Then reassign the position of the last object. The new object will be added to the passed index position and increase the size of the arraylist. 15 Figure 12: indexOf method in ArrayList The indexOf method will take an element. If an element is found in the Array, that index will be returned, otherwise, -1 will be returned; Figure 13: contains method in ArrayList The contains method takes an element as an argument and checks if the element exists in the arraylist. Figure 14: isEmpty method in ArrayList The isEmpty method checks if size is equal to ) and returns True or False 16 Summary:  Boolean add (E element): adds a new element at the end of the sequence and returns true if it is successful This method should also increase the size of the structure and ensure that there is sufficient space for the addition to function. You will need to resize the array if necessary.  Boolean add (int index, E element): The only difference between this and the previous one is that we now have a specific index at which to add (insert) an element. This time, you must validate the index before adding the element and shifting any remaining elements to the right (from the index + 1 to the last index + 1).  E get (int index): The element at the specified index is returned without being removed from the collection. If the index is invalid, throw an IndexOutOfBoundsException with the appropriate message.  E set (int index, E element): sets the element at the given index and returns the previously stored element at that index; again, validate the index and throw IndexOutOfBoundsException if the validation fails.  E remove (int index): removes the element at the specified index and returns it - the same validation as before, but you should already be able to reuse the index validation here.  Int size (): returns the number of elements.  Int indexOf (E element): returns the index of an element if the element is not present in the structure then return -1 as invalid array index.  Boolean contains (E element): returns true or false if the element is present inside the structure.  Boolean isEmpty (): returns if there are elements stored or no. >) UNIVERSITY of GREENWICH ERLE RG tikes ystem.out.println Deiat ess ey ployee employee = ToT TNT Iployee iployee Tae Se iployee TINE rer eed Ee ers Tree Poe Se aap rT treme cea eens Cty Cee rte CU tN Cen ie Piky7-t-30) ployee2) a TST) Pike Pears Dea Dee Nd et eur) pl eo a TST) Petr Oh t-print uals Pears reais OU ae eUpdate) PEAR ret Figure 15: Using ArrayList manage Employee 17 20 Figure 18: How a function calls is implemented with the stack When a program calls a function, a stack frame is typically built on the stack to handle the function's data. Each function generates its own stack frame, which acts as a logical framework for storing parameters, local variables, and other data. The diagram below depicts a conceptual overview of how many stack frames are built. At the top of the stack, data from the current stack frame, which is linked with the most recently called function, is stored. A second stack frame is located beneath the current stack frame and contains the current function. It was the last active stack frame prior to the function call. The first data elements added to the stack frame are parameters, which are followed by the return address, which tells the program location to return once the function closes. Following the return address is an extended base pointer (EBP) address, which is saved on the stack frame to point to the previous frame's base pointer so that it enables stack walking in a debugger and viewing other frames' local variables to work. Specifically, when a function is called and a stack frame is created, the program saves the existing EBP to the stack as a reference to the calling stack frame. The program puts the local variables onto the stack after adding the stored EBP, often together with other sorts of data. Example of function calls with the stack: 21 Figure 19: Example of function calls with the stack Activation record: When a function calls another function, an entry is pushed to the stack. This entry is called as Activation Record. Activation record contains parameters, local variables, and return address that the called function needs to return to the calling function.  On running the program, the main() is called, so an activation record for main() is created and added to the stack.  Now, main() calls f1(), which creates an activation record for f1() on top of stack and f1() calls f2() by adding activation record for f2() on top of stack.  When f2() terminates, its activation record is removed from the stack.  After completing the execution of f1(), it returns by removing the activation record from the stack.  At this stage, we are back to our main() which removes its activation record leading to the termination of the program. 22 2.2 Application of an ADT (P3) - Doubly-Linked Lists Scenario: We are tasked with designing the structure of a web browser. There is a very basic function that every browser has, which is backward and forward navigation of visited web pages, that is a back and forward button. We see these functions as similar to Doubly-Linked Lists, so we'll use it to accomplish this task. Figure 20: Doubly-Linked Lists Definition: Doubly Linked List is a variation of Linked list in which navigation is possible in both ways, either forward and backward easily as compared to Single Linked List. Following are the important terms to understand the concept of doubly linked list. Advantages of Doubly Linked List:  The doubly linked list allows traversing in both forward and backward directions.  Deletion of the nodes can be done easily.  Reversing of linked list is easy.  Insertion can be performed efficiently at any node. Disadvantages of Doubly Linked List:  In a doubly-linked list, each node has an extra pointer which requires extra space.  Doubly linked list operations require more pointers to be handled hence, more time.  Random access to elements is not allowed. Code snippet 25 Figure 23: addIndex in DoublyLinkedList The addIndex method adds an element to a specified position. Check if index = 0 will call addFirst method if index = size will call addLast method and if other than these two cases we will get element before and after index position then assign next and previous of each Node accordingly suitable for inserting a new Node in the middle. 26 Figure 24: addLast in DoublyLinkedList With the addLast method, will first take an element and check if tail is null. If true, then head and tail will be assigned by the element itself. If False, then tail is removed and next is assigned the new element. Then reassign tail with the new element and the previous of that element is the old tail. Figure 25: removeFirst in DoublyLinkedList The removeFirst method will check the validity of the size and then retrieve the head and reassign the head with the next Node. If head is not null, the previous note of head is null. Next we will remove the link of the old Node head and reduce the size. 27 Figure 26: removeElement in DoublyLinkedList The removeElement method will take an element and go through all the elements. If the element is equal to head, then we will call the removeFirst method, if it is with tail, we will call the removeLast method, if the element is found, we will get the Node before and after the element just found and linked together, then delete remove the links between the removed element and reduce the size. 30 Summary:  AddFirst (E element): adds an element in front of the collection and increases the size.  AddLast (E element): adds an element after the last element of the collection and increases the size.  AddIndex(int index ,E element): Add element to index position and increases the size.  E removeFirst (): removes and returns the first element of the collection if there is such if no then throw IllegalStateException with appropriate message.  E removeLast (): removes and returns the last element of the collection if there is such if no then throw IllegalStateException with appropriate message.  removeElement(E element): Removes an element whose value is equal to the element passed in and reduce the size.  E getFirst (): returns but does not remove the first element of the collection if there is such if no then throw IllegalStateException with appropriate message.  E getLast (): returns but does not remove the last element of the collection if there is such if no then throw IllegalStateException with appropriate message.  E getIndex(): Returns the element whose index is equal to the index passed in  Int size (): returns the number of elements inside the collection.  Boolean isEmpty (): returns if the collection contains any elements or not. 2.3 Application of Queue (M1) Scenario: We were tasked with implementing a program to manage movie ticket customers. With the feature that those queuing to get the number first will buy tickets first, those who come later will have to buy tickets later. We find that it makes perfect sense to include the Queue data structure in this program, because it ensures the First In First Out (FIFO) structure. Definition: A queue is defined as a linear data structure that is open at both ends and the operations are performed in First In First Out (FIFO) order. We define a queue to be a list in which all additions to the list are made at one end, and all deletions from the list are made at the other end. The element which is first pushed into the order, the operation is first performed on that. 31 Figure 33: Queue FIFO Principle of Queue:  A Queue is like a line waiting to purchase tickets, where the first person in line is the first person served. (i.e. First come first serve).  Position of the entry in a queue ready to be served, that is, the first entry that will be removed from the queue, is called the front of the queue(sometimes, head of the queue), similarly, the position of the last entry in the queue, that is, the one most recently added, is called the rear (or the tail) of the queue. See the below figure. Figure 34: FIFO Characteristics of Queue:  Queue can handle multiple data.  We can access both ends.  They are fast and flexible. 32 Advantages of Queue:  A large amount of data can be managed efficiently with ease.  Operations such as insertion and deletion can be performed with ease as it follows the first in first out rule.  Queues are useful when a particular service is used by multiple consumers.  Queues are fast in speed for data inter-process communication.  Queues can be used in the implementation of other data structures. Disadvantages of Queue:  The operations such as insertion and deletion of elements from the middle are time consuming.  Limited Space.  In a classical queue, a new element can only be inserted when the existing elements are deleted from the queue.  Searching an element takes O(N) time.  Maximum size of a queue must be defined prior. Figure 35: Fields in Queue 35 3. ADT vs OOP (M3 - D2) 3.1 Using OOP to represent ADT Figure 41: Encapsulation If we now add the word abstract back in we can define an abstract data type (ADT) as a data type, that is a type and the set of operations that will manipulate the type. The set of operations are only defined by their inputs and outputs. The ADT does not specify how the data type will be implemented, all of the ADT's details are hidden from the user of the ADT. This process of hiding the details is called encapsulation. If we extend the example for the integer data type to an abstract data type, the operations might be delete an integer, add an integer, print an integer, and check to see if a certain integer exists. Notice that we do not care how the operation will be done but simply how do invoke the operation. Let's start by looking at traditional programming languages and the data types that they use. Traditional languages are based on text and numerical data types, and you are limited to what kinds of data types that the programming language will support. Variables that are used by the programming language have to be defined using one of the supported data types. An abstract data type is more than a set of values. When used to create an object, it can also have method attached to it, and the details of these methods are hidden from the user. One of the main reasons why hierarchical, network and relational databases are being replaced is their failure to support ADT's. These traditional databases have very strict rules foe the layout of data and simply are not flexible enough to handle ADT's. ADT allows creation of instances with well defined properties and behaviour. Abstraction allows one to collect instances of entities into groups in which their common attributes need to be considered. Example: Suppose you have to make a program to deal with cars and motorbikes. You can define the classes (entities) of Car and Bike and you will see they have much (but not all) functionality in common. It 36 would be a mistake to derive Car from Bike or the other way around. What you need to do is to define a common abstract base-class MotorVehicle and derive both Car and Bike from that class. Data abstraction is an encapsulation of a data type and the subprograms that provide the operations for that type. Programs can declare instances of that ADT, called an object. Object-oriented programming is based on this concept. In object-orientation, ADTs may be referred to as classes. Therefore, a class defines properties of objects which are the instances in an object-oriented environment. ADT and Object oriented Programming are different concepts. OOPs use the concept of ADT. ADTs provide type opaqueness. Thus you have an opaque type (say list_t) and a set of methods (say insert_list, delete_list, create_list) that operate on the opaque type. If that opaque type has multiple representations (say for empty list, full list etc) then each of the methods that operates on that opaque type must account for each of those representation. Advantages of encapsulation and information hiding when using an ADT  Reliability - user code does not depend on specifics of ADT code  Reduces range of code and variables of which the programmer must be aware  Name conflicts are less likely because of smaller scopes  Simplifies the maintenance of the application  Makes the application easier to understand 3.2 Discussion Figure 42: Discussion 37  If classes and inheritance are required rather than optional implementation details, then that version of OOP supports the definition of ADTs.  The names of the messages it receives (the names of its methods in the Simula version) and the values it encapsulates define an object essentially. The behavior of those methods varies; you never know what will happen in response to a message (a method call), though it's reasonable to expect a returned value of a given type.  The values on which it can operate and the operations that can be performed on them define an abstract data type. Inheritance is not included in the concept. Parametric polymorphism is necessary. There is no concept of an object containing its own operations; the semantics of the operations are an essential part of the definition of an ADT and cannot be changed.  CLU - a language created by one of the people who gave ADTs their name and formal definition, designed explicitly to enable programming with ADTs - influenced the design of Java. Java's private methods, final methods, generics, and interfaces enable you to create ADT-like objects. It still does not provide a distinct concept of an ADT; instead, it emerges from the choices you make when defining an abstract class or interface. Conclusion: ADTs are not one of the fundamental concepts underlying OOP. Encapsulation (local retention, protection, and hiding of state-process), late-binding in all things, and messaging are the fundamental concepts of OOP. Therefore, I disagree with the view that mandatory ADTs are the basis for object orientation. Despite the fact that the concept influenced the design of many later languages to which the label "object-oriented" has been applied II/ Algorithms 1. Sorting algorithms (M2) 1.1 Bubble sort Figure 43: Bubble sort 40  Bubble sort may require (n/2) passes and O(n) comparisons for each pass in the average case.  As a result, the average case time complexity of bubble sort is O(n/2 x n) = O(n/2 x n) = O(n/2 x n) = O(n/2 x n) = O (n2). The Space Complexity of the Bubble Sort Algorithm  Bubble sort requires only a fixed amount of extra space for the flag, i, and size variables.  As a result, the space complexity of bubble sort is O. (1).  It is an in-place sorting algorithm, which modifies the original array's elements to sort the given array. Advantages of Bubble Sort Algorithm:  Besides the memory that the array or list occupies, the bubble sort requires very little memory.  The bubble sort is made up of only a few lines of code.  With a best-case running time complexity of O(n), the bubble sort is helpful in determining whether or not a list is sorted. Other sorting methods frequently cycle through their entire sorting sequence, taking O(n2) or O(n log n) time to complete.  The same is true for data sets with only a few items that must be swapped a few times. Disadvantages of Bubble Sort Algorithm  The main disadvantage is the amount of time it takes. It is highly inefficient for large data sets, with a running time of O(n2).  Furthermore, the presence of turtles can significantly slow the sort. Example of Bubble Sort: 41 Figure 45: Bubble Sort As you will see, the first time of the loop we will create a variable "check" with the value false. Next we will iterate to compare each pair of adjacent elements. If the first element is greater than the second, it will execute and reassign the variable "check" with a value of true. Then we will check if "check" is false then the loop ends, else it will continue looping when this break statement or iterate through the number of times equal to the length of the array. Figure 46: Example of using Bubble Sort 42 Figure 47: Result of using Bubble Sort 1.2 Quick sort QuickSort is a Divide and Conquer algorithm. It picks an element as a pivot and partitions the given array around the picked pivot. There are many different versions of quickSort that pick pivot in different ways.  Always pick the first element as a pivot.  Always pick the last element as a pivot (implemented below)  Pick a random element as a pivot.  Pick median as the pivot. The key process in quickSort is a partition(). The target of partitions is, given an array and an element x of an array as the pivot, put x at its correct position in a sorted array and put all smaller elements (smaller than x) before x, and put all greater elements (greater than x) after x. All this should be done in linear time. Figure 48: Quick sort Quick Sort Pivot Algorithm: Based on our understanding of partitioning in quick sort, we will now try to write an algorithm for it, which is as follows.  Step 1: Choose the highest index value has pivot 45 Figure 49: partition code The partition function will take 3 parameters as array and beginIndex and endIndex. First we will perform the assignment of pivot as the last element of the array and the index will be equal to beginIndex - 1 , this is the new pivot value that we will return after this function is done. Next we will iterate through all elements except the last element, if any element is less than pivot will be swapped to index+1 position. After the iteration, we will reset the array with the new pivot index. Figure 50: quickSort code The quickSort function will help us perform a recursion to partition each subarray after it has been split. The function will continue to execute if begin < end. 46 Figure 51: Using quicksort Figure 52: The result of using quickSort 2. Shortest path algorithms (D1) 2.1 Dijkstra’s algorithm Figure 53: Dijkstra’s algorithm 47 Definition Dijkstra’s algorithm is the iterative algorithmic process to provide us with the shortest path from one specific starting node to all other nodes of a graph. It is different from the minimum spanning tree as the shortest distance among two vertices might not involve all the vertices of the graph. It is important to note that Dijkstra’s algorithm is only applicable when all weights are positive because, during the execution, the weights of the edges are added to find the shortest path. And therefore if any of the weights are introduced to be negative on the edges of the graph, the algorithm would never work properly. However, some algorithms like the Bellman-Ford Algorithm can be used in such cases. It is also a known fact that breadth-first search(BFS) could be used for calculating the shortest path for an unweighted graph, or for a weighted graph that has the same cost at all its edges. But if the weighted graph has unequal costs at all its edges, then BFS infers uniform-cost search. Now what? Instead of extending nodes in order of their depth from the root, uniform-cost search develops the nodes in order of their costs from the root. And a variant of this algorithm is accepted as Dijkstra’s Algorithm. Generally, Dijkstra’s algorithm works on the principle of relaxation where an approximation of the accurate distance is steadily displaced by more suitable values until the shortest distance is achieved. Also, the estimated distance to every node is always an overvalue of the true distance and is generally substituted by the least of its previous value with the distance of a recently determined path. It uses a priority queue to greedily choose the nearest node that has not been visited yet and executes the relaxation process on all of its edges. How to Implement the Dijkstra Algorithm? Before proceeding the step by step process for implementing the algorithm, let us consider some essential characteristics of Dijkstra’s algorithm;  Basically, the Dijkstra’s algorithm begins from the node to be selected, the source node, and it examines the entire graph to determine the shortest path among that node and all the other nodes in the graph. The algorithm maintains the track of the currently recognized shortest distance from each node to the source code and updates these values if it identifies another shortest path. 50 We add point A when filling in the column for the purpose of saving it to use for the next steps and retrieve path for the final step. After doing above step we will compare distance between 3 points B, C and D then take the point with shortest distance and make it new current distance of neighboring point and mark the current point as visited, here that point is point B. If all points are marked, the algorithm will end, but in this case we have 4 unmarked C D E F points, so we have to continue. We will continue to perform the same next steps as we did above. There is a note that when measuring the new distance, if the new distance is less than the old distance of that point to the current point, the old distance will be updated. Results obtained after completing the above steps:  Shortest distance from A to B: A -> B= 3  Shortest distance from A to C: A -> C = 5  The shortest distance from A to D: A -> B -> D = 7  The shortest distance from A to E: A -> B -> D –> E = 9  The shortest distance from A to F: A -> B -> D -> F = 9 2.2 Bellman Ford’s algorithm Figure 56: Bellman Ford’s algorithm Definition 51 Bellman ford algorithm is a single-source shortest path algorithm. This algorithm is used to find the shortest distance from the single vertex to all the other vertices of a weighted graph. There are various other algorithms used to find the shortest path like Dijkstra algorithm, etc. If the weighted graph contains the negative weight values, then the Dijkstra algorithm does not confirm whether it produces the correct answer or not. In contrast to Dijkstra algorithm, bellman ford algorithm guarantees the correct answer even if the weighted graph contains the negative weight values. Steps for finding the shortest distance to all vertices from the source using the Bellman-Ford algorithm  This step initializes distances from the source to all vertices as infinite and distance to the source itself as 0. Create an array dist[] of size |V| with all values as infinite except dist[src] where src is source vertex.  This step calculates shortest distances. Do following |V|-1 times where |V| is the number of vertices in given graph. Do following for each edge u-v  If dist[v] > dist[u] + weight of edge uv, then update dist[v] to  dist[v] = dist[u] + weight of edge uv  This step reports if there is a negative weight cycle in the graph. Again traverse every edge and do following for each edge u-v ……If dist[v] > dist[u] + weight of edge uv, then “Graph contains negative weight cycle”. The idea of step 3 is, step 2 guarantees the shortest distances if the graph doesn’t contain a negative weight cycle. If we iterate through all edges one more time and get a shorter path for any vertex, then there is a negative weight cycle Time Complexity: O(V * E), where V is the number of vertices in the graph and E is the number of edges in the graph Auxiliary Space: O(E) Notes:  Negative weights are found in various applications of graphs. For example, instead of paying the cost for a path, we may get some advantage if we follow the path.  Bellman-Ford works better (better than Dijkstra’s) for distributed systems. Unlike Dijkstra’s where we need to find the minimum value of all vertices, in Bellman-Ford, edges are considered one by one.  Bellman-Ford does not work with an undirected graph with negative edges as it will be declared as a negative cycle. Example: Find the shortest path from vertex A to other vertices. 52 Figure 57: Example of Bellman Ford’s algorithm Figure 58: Perform Bellman Ford’s algorithm - First time First we will initialize the vertices and choose the starting point as the vertex A will have a distance of 0 the remaining vertices will be infinity. Next we will list the consecutive edges that form a column as the index of each row.
Docsity logo



Copyright © 2024 Ladybird Srl - Via Leonardo da Vinci 16, 10126, Torino, Italy - VAT 10816460017 - All rights reserved