0% found this document useful (0 votes)
24 views30 pages

DS Complete Notes IMG Mar 2023

Uploaded by

jamal6381629068
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
24 views30 pages

DS Complete Notes IMG Mar 2023

Uploaded by

jamal6381629068
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 30
Department of Computer Science - Data Structure Complete Notes memory locations. The first element is stored at the smallest memory location ‘The idea is to store multiple items of the same type together. Each element is of same data type and carries a same size Elements of the array can be randomly accessed since we can calculate the address of each element Array Representatioi Arrays can be declare array is of same data type and carries the same size We can declare an array as Example int array [10] = { 35, 33, 42, 10, 14, 19, 27, 44, 26, 31 } 4 Type As per the above example, following are the important points to be considered. elements | 96 || 33 || 42 || 10 | 14 || 19 || 27 || 44 || 26 | 91 index ‘Two Dimensional Array: ‘The two-dimensional array can be defined as an array of arrays. The 2D array is organized as matrices which can be represented as the collection of rows and columns. The syntax to declare the 2D array is Example: Here, 4 is the number of rows, and 3 is the number of columns Basic Operations Following are the basic operations supported by an array. ‘+ Traverse ~ print all the array elements one by one. «Insertion ~ Adds an element at the given index. + Deletion - Deletes an element at the given index. * Search ~ Searches an element using the given index or by the value. + Update ~ Updates an element at the given index Advantages Name ements Array An array is a collection of similar data items stored at contiguous (nearby) various ways in different languages. Each element of an data_type array_namelarray_size]; int marks[5]; 4 t + Index starts with 0. * Array length is 10 which means it can store 10 elements. + _ Each element can be accessed via its index. For example, we can fetch an element at index 5 as 19 0123 45 6789 + Size :10 data_type array_name|rows}[columns]; int a[4][3]; Array provides the single name for the group of variables of the same type therefore, it is easy to remember the name of all the elements of an array ‘Traversing an array is a very simple process, we just need to increment the address of the array in order to visit each element one by one. ‘Any element in the array can be directly accessed by using the index Department of Computer Science - Data Structure Complete Notes STACK It is type of linear data structure. It follows LIFO (Last In First Out) property. It has only one pointer TOP that points the last or top most element of Stack. Insertion and Deletion in stack can only be done from top only. Insertion in stack is also known as a PUSH operation. Deletion from stack is also known as POP operation in stack. To use a stack efficiently, we need to check the status of stack as well. For the same purpose, the following functionality is added to stacks + peek) - get the top data element of the stack, without removing it. + isFull) ~ check if stack is full. + isEmpty() - check if stack is empty Push Operation The process of putting a new data element onto stack is known as a Push Operation. Push operation involves a series of steps — + Step 1 - Checks if the stack is full. + Step 2 - If the stack is full, produces an error and exit + Step 3 - If the stack is not full, increments top to point next empty space + Step 4 - Adds data element to the stack location, where top is pointing. + Step 5 ~ Returns success. orithm for PUSH Ope: ion 1, If (TOP == MAX) Then [Check for overflow] 2. Print: Overflow 3. Else 4. Set TOP = TOP + 1 [Increment TOP by 1] 5. Set STACK[TOP] - ITEM [Assign ITEM to top of STACK] 6. Print: ITEM inserted [End of If] ay Pop Operation Push / Pop Accessing the content —_while a = removing it from the stack, is known as a posse — Pop Operation. In an array implementation oo of pop|) operation, the data element is not Stack Stack actually removed, instead top is decremented to a lower position in the stack to point to the next value. Department of Computer Science ~ Data Structure Complete Notes A Pop operation may involve the following steps - Step 1 - Checks if the stack is empty. Step 2 - If the stack is empty, produces an error and exit. Step 3 ~ If the stack is not empty, accesses the data element at which top is pointing, Step 4 - Decreases the value of top by 1. Step 5 ~ Returns success. Algorithm for Pop Operation 1. If (TOP. 0) Then [Check for underflow] 2. Print: Underflow 3. Else 4. Set ITEM = STACK[TOP] [Assign top of STACK to ITEM] 5. Set TOP = TOP - 1 [Decrement TOP by 1] 6. Print: ITEM deleted [End of If] 7. Exit Applications of Stack Conversion of polish notations. There are three types of notations: > Infix notation - Operator is between the operands : x + y > Prefix notation - Operator is before the operands : + xy > Postfix notation - Operator is after the operands : xy + To reverse a string. A string can be reversed by using stack. Used in many algorithms like Tower of Hanoi, tree traversals, stock span problem, histogram problem. Other applications can be Backtracking, Knight tour problem, rat in a maze, N queen problem and sudoku solver Department of Computer Science - Data Structure Complete Notes QUEUE It is a linear data structure. It is considered as sequence of items. It supports FIFO (First In First Out) property. It has three components: © Container of items that contains elements of queue. © Apointer front that points the first item of the queue. © Apointer rear that points the last item of the queue Insertion is performed from REAR end. Deletion is performed from FRONT end. Insertion operation is also known as ENQUEUE in queue £ » in| Data | | Data} (oo Da Dat Data | Out os ly Last in Last ut Fist nist Out Queue operations may involve initializing or defining the queues. Some of the basic operations associated with queues enqueue() ~ add (store) an item to the queue. dequeue() ~ remove (access) an item from the queue. Few more functions are required to make the above-mentioned queue operation efficient. These are - peek() ~ Gets the element at the front of the queue without removing it. isfull() - Checks if the queue is full. isempty() ~ Checks if the queue is empty. Engueue Operation Queues maintain two data pointers, front and rear. Therefore, its operations are comparatively difficult to implement than that of stacks. The following steps should be taken to enqueue (insert) data into a queue ~ Step 1 - Check if the queue is full Step 2 - If the queue is full, produce overflow error and exit. Step 3 - If the queue is not full, increment rear pointer to point the next empty space. Step 4 - Add data element to the queue location, where the rear is pointing Step 5 - return success. Department of Computer Science ~ Data Structure Complete Notes “ or Rear ay Queue Enqueue Algorithm for Enqueue operation If (REAR == N) Then [Check for overflow] 2. Print: Overflow 3. Else 4. If FRONT and REAR (a) Set FRONT = 1 (b) Set REAR = 1 5. Else 6. Set REAR = REAR + 1 [Increment REAR by 1] [End of Step 4 If] 7. QUEUE|REAR] 8. Print: ITEM inserted [End of Step 1 If] 9. Exit ) Then [Check if QUEUE is empty] = ITEM Dequeue Operation Accessing data from the queue is a process of two tasks - access the data where front is pointing and remove the data after access. The following steps are taken to perform dequeue operation ~ = Step 1 ~ Check if the queue is empty. + Step 2 ~ If the queue is empty, produce underflow error and exit. + Step 3 - If the queue is not empty, access the data where front is pointing. + Step 4 ~ Increment front pointer to point to the next available data element. + Step 5 - Return success. Department of Computer Science ~ Data Structure Complete Notes on rip ee ne ater ° e 2 dequeue Queue Queue Dequeue Algorithm for Dequeue operation 1. If (FRONT == 0) Then [Check for underflow] 2. Print: Underflow 3. Else 4. ITEM = 5. REAR) Then [Check if only one element is left] (a) Set FRONT = 0 (b) Set REAR = 0 6. Else 7. Set FRONT = FRONT + 1 [Increment FRONT by 1] [End of Step 5 If] 8. Print: ITEM deleted [End of Step 1 If] 9. Exit Queue Application: + In real life, Call Center phone systems will use Queues, to hold people calling them in an order, until a service representative is free. * Serving requests on a single shared resource, like a printer, CPU task scheduling ete + Cashier line in any store + people on an escalator Department of Computer Science ~ Data Structure Complete Notes Infix and Postfix Expression The way to write arithmetic expression is known as a notation. An arithmetic expression can be written in three different notations, i.e., without changing the output of an expression. An expression consists of constants, variables, and symbols. Symbols can be operators or parenthesis. All these components must be arranged according to a set of rules. These notations are + Infix Notation + Prefix (Polish) Notation ‘+ Postfix (Reverse-Polish) Notation Infix Notation We write expression in infix notation, e.g, a - b + c, where operators are used in-between operands. An algorithm to process infix notation could be difficult and costly in terms of time and space consumption. Prefix Notation In this notation, operator is prefixed to operands, i.e. operator is written ahead of operands. For example, +ab. Prefix notation is also known as Polish Notation. Postfix Notation This notation style is known as Reversed Polish Notation. The postfix expression is an expression in which the operator is written after the operands. For example, the postfix expression of infix notation (2+3 ) can be written as 23+ ‘The following table are some of the examples of all three notations Sr.No. Infix Notation Prefix Notation Postfix Notation 1 at+b +ab abt 2 (atbjec +tabe abte+ 3 as (b+o) satbe abcte 4 a/btc/d +fab/ed ab/ed/+ 5 fatb)e(ctd) stabted abtcdt« 6 (atb)eq)-d -++abed abteed- Department of Computer Science - Data Structure Complete Notes Sr.No. Operator Precedence _—Associativity 1 Exponentiation * Highest Right Associative 2 Multiplication (=) & Division (/) Second Highest Left Associative Addition (+) & Subtraction (~) Lowest Left Associative ‘The above table shows the default behaviour of operators and their priority. At any point of time in expression evaluation, the order can be altered by using parenthesis. Infix to Postfix Expression To convert infix expression to postfix expression, we will use the stack data structure. By scanning the infix expression from left to right, when we will get any operand, simply add them to the postfix form, and for the operator and parenthesis, add them in the stack maintaining the precedence of them. Print the operand as they arrive. If the stack is empty or contains a left parenthesis on top, push the incoming operator on to the stack, If the incoming symbol is '(, push it on to the stack. If the incoming symbol is ', pop the stack and print the operators until the left parenthesis is found. If the incoming symbol has higher precedence than the top of the stack, push it on the stack. If the incoming symbol has lower precedence than the top of the stack, pop and print the top of the stack. Then test the incoming operator against the new top of the stack. If the incoming operator has the same precedence with the top of the stack then use the associativity rules. If the associativity is from left to right then pop and print the top of the stack then push the incoming operator. If the associativity is from right to left then push the incoming operator. At the end of the expression, pop and print all the operators of the stack Department of Computer Science - Data Structure Complete Notes Cirew ue Circular Queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle and the last position is connected back to the first position to make a circle. Circular queue avoids the wastage of space in a regular queue implementation using arrays. In a normal Queue Data Structure, we can insert elements until queue becomes full. But once the queue becomes full, we cannot insert the next element until all the elements are deleted from the queue. For example, consider the queue below. Queue is Full “[-[-T-I-T-T- Front Rear When we dequeue any element to remove it from the queue, we are actually moving the front of the queue forward, thereby reducing the overall size of the queue And we cannot insert new elements, because the rear pointer is still at the end of the queue. The only way is to reset the linear queue, for a fresh start Queue is Full (Even after removing 2 elements) Aa Le] a Operations on Circular Qué «Initially, the head and the tail pointers will be pointing to the same location, this would mean that the queue is empty. + New data is always added to the location pointed by the tail pointer, and once the data is added, tail pointer is incremented to point to the next available location. «The head and the tail pointer will get reinitialised to 0 every time they reach the end of the queue. + Also, the head and the tail pointers can cross each other. In other words, head pointer can be greater than the tail. Sounds odd? This will happen when we dequeue the queue a couple of times and the tail pointer gets reinitialised upon reaching the end of the queue. + The figure shows the structure of circular queue. It stores an element in a circular way and performs the operations according to its FIFO structure. Department of Computer Science - Data Structure Complete Notes Had Tal-0 ho ~ ers > SOSL Cey OC EnQueue and Dequeue oper: n_ in the Circular Queue * Two pointers called FRONT and REAR are used to keep track of the first and last elements in the queue. * When initializing the queue, we set the value of FRONT and REAR to -1. * Onenqueing an element, we circularly increase the value of REAR index and place the new element in the position pointed to by REAR. * On dequeueing an element, we return the value pointed to by FRONT and circularly increase the FRONT index. + Before enqueing, we check if queue is already full, * Before dequeuing, we check if queue is already empty. + When enqueing the first element, we set the value of FRONT to 0. * When dequeing the last element, we reset the values of FRONT and REAR to 1 0) Then [Check if QUEUE is empty] (a) Set FRONT = 1 (b) Set REAR = 1 5. Else If (REAR == N) Then [If REAR reaches end if QUEUE] 6. Set REAR = 1 7. Else 8. Set REAR = REAR + 1 [Increment REAR by 1] [End of Step 4 If] 9. Set QUEUE|REAR] = ITEM 10. Print: ITEM inserted [End of Step 1 If] 11. Exit Department of Computer Science ~ Data Structure Complete Notes Algorithm for Dequeue in Circular Queue 1. If (FRONT == 0) Then [Check for Underflow] 2. Print: Underflow 3. Else 4. ITEM = QUEUE|FRONT| 5. If (FRONT == REAR) Then [If only element is left] (a) Set FRONT = 0 (b) Set REAR = 0 6. Else If (FRONT == N) Then [If FRONT reaches end if QUEUE] 7. Set FRONT = 1 8. Else 9, Set FRONT = FRONT + 1 [Increment FRONT by 1] [End of Step 5 If] 10. Print: ITEM deleted [End of Step 1 if] 11. Exit Linear Queue Applications: * Queue is used in model real-world situations such as people waiting in line at a bank, airplanes waiting to take off, or data packets waiting to be transmitted over the Internet. * There are various queues quietly doing their job in your computer's (or the network's) operating system. + There's a printer queue where print jobs wait for the printer to be available. * Stores, reservation centres, and other similar services typically process customer requests according to the FIFO principle. Department of Computer Science - Data Structure Complete Notes Singly Linked List Singly linked list is a collection of nodes linked together in a sequential way where each node of singly linked list contains a data field and an address field which contains the reference of the next node. In a singly-linked list, every element contains some data and a link to the next element. The elements of a linked list are called the nodes. A node has two fields ive. data and next. The data field contains the data being stored in that specific node. ‘The next field contains the address of the next node. So this is the place where the link between nodes is established. No matter how many nodes are present in the linked list, the very first node is called head and the last node is called the tail. If there is just one node created then it is called both head and tail. A node is a collection of two sub-elements or parts. A data part that stores the element and a next part that stores the link to the next node. A linked list is formed when many such nodes are linked together to form a chain Each node points to the next node present in the order. ‘The first node is always used as a reference to traverse the list and is called HEAD. The last node points to NULL. 7 ee eo Advantages of Linked Lists * They are a dynamic in nature which allocates the memory when required. ‘+ Linked lists are used to implement stacks, queues, graphs, ete. ‘+ Linked lists let you insert elements at the beginning and end of the list. ‘* In Linked Lists we don't need to know the size in advance. + Insertion and deletion operations can be easily implemented. * Stacks and queues can be easily executed. ‘+ Linked List reduces the access time. Disadvantages of Linked Lists + The memory is wasted as pointers require extra memory for storage. ‘+ No element can be accessed randomly; it has to access each node sequentially. * Reverse Traversing is difficult in linked list. Inserting in a singly linked list «Inserting at beginning «Inserting at the end «Inserting at any position Department of Computer Science ~ Data Structure Complete Notes Insertinj the beginning Insertion of a new node is quite simple. It is just a 2-step algorithm which is performed to insert a node at the start of a singly linked list. Create a new node, say newNode points to the newly created node. Link the newly created node with the head node, ie. the newNode will now point to head node Make the new node as the head node, i.e. now head node will point to newNode New node should be connected to the first node, which means the head. This can be achieved by putting the address of the head in the next field of the new node. New node should be considered as a head. It can be achieved by declaring head equals to a new node Inserting at the end Create a new node and make sure that the address part of the new node points to NULL i.e. newNode->next=NULL ‘Traverse to the last node of the linked list and connect the last node of the list with the new node, ie. last node will now point to new node. (lastNode->next = newNode) ‘The insertion of a node at the end of a linked list is the same as we have done in node creation function. Set the next pointer of the new node to be NULL. Last node of the existing node is linked with the newnode, ie. , the last node’s(existing) nextpointer points to the new node Department of Computer Science ~ Data Structure Complete Notes Inserting at any position In this case, we don’t disturb the head and tail nodes. Rather, a new node is inserted between two consecutive nodes. We call one node as current and the other as previous, and the new node is placed between them. Such case can be done using following steps: * Move the current pointer upto the position where node to be inserted. «Store current next pointer address to tmp_node next. «Store tmp_node address to current next. ME Et ae Deleting in a singly linked list Linked lists provide us the great feature of deleting a node. The process of deletion is also easy to implement. The basic structure is to declare a temporary pointer which points the node to be deleted. There are also three cases in which a node can be deleted «Deleting at beginning « Deleting at the end « Deleting at any position Deleting at beginning In this case, the first node of the linked list is deleted. The first node is called the head. So, we are going to delete the head node. The process of deletion includes «Copy the address of first node ie. head node to some temp variable say to Delete. «Move the head to the second node of the linked list i.e. head = head->next * Disconnect the connection of first node to second node. Department of Computer Science ~ Data Structure Complete Notes Deleting at the en In this case, the last node of the linked list is deleted. We also need access to the second to the last node of the linked list as we will delete the last node and make the previous node as the tail of linked list. + Traverse to the last node of the linked list keeping track of the second last node in some temp variable say secondLastNode «If the last node is the head node then make the head node as NULL else disconnect the second last node with the last node i.e. secondLastNode->next = NULL. he Srna la bole Deleting at any position: ‘The process of deletion is simple. Here we don’t use the head and tail nodes. We ask the user to input the position of the node to be deleted. After that, we just move two temporary pointers through the linked list until we reach our specific node. Now, we delete our current node and pass the address of the node after it to the previous pointer. ‘+ Traverse to the n® node of the singly linked list and also keep reference of n-1'* node in some temp variable say prevnode + Reconnect the n-1 node with the n+1 node ie. prevNode->next = toDelete- >next «Free the memory occupied by the n> node i. nt . toDelete node. Poe ee, Ei-ER aataede seIande Dr R N MUHAMMAD Department of Computer Science - Data Structure Complete Notes Doubly linked Lis Doubly linked list is a collection of nodes linked together in a sequential way. Each node of the list contains two parts (as in singly linked list) data part and the reference or address part. The basic structure of node is shown in the below image. Data Nate Doubly linked list is almost similar to singly linked list except it contains two address or reference fields, where one of the address field contains reference of the next node and other contains reference of the previous node. Doubly linked list is sometimes also referred as bi-directional linked list since it allows traversal of nodes in both direction. The basic diagram of a doubly linked list is shown below ea | fast Advantages of Doubly linked list: As like singly linked list it is the easiest data structures to implement. Doubly linked list can be used in navigation systems where both front and back navigation is required. It is used by browsers to implement backward and forward navigation of visited web pages i.e. back and forward button It is also used by various application to implement Undo and Redo functionality. Allows traversal of nodes in both direction which is not possible in singly linked list. Deletion of nodes is easy when compared to singly linked list Reversing the list is simple and straightforward. It is one of most efficient data structure to implement when traversing in both direction is required. Disadvantages of Doubly linked list: It uses extra memory when compared to array and singly linked list. Since elements in memory are stored randomly, hence elements are accessed sequentially no direct access is allowed. Department of Computer Science ~ Data Structure Complete Notes Insertion in doubly Linked List * Traverse to N-1 node in the list. Where N is the position to insert. Say temp now points to N-1th node. ‘Create a newNode that is to be inserted and assign some data to its data field. * Connect the next address field of newNode with the node pointed by next address field of temp node. + Connect the previous address field of newNode with the temp node. * Check if temp->next is not NULL then, connect the previous address field of node pointed by temp.next to newNode. * Connect the next address field of temp node to newNode i.e. temp->next will now point to newNode. Deletion in doubly Linked List tend + Traverse to Nth node of the linked list, lets say a pointer current points to Nth node in our case 2 node * Link the node behind current node with the node ahead of current node, which means now the N-1th node will point to N+1th node of the list * If N+ ith node is not NULL then link the N+1th node with N-1th node is the previous address field of N+1th node will point to N-1th node. * Finally delete the current node from memory now Dr R N MUHAMMAD ILYAS Department of Computer Science - Data Structure Complete Notes Tree Traversal Traversal is a process to visit all the nodes of a tree and may print their values too. Because, all nodes are connected via edges (links) we always start from the root (head) node. That is, we cannot randomly access a node in a tree. There are three ways which we use to traverse a tree. They are * Inorder Traversal: (Left, Root, Right) Root, Left, Right) © Post-order Traversal: (Left, Right, Root) © Pre-order Travers In-Order Traversal: ‘This technique follows the ‘left root right’ policy. It means that first left subtree is visited after that root node is traversed, and finally, the right subtree is traversed. As the root node is traversed between the left and right subtree, it is named In-Order traversal. So, in the In-Order traversal, each node is visited in between of its subtrees. «First, visit all the nodes in the left subtree + Then the root node «Visit all the nodes in the right subtree Pre-Order Traversal: ‘This technique follows the ‘root left right’ policy. It means that, first root node is visited after that the left subtree is traversed recursively, and finally, right subtree is recursively traversed. As the root node is traversed before (or pre) the left and right subtree, it is called Pre-Order traversal. So, in a Pre-Order traversal, each node is visited before both of its subtrees. «Visit root node ‘+ Visit all the nodes in the left subtree «Visit all the nodes in the right subtree Post-Order Traversal: This technique follows the ‘left-right root’ policy. It means that the first left subtree of the root node is traversed, after that recursively traverses the right subtree, and finally, the root node is traversed. As the root node is traversed after (or post) the left and right subtree, it is called Post-Order traversal. So, in a Post-Order traversal, each node is visited after both of its subtrees + Visit all the nodes in the left subtree «Visit all the nodes in the right subtree Visit the root node Department of Computer Science - Data Structure Complete Notes Department of Computer Science - Data Structure Complete Notes Graph * A Graph is a non-linear data structure consisting of nodes and edges. * The nodes are sometimes also referred to as vertices and the edges are lines or ares that connect any two nodes in the graph. * A graph is a pictorial representation of a set of objects where some pairs of objects are connected by links. * Graphs are used to solve many real-life problems. Graphs are used to represent networks, The networks may include paths in a city or telephone network or circuit network. * The interconnected objects are represented by points termed as vertices, and the links that connect the vertices are called edges. + A Graph consists of a finite set of vertices (or nodes) and set of Edges which connect a pair of nodes. Vertices In the above Graph, the set of vertices V = (0, 1, 2, 3, 4} and the set of edges E (0& 1, 1&2, 2&3,3&4,064, 1&4, 1&3) Directed and Undirected graph A graph can be directed or undirected. However, in an undirected graph, edges are not associated with the directions with them. If an edge exists between vertex A and B then the vertices can be traversed from B to A as well as A to B. An undirected Directed Graph In a directed graph, edges form an ordered pair. Edges represent a specific path from some vertex A to another vertex B. Node A is called initial node while node B is called terminal node. Department of Computer Science - Data Structure Complete Notes Graph Terminology Vertex: Each node of the graph is represented as a vertex. In the following example, the labeled circle represents vertices. Thus, A to G are vertices. We can represent them using an array as shown in the following image. Here A can be identified by index 0. B can be identified using index 1 and so on. Edge: Edge represents a path between two vertices or a line between two vertices. In the following example, the lines from A to B, B to C, and so on represents edges. We can use a two-dimensional array to represent an array as shown in the following image. Here AB can be represented as 1 at row 0, column 1, BC as 1 at row 1, column 2.and so on, keeping other combinations as 0. Adjaceney: Two node or vertices are adjacent if 5 b they are connected to each other through an edge. In the following example, B is adjacent to A, Cis adjacent to B, and so on. Path: Path represents a sequence of edges between the two vertices. In the following @ d e example, ABCD represents @ path from A to D. A path can be defined as the sequence of nodes that are followed in order to reach some terminal node V from the initial node U Closed Path: A path will be called as closed path if the initial node is same as terminal node. A path will be closed path if Simple Path: If all the nodes of the graph are distinct with an exception VO=VN, then =VN. such path P is called as closed simple path Cycle: A cycle can be defined as the path which has no repeated edges or vertices except the first and last vertices. Connected Graph: A connected graph is the one in which some path exists between every two vertices (u, v] in V. There are no isolated nodes in connected graph. Complete Graph: A complete graph is the one in which every node is connected with all other nodes. A complete graph contain n(n-1)/2 edges where n is the number of nodes in the graph. Weighted Graph: In a weighted graph, each edge is assigned with some data such as length or weight. The weight of an edge € can be given positive value indicating the cost of traversing the edge. Degree of the Node: A degree of a node is the number of edges that are connected with that node. A node with degree 0 is called as isolated node. Department of Computer Science - Data Structure Complete Notes Graph Representatio: A graph representation is a technique to store graph into the memory of computer. * To represent a graph, we just need the set of vertices, and for each vertex the neighbors of the vertex (vertices which is directly connected to it by an edge). If it is @ weighted graph, then the weight will be associated with each edge * There are other representations also like, Incidence Matrix and Incidence List. ‘The choice of graph representation is situation-specific. It totally depends on the type of operations to be performed and ease of use. * There are different ways to optimally represent a graph, depending on the density of its edges, type of operations to be performed and ease of use. © The following two are the most commonly used representations of a graph. + Adjacency Matrix © Adjacency List Adjacency matrix is a sequential representation. It is used to represent which nodes are adjacent to each other. ie, is there any edge connecting nodes to a graph. Adjacency Matrix is a 2D array of size V x V where V is the number of vertices in a graph. Let the 2D array be adifj[], a slot adil vertex i to vertex j. Adjacency matrix for undirected graph is always symmetric. 1 indicates that there is an edge from Adjacency Matrix is also used to represent weighted graphs. If adjjjlj] = w, then there is an edge from vertex i to vertex j with weight w. Adjacency List: Adjacency list is a linked representation. In this representation, for each vertex in the graph, we maintain the list of its neighbors. It means, every vertex of the graph contains list of its adjacent vertices. We have an array of vertices which is indexed by the vertex number and for each vertex v, the corresponding array element points to a singly linked list of neighbors of v. An array of lists is used. The size of the array is equal to the number of vertices. Let the array be an array |]. An entry arrayli] represents the list of vertices adjacent to the ith vertex. This representation can also be used to represent a weighted graph. The weights of edges can be represented as lists of pairs. Department of Computer Science ~ Data Structure Complete Notes Basic operation of graph ‘Add/Remove Vertex: ‘This is the simplest operation in the graph. You simply add a vertex to a graph It need not be connected to any other vertex through an edge. However, you must remove all edges originating from and ending at the deleted vertex when removing a vertex. We cannot successfully remove a vertex if we do not remove all the edges incident on the vertex. Once we remove the vertex then the adjacency matrix will not contain the row and column for the corresponding vertex. ‘This operation changes the vertex set and the edge family of the graph. Add/Remove Edge: This operation adds or removes an edge between two vertices. When all the edges originating from and ending at a vertex are deleted, the vertex becomes isolated. Adding an edge to a graph can be done by connecting two given vertices. Deleting an edge can be done by removing the connection between the given vertices. I am not putting any image as it is very trivial operation: Department of Computer Science - Data Structure Complete Notes ph Traversal Graph traversal is a technique used for searching a vertex in a graph. The graph traversal is also used to decide the order of vertices is visited in the search process. A graph traversal finds the edges to be used in the search process without creating loops. That means using graph traversal we visit all the vertices of the graph without getting into looping path. There are two graph traversal techniques and they are as follows. ‘+ DFS (Depth First Search) + BFS (Breadth First Search) Breadth-First Search (BFS): This is a traversal operation in the graph. BFS horizontally traverses the graph ‘This means that it traverses all the nodes at a single level before proceeding to the next level. The BFS algorithm starts at the top of the first node in the graph and then traverses all the adjacent nodes to it. Once all the adjacent nodes are traversed, the algorithm repeats the same procedure for child nodes DFS traversal of a graph produces a spanning tree as final result. Spanning ‘Tree is a graph without loops. We use Stack data structure with maximum size of total number of vertices in the graph to implement DFS traversal. We use the following steps to implement DFS traversal... * Step 1 - Define a Stack of size total number of vertices in the graph * Step 2 - Select any vertex as starting point for traversal. Visit that vertex and push it on to the Stack. * Step 3 - Visit any one of the non-visited adjacent vertices of a vertex which is at the top of stack and push it on to the stack. * Step 4 - Repeat step 3 until there is no new vertex to be visited from the vertex which is at the top of the stack. * Step 5 - When there is no new vertex to visit then use back tracking and pop one vertex from the stack. * Step 6 - Repeat steps 3, 4 and 5 until stack becomes Empty. * Step 7 - When stack becomes Empty, then produce final spanning tree by removing unused edges from the graph Department of Computer Science - Data Structure Complete Notes ‘Traversing the above graph in BFS fashion would result from A -> B > C -> D - > E-> F > G. The algorithm starts from node A and traverses alll its adjacent nodes B, C and D. It marks all the four nodes as. ited. Once all the adjacent nodes of A are traversed, the algorithm moves to the first adjacent node of A and repeats the same procedure. In this case, the node is B, and the adjacent nodes to B are E and F. Next, the adjacent nodes to C are traversed. Once all the nodes are visited, the operation ends. Depth First Search (DFS): Depth First Search or DFS traverses the graph vertically. It starts with the root node or the first node of the graph and traverses all the child nodes before moving to the adjacent nodes. BFS traversal of a graph produces a spanning tree as final result. Spanning Tree is a graph without loops. We use Queue data structure with maximum size of total number of vertices in the graph to implement BFS traversal. We use the following steps to implement BFS traversal... + Step 1 - Define a Queue of size total number of vertices in the graph. «Step 2 - Select any vertex as starting point for traversal. Visit that vertex and insert it into the Queue. * Step 3 - Visit all the non-visited adjacent vertices of the vertex which is at front of the Queue and insert them into the Queue. * Step 4 - When there is no new vertex to be visited from the vertex which is at front of the Queue then delete that vertex. «Step 5 - Repeat steps 3 and 4 until queue becomes empty. * Step 6 - When queue becomes empty, then produce final spanning tree by removing unused edges from the graph ‘Traversing the above graph in BFS fashion would result from A -> B-> E-> F > C -> G -> D. The algorithm starts from node A and traverses all its child nodes. As soon as it encounters B, it seems that it has further child nodes. So, the child nodes of Bare traversed before proceeding to the next child node of A. Department of Computer Science - Data Structure Complete Notes Hashing Techniques Hashing is the process of mapping large amount of data item to smaller table with the help of hashing function. Hashing is also known as Hashing Algorithm or Message Digest Function. It is a technique to convert a range of key values into a range of indexes of an array. It is used to facilitate the next level searching method when compared with the linear or binary search. Hashing is one of the searching techniques that uses a constant time. The time complexity in hashing is O(1) Hashing allows to update and retrieve any data entry in a constant time O(1), Constant time O(1) means the operation does not depend on the size of the data. Hashing is used with a database to enable items to be retrieved more quickly. It is used in the encryption and decryption of digital signatures. Thus, it becomes a data structure in which insertion and search operations are very fast irrespective of the size of the data. Hash Table uses an array as a storage medium and uses hash technique to generate an index where an element is to be inserted or is to be located from. Hash table is one of the most important data structures that uses a special function known as a hash function that maps a given value with a key to access the elements faster. Hash Table is a data structure which stores data in an associative manner. In a hash table, data is stored in an array format, where each data value has its own unique index value. Access of data becomes very fast if we know the index of the desired data Hash Function A fixed process converts a key to a hash key is known as a Hash Function. ‘This function takes a key and maps it to a value of a certain length which is called a Hash value or Hash, Hash value represents the original string of characters, but it is normally smaller than the original. It transfers the digital signature and then both hash value and signature are sent to the receiver. Receiver uses the same hash function to generate the hash value and then compares it to that received with the message. If the hash values are same, the message is transmitted without errors. Department of Computer Science - Data Structure Complete Notes Hash Table Hash table or hash map is a data structure used to store key-value pairs. It is a collection of items stored to make it easy to find them later. It uses a hash function to compute an index into an array of buckets or slots from. which the desired value can be found. It is an array of list where each list is known as bucket. It contains value based on the key. Hash table is used to implement the map interface and extends Dictionary class. Hash table is synchronized and contains only unique elements. 01234567 8 9 Plea) Fig. Hash Table Suppose we have integer items (26, 70, 18, 31, 54, 93}. One common method of determining a hash key is the division method of hashing and the formula is : Hash Key = Key Value % Number of Slots in the Table Division method or reminder method takes an item and divides it by the table size and returns the remainder as its hash value. 26 26% 10=6 6 70 70% 0 is | 18% a 31 31% 1 34 54% 10-4 4 93 93% 10 =3 3 After computing the hash values, we can insert each item into the hash table at the designated position as shown in the above figure. In the hash table, 6 of the 10 slots are occupied, it is referred to as the load factor and denoted by, A = No. of items / table size. For example , 4 = 6/10. It is easy to search for an item using hash function where it computes the slot name for the item and then checks the hash table to see if it is present. Constant amount of time O(1) is required to compute the hash value and index of the hash table at that location. Department of Computer Science - Data Structure Complete Notes ick Sort © Sorting is a way of arranging items in a systematic manner. * Quick sort is a highly efficient sorting algorithm and is based on partitioning of array of data into smaller arrays. * A large array is partitioned into two arrays one of which holds values smaller than the specified value, say pivot, based on which the partition is made and another array holds values greater than the pivot value. © Itisa faster and highly efficient sorting algorithm. * This algorithm follows the divide and conquer approach. Divide and conquer is a technique of breaking down the algorithms into subproblems, then solving the subproblems, and combining the results back together to solve the original problem. Quicksort picks an element as pivot, and then it partitions the given array around the picked pivot element. In quick sort, a large array is divided into two arrays in which one holds values that are smaller than the specified value (Pivot), and another array holds the values that are greater than the pivot. After that, left and right sub-arrays are also partitioned using the same approach. It will continue until the single element remains in the sub-array Divide: First pick a pivot element. After that, partition or rearrange the array into two sub-arrays such that each element in the left sub-array is less than or equal to the pivot element and each element in the right sub-array is larger than the pivot element. Conquer: Recursively, sort two sub arrays with Quicksort, Combine: Combine the already sorted array. Quicksort picks an element as pivot, and then it partitions the given array around the picked pivot element. In quick sort, a large array is divided into two arrays in which one holds values that are smaller than the specified value (Pivot), and another array holds the values that are greater than the pivot After that, left and right sub-arrays are also partitioned using the same approach. It will continue until the single element remains in the sub-array. Algorithm for Quick Sort Step 1: Choose the highest index value as pivot. Step 2: Take two variables to point left and right of the list excluding pivot. Step 3: Left points to the low index. Step 4: Right points to the high index. Step 5: While value at left < (Less than) pivot move right. Step 6: While value at right > (Greater than) pivot move left. Step 7: If both Step 5 and Step 6 does not match, swap left and right. Step 8: If left = (Less than or Equal to) right, the point where they met is new pivot Department of Computer Science ~ Data Structure Complete Notes Partition 7 Partition = ‘The above diagram represents how to find the pivot value in an array. As we see, pivot value divides the list into two parts (partitions) and then each part is processed for quick sort. Quick sort is a recursive function, We can call the partition function again. Department of Computer Science ~ Data Structure Complete Notes Tower of Hanoi Tower of Hanoi is a mathematical puzzle which consists of three pegs named as origin, intermediate and destination and more than one disks. These disks are of different sizes and the smaller one sits over the larger one. In this problem we transfer all disks from origin peg to destination peg using intermediate peg for temporary storage and move only one disk at a time. Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move the entire stack to another rod, using the following simple steps: Only one disk can be moved at a time. Smaller disk can be placed on larger disk. Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack ie. a disk can only be moved if it is the uppermost disk on a stack. No disk may be placed on top of a smaller disk. ‘This problem can be easily solved by Divide & Conquer algorithm Algorithm for TOH problem: Let’s consider move ‘n’ disks from source peg (A) to destination peg (C), using intermediate peg (B) as auxiliary. 1. Assign three pegs A, B & C 23% 1 Move the single disk from A to C and stop. 3. Ifn>1 a) Move the top (n-1) disks from A to B. b) Move the remaining disks from A to c) Move the (n-1) disks from B to C 4, Terminate

You might also like