Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
27 views
Module 5
DSA notes for beginners
Uploaded by
Amit Motaphale
AI-enhanced title
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save Module-5 For Later
Download
Save
Save Module-5 For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
27 views
Module 5
DSA notes for beginners
Uploaded by
Amit Motaphale
AI-enhanced title
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save Module-5 For Later
Carousel Previous
Carousel Next
Save
Save Module-5 For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 78
Search
Fullscreen
Lecture Notes Data Structures and Applications [21CS35] Introduction "Tree is a non-tinear data structure used to represent hierarchical structure of data A tree consists of a finite set of elements, called nodes, and a finite set of directed lines, called branches, that connect the nodes, If the tree is not empty, then the first node is called the root. A tee may be divided into sub-trees. A sub-tree is any connected structure below the root. ‘The first node in a sub-tree is known as the root of the sub-tree. The concept of sub-tree leads to a recursive definition of a tree Definition "A tree is a finite set of one or more nodes such that 1) There is a specially designated node called the root. 2) The remaining nodes are partitioned into n>0 disjoint sets T1, T>, .....Tn, where each of these sets isa tree. Ti, T2, ....,Taare called the sub trees of the root. BRANCH Assoc. Prof. Assoc. Prof. NST 8M ArTLecture Notes Data Structures and Applications [21CS35] Example: The degree of ‘A” is 3, degree of “B’ is 1 and degree of ‘D” is 0. Example: The degree of the above tree is 3 - Root Node ~ The first node al the top of the free which does not have a parent is called as the == ‘ample: Node ‘A’ is the root node of the above trea Leaf Node — A node that has a degree of zero is called as a leaf node or a terminal node, Tis, node with no children. Example: The nodes D, E, F, H, I and J are the leaf nodes of the above tree. Example: The nodes A, B, C and G are the intemal nodes of the above tree. for the left subtree and / or right subtree Example: The parent of D and E is C, The parent of H, and J is G, the parent of B, F and G is A and the parent of C is B. Example: The children of C is D and E, The children of G is H, I and J, the children of A is B, F and G and the child of B is C. Example: The nodes D and E are siblings since they have the same parent C, The nodes H, 1 and J are siblings since they have the same parent G, and the nodes B, F and G are siblings since they have the same parent A. Example: Ancestors of D is C, B and A, Ancestors of His Gand A. Example: Descendants of B is C, D and E, Descendants of Gis H, I and J Example: The distance from the root node A to itself is 0, so the level of root node is 0. The level of other nodes is shown in the diagram. Example: The maximum level of the above tree is thee and hence the height of the above tuee is fo. Module 5 2Lecture Notes Data Structures and Applications [21CS35] Representation of Trees Consider the following tree, ‘There are three possible ways in which this tree can be represented. List Representation In this representation, the information in the root node comes first, which is immediately followed by a list of sub trees of that node, This is recursively repeated for each of the sub tree. The above tree can be written as a list (A (B(E(K L)F)C(G)D(H(M)1J))) ‘The following is the resulting memory representation of the above tree ar J +k $1 [0 Left-child Right-sibling Representation In this representation, the left pointer of a node in the tree will be the left child and the remaining children of the node will be inserted horizontally to the left child. The above tree written using Left-child Right-sibling Represenfation is as shown below. #6 fo] (DI + tT #ifo [=k] HEM [0 Module 5 3Lecture Notes Data Structures and Applications [21CS35] Degree Two Tree Representation (Also called as Binary Tree Representation) This representation is obtained by rotating the right-siblings in a Left-child Right-sibling Representation by 45 degrees. The degree two tree representation of the above tree is as shown below. Dr.Mahesh G Dr.Harish G ‘Assoc. Prof. Assoc. Prof. ns & brant Definition A binary tree is a tree which has finite set of nodes that is either empty or consists of a root and two disjoint binary trees called the left sub tree and right sub tree. It is named as binary tree because each node can have atmost 2 sub trees i.c. every node ean have 0, | or 2 children. Note: 1. Root ~ If the tree is not emply, the first node is called the root node. 2. Left sub tree ~ It is a tree which is connected to the left of the root. Since this tree comes towards left of root, itis called left sub tree 3. Right sub tree ~ It isa tree which is connected to the right of the root. Since this tree comes towards right of root, itis called right sub tree ‘The Abstract Datatype The Abstract Data Type of Binary Tree (Bin Tree) is Objects: A finite set of nodes either empty or consisting of a root node, left binary tree and tight binary tree. Functions: For all, root, root] and root? € BinTree item € element Module 5 4Lecture Notes BinTree Create() Boolean IsEmpty(toot) BinvTree MakeBT(item, root, root2) BinvTree Lehild(root ) BinTree Rehild(root ) element Data(root) Special types of Binary Tree Data Structures and Applications [21CS35] Creates an empty binary tree If(root—=NULL) return TRUE else return FALSE return a binary tree whose node contains the data item with rootl as left sub tree and root2 as right sub tree H(JsEmpty(roo!)) return error else return left sub tree of root, If(IsEmpty(root)) return error else return right sub tree of root If(IsEmpty(root)) return error else return the data specified in the root node. ‘The following are some of the special types of binary trees, Strictly Binary Tree ~ It is a binary tree in which the out-degree of every node ina tree is either 0 or 2 i.e. every node must have either 2 children or no child Example: Assoc. Prof, Full or Complete Binary Tree — It isa binary tree that contains maximum possible number of nodes at all levels i.¢ the number of nodes at any level ‘i” is 2' Example Module 5 LEVELO 2=1 LEVEL1 2'=2 wLecture Notes Data Structures and Applications [21CS35] Almost Complete Binary Tree - It is a binary tree in which 1_Ithas maximum possible number of nodes at each level except the last level AND, 2._ All nodes at the last level should be present only from left to right, if the number of nodes at this Ievel is not the maximum possible Eafe ee Skewed Tree— A skewed tree isa tree consisting of only left subtree or only right sub tree. A tree_with only left subtrees is called as left skewed binary tree and a tree with only nght subtrees is called right skewed binary tree Example: Dr.Mahesh G Dr.Harish G Assoc. Prof. Assoc. Prof. BMSIT EM. Dealt Right Skewed Tree Left Skewed Extended Binary Tree or 2-Tree — A binary tee T is said to be a 2-tree or an extended binary tree if each node N has either 0 or 2 children: Example : Consider the following binary trees Module 5 6Lecture Notes Data Structures and Applications [21CS35] ‘The extended binary trees for the above binary tress are as shown below, Dr.Mahesh G Dr.Harish G Assoc. Prof. Assoc. Prof. iT A Deal Note: 1) The square nodes in an extended binary tree are called evternal nodes. 2) The original (circular) nodes of the binary tree are called as infernal nodes. Lemma 1: The maximum number of nodes on level ‘i! of a binary tree is for i20 oN, Proof: Consider the following complete binary tree Number of nodes at level 0 = 1 Number of nodes at level 1 = 2 Number of nodes at level 2 = 4 Number of nodes at level 3 =8 = Hence, Number of nodes at level i = Module 5 7Lecture Notes Data Structures and Applications [21CS35] Lemma 2: The Total number of nodes ina full binary tree of level ‘it is 21-1 Proof: Total number of nodes in a full binary tree of level “is given by Ne=2% 24 92493 +2 ‘This series is in geometric progression whose sum is $ ~ a(t"— 1)/ (1) Where, ais the first term = 1 ris the common ratio = 2 nis the number of terms =i+1 Hence Ni=a(t® = 1) /(r- 1) = 102" = 1) /@- 1) = 2" Lemma 3: The maximum number of nodes in a binary tree of depth k = 2*— 1 Proof: From Lemma 2, we have the Total number of nodes in a full binary tree of level “is 2"! 1, Also, by definition, we have depth of a tree = maximum level +1 Hence k=i+ 1; Substituting this value in N= 2 — 1, we get Ni=2*— Lemma 4: For any non empty binary tree, T, if no is the number of leaf nodes and nz is the number of nodes of degree 2, then no= mn: + 1. (Relation between number of leaf nodes and degree-2 nodes) Proof: Let nobe the number of nodes with degree 0, mi be the number of nodes with degree 1 and ne be the number of nodes with degree 2. Then the total number of nodes in the tree is Ni =no+mtm..... () Let ‘B’ be the total number of branches in the tree. The total number of nodes in a tree is equal to the total number of branches plus one i.e. Nt= B+ 1 Q Branches stem from a node with degree | or degree 2 If there is node with degree 1, then the number of branches ~ 1. Henee, for m) number of nodes with degree 1, nunber of branches =n; If there is node with degree 2, then the number of branches = 2. Hence, for ns number of nodes with degree 2, nuunber of branches = 2m. ‘With this total number of branches B =n: + 2m @ From (1) and (2) we have no mi +n Substituting (3) in (4) we get, not my +m=n) + nz 1 no=ny + 2n2+ 1m —-1e ‘Therefore, no= m+ 1 BH @ Module 5 8Lecture Notes Data Structures and Applications [21CS35] Binary Tree Representation Binary trees can be represented using dynamic memory allocation (Linked Representation) or sequential allocation (Array Representation) Linked Representation In this representation, each node in a tree has three fields 1. info ~ Contains the actual information 2. link — Contains the address of left sub tree 3. rlink — Contains the address of right sub tree So, a node can be represented using the structure as shown below. struct node, { int info; Dr.Mahesh G Dr.-Harish G struct node “link; struct node *link, y Example: Consider the tree shown below. ‘The linked representation of the above tree is as shown below. root pa fe Tal Note: A variable root always points to the root node, If root = NULL, then the tree is empty. Module 5 9Lecture Notes Data Structures and Applications [21CS35] Array Representation This representation of binary tree requires numbering of nodes starting with nodes on level 0, then on level 1 and so on from left to right with mumbers 0, 1, 2, These nodes are maintained in a 1-D array in appropriate subscripts according to their node number Example 1: pe | ale | |= Example 2: Dr.Mahesh G Dr.Harish G Assoc. Prof. Assoc. Prof nas be ar Note: 1) The index i =0 always gives the position of the root node 2). Given the position of a node ‘i Left chuld’s position Right child’s position = 2i +2 Parents position = 1) /2 Definition ‘Traversing means visiting each node of the tree exactly once in a systematic manner. During traversing we may print the info field of each node visited, Module 5 10Lecture Notes Data Structures and Applications [21CS35] ‘The different traversal techniques of a binary tree are GPO FAEPD 1 is defined as follows Step 1: Visit the node Step 2: Recursively traverse the left subtree in Pre-Order Step 3: Recursively traverse the right subtree in Pre-Order OFA 11 is defined as follows Step 1: Recursively traverse the left subtree in In-Order Step 2: Visit the node (GPRS 1 is defined as follows Step 1: Recursively traverse the left subtree in Post-Order Step 2: Recursively traverse the right subtree in Post-Order Step 3- Visit the node Problem 1 — Traverse the below tree in Pre-Order, In-Order and Post-Order Dr.Mahesh G Dr.Harish G Assoc. Prof. Assoc. Pi BMT & Drea Pre-Order (N LR) ABr Cp AB Dr Ep Ce ABDEpCr ABDE FrCp ABDEFCe ABDEFCGplp ABDEFCGIb bb ABDEFCGHP ABDEFCGHI In-Order (LN R) BAC: DBEACL DBEIAG DBREAG DBFEAG DBFEAGCK DBFEAGH:Ch DBFEAGHCK DBFEAGHCI Post-Order (L. RN) Br CpA DeEeB Ce A DEPBCeA DFpEBCpA DFEBCPA DFEBGpIpCA DFEBHeGIpCA DFEBHGRCA DFEBHGICA Module 5 nLecture Notes Data Structures and Applications [21CS35] Inserting an element into a Binary Tree based on direction NODE insert_node(int item, NODE root) { NODE temp, //Node to be inserted NODE cur, //Child node NODE prev, //parent node char direction{20]; //directions where the node has to be inserted inti; temp = (NODE) malloc(sizeof{stmet node)), temp->info=item; temp->llink=NULL, temp->rlink=NULL; iffzoot_ =NULL) Assoc. Prof. Assoc. Prof. t ast Dra return temp, 3 printf(‘give the directions where u want to insert\’), seanf(“ ~ direction); prev-eur; if(direction{i] =="') //direction 1 move to left cur=cur->llink, ase cur=cur->rlink; //otherwise move to right 3 iffcur!=NULL || i!=stlen(direction)) { printf("insertion not possible\n"); free( temp); return root, 3 if{direction{i-1]—1) prev-llink=temp; —_//attach node to left of parent else prev->alink-temp, — //attach node to right of parent retum root; Module 5 2Lecture Notes Data Structures and Applications [21CS35] Recursive Inorder Traversal void inorder(NODE root) t if(root = = NULL) return; inorder(root->llink); printf(%d\n" root-> info); inorder(root->rlink); 3 Recursive Preorder Traversal void preorder(N ODE root) t if(root = = NULL) return; printf(’%d\n" zoot->info); preorder(root->llink); preorder(root->rlink): 5 Recursive Postorder Traversal void postorder(NODE root) t if root = = NULL) return; postorder(root->Ilink)s postorder(root->rlink); printf("%d\n" zoot>info); Assoc. Prof. Assoc. Prof. } ust ora Function to print in the form of Tree void display(NODE root, int height) t int i; if(root = = NULL) return; display(root->rlink, height*1); for(i=1; i<=heightl; it) print{('--"); printf("%din" root->info); display(soot->llink, height+1); Module 5Lecture Notes Data Structures and Applications [21CS35] Main Function for Binary Tree main() NODE root = NULL; int item, choices for(:) t printf("\nl:insert_node\n2:inorder\n3:preorder\n"); printf(‘4:postorder\n5.display\n6:exit\n"); printf("enter your choice\n"); seanf("%d" ,Sichoice); switeh(choice) { case 1: printf("enter the item to be inserted\n") seanf("%d",&item); root = insert_node(item, root); break; case 2: if(root = = NULL) printf(’the tree is empty\n"); else inorder(root)s break; case 3: if(roo ULL) printf(’the tree is empty\n"); else preorder(roat) break; postorder(root); break; case 5: if(root = = NULL) printf("the tree is empty\n"); else display(root,1); break; default : exit(0); Module 5 4Lecture Notes Iterative Inorder Traversal void inorder(NODE root) { NODE cur, s[25]; int top iffzoot { NULL) printf(“tree is emptyin”); retum; } cur = root; for( ;;) { while(cur = NULL) C push(cur, &top, 8); cur = cur->llink; } ifftop '= -1) cur = pop(stop, 5); printf(“%edin”, cur->info); eur = cur->rlink, } else break: Level Order Traversal Data Structures and Applications [21CS35] Iterative Preorder Traversal void preorder(NODE root) { NODE eur, [25]; int top=-1, if{zoot == NULL) { printf{‘“tree is emptyin”); retumn; } cur =root, for( 3) { while(cur != NULL) { printit“%edin”, cur->info); push(cur, Stop, 3); cur = onr->Ilink, 3 ifftop != -1) { cur = pop(&top, s); cur =cur->rlink, } else break, Dr.Mahesh G Dr.Harish G Assoc. Prof. br. aT ‘The nodes in a tree are numbered starting with the root node on level 0, and continuing with nodes on levell, Ievel2 and so on, Nodes on any level are numbered fiom left to right. Visiting the nodes according to this numbering scheme is called as level order traversal. This traversal technique uses a queue Example: For the twee shown below, level order traversing is AB C DEF GHI Contents ofthe Queue _[ Output A BC A CDE AB DEFG ABC EFG ABCD FGH ABCDE GHI ABCDEF EI ABCDEFG I ABCDEFGH QUEUE EMPTY STOP [ABCDEFGHI Module 5Lecture Notes Algorithm Step 1: Insert the root into quene Data Structures and Applications [21CS35] Step 2: As long as the queue is not empty, delete an element from the queue and print the info field. If the left subtree exists insert it into the queue. If the right subtree exists insert into the queue Function for level order traversing of a binary tree void level_order(NODE root) { NODE q{100], cur; int 0, =: marth, Dr.Mahesh G Dr.Harish G lt] = root; ‘Assoc. Prof. Assoc. Prof, while( f<=1) { iffeur->llink -NULL) C rath alr] = cur->ilink; if(cur->rlink |=NULL) t r=rtl; alr] = cur->alink, } 3 Module 5 16Lecture Notes Data Structures and Applications [21CS35] Binary Search Trees Dictionary A dictionary is a collection of pairs (key, item), where each key has an item associated with it It is assumed that no two pairs have the same Example: The dictionary of telephone numbers and the name of the person who holds that number is as shown below. Number [Name TITVITIT | Mahesh 222322222 | Harish 333333333 | Ramesh 444444444 | Suresh. ADT of Dictionary Objects: A collection of n>0 pairs, where each pair has a key and associated item. Functions: Dr.Mahesh G Dr.Harish G For all, ‘Assoc. Prof. _-AS80C. Prof d € Dictionary "0 Dy Ait item, key, n € integer Dictionary Create() = Create an empty dictionary Boolean IsEmpty(d, n) = Iffa— 0) retwn TRUE else return FALSE void Insert(item, k, d) — Insert the item with key k into d. element Delete(d, k) element search(d, k) Delete and retum item with key k if present. return item with key k if present return NULL if no such element. BST Definition A binaty search tree is a binary tree. It may be empty. If it is now empty, then it satisfies the following properties. 1) Each node has exactly one key and the keys in the tree are distinct 2) The keys (ifany) in the left subtree are smaller than the key in the root. 3) The keys (if any) in the right subtree are larger than the key in the root. 4) The left and right subtrees are also binary search trees, This means, for each node say ‘x’, in the tree, if its left or right sub tree exists, then elements in the left subtree are less than info(x) and elements in the right subtree are greater than info(x) Example: The following is a binary search tree Module 5 7Lecture Notes Data Structures and Applications [21CS35] Note: 1) Traversing a BST is same as traversing a binary tree. The inorder, preorder and postorder traversals of the above tree is given by, Inorder 20, 50, 60, 70, 100, 150, 160, 200, 300 Preorder 100, 50, 20, 70, 60, 200, 150, 160, 300 Postorder 20, 60, 70, 50, 160, 150, 300, 200, 100 2) Inorder traversal on a binary search tree will give sorted order of data in ascending order. This method of sorting is known as binary sort. 3) In preorder traversal, the root is processed first, before the left and right sub trees, 4) Ininorder traversal, the root is processed between its subtrees, 5) In postorder traversal, the root is processed after the subtrees. Inserting an element into BST NODE insert_node(int item, NODE root) t NODE cur,temp,prev; temp = (NODE)malloc(sizeof(struct node)); temp->info = items temp->llink = temp>rlink = NULL; if(root = = NULL) return temp; prev = NULL: cur = root; while(cur != NULL) t prev = curs if (tem < cu->info) cur = cur->llinks else cur = cur>rlink; } if(item < prev->info) prev->llink = temp; else prev->rlink = temp; return root; Module 5 18Lecture Notes Data Structures and Applications [21CS35] Note: To avoid duplicate elements in tree the necessary modification is, change the while oop as shown below. while(cur != NULL) t prev = curs if(Gtem < cur->info) cur = cur->llink; else if(item > cur>info) cur = cur->rlink; else t printf("item already exists!cannot insertin"); free(temp); return root; 3 3 Count the Nodes in a Tree // assume count is a global variable which is initialized to zero, before ealling the funetion in the main program, void count_nodes(NODE root) t if(root = = NULL) return; Or hesh G Dr.Harish G ‘Assoc. Prof. ASSOC. Prof count_nodes (root->Hlink); BMsiT MM or AT count++; count_nodes (root->rlink); 3 Count the Leaves in a Tree / assume count is a global variable which is initialized to zero, before calling the fanction in the main program void count_leaves(NODE root) t if(root = = NULL) return; count_leaves (root->llink); if(root-Llink count++; ULL && root->rlink==NULL) count_leaves (root->rlink)s Module 5 19Lecture Notes Data Structures and Applications [21CS35] Height of a Tree int max(int a, int b) { 1f(a>b) Tetum a; else retum b; } int height(NODE root) { if(root = = NULL) return 0; else return( max( height(root>Hlink), height(root->rlink) ) + 1); 3 Sum of all the nodes in a Tree / assume sum is a global variable which is initialized to zero, before calling the fianction in the main program. void add_nodes(NODE root) t if(root = = NULL) return; Dr.Mahesh G Dr-Harish G Assoc. Prof. ASSOC aust em. ‘an add_nodes (root->llink); sum = sum + rootinfo, add_nodes (root->rlink); 3 / Main function to call the above functions int count, sum; void main() t NODE root = NULL; int item, choices elrser(); for(;) { printf("\nl:insert_node\n2:count nodes\n3:count leaves\n” printi(“4:heightinS.sum\n6:exit\n"); printf("enter your choice\n"); seanf("%d!" Schoice); switeh(choice) { case 1: printf("enter the item to be insertedin"); Module 5 20Lecture Notes Data Structures and Applications [21CS35] scanf("%d" &item); root = insert_node(item, root); break; case 2: count = 0; count_nodes(root); printf('number of node = %din", count); break; case 3: count = 0; count_leaves(root); printf('number of leaves = din’, count); breaks case 4: printf(‘the height of the tree is %d\n", height(root)); break; sum = 0; add_nodes(root); printf("Sum of all the nodes = %din", sum); break; default : exit(0); } jahes| ia } Assoc. Prof. Assoc. Prof } ast Ar Recursive Search of a BST ‘NODE reeursive_search(int item, NODE root) { If(root—=NULL | item = root>info) retum root, if item < root->info) retum recursive_search(item, root->llink); retum recursive_search(item, root->1link), 3 Iterative Search of a BST NODE iterative_search(int item, NODE root) { NODE cur, cur = root, while( cur!=NULL && item!= cur->info) { If(item
info) cur = cur->llink, Module 5 auLecture Notes Data Structures and Applications [21CS35] else cur = cur->rlink, } retum cur; } Maximum Value ina BST NODE maximurn_node(NODE roo!) t If(toot =NULL) Tetum root; while(root->rlink != NULL) root = root->tlink, return root, 3 Minimum Value ina BST NODE minimum_node(NODE root) { Dr.Mahesh G Dr.Harish G If(root—=NULL) Assoc. Prof. ‘Assoc. Prof. Tetum root, BIST &M Dr. AIT While (root->Ilink = NULL) root = 100t->Ilink; return root, 3 Create a copy of a Binary Tree NODE copy(NODE root) { NODE temp, If(root = NULL) return NULL; temp = (NODE)malloc(sizeot(stmet node)); temp->info = root->info, temp-llink = copy(root-Ilink);, temp->rlink = copy(root->rlink), retum temp, Module 5 2Lecture Notes Data Structures and Applications [21CS35] Deletion from a BST Deleting a node requires searching for the node and then delete with also maintaining the ordering and properties of binary search tree. Note: “cur” is found to be the node that gets deleted Case 1: Node to be deleted (cur) has no children. child =NULL No adjustments is needed except to make parents right link as NULL as in this example. (In some cases, left link mnst be made NULL) i child = NULL (establish links and delete If(eur = par->llink) par->Ilink=child, else par->rlink=child, free(our), Case 2: Node to be deleted (cur) has only one subtree, cur Module 5 23Lecture Notes Data Structures and Applications [21CS35] (Find the child 1f(eur->llink = NULL) child = our->rlink, else iffeur->rlink = NULL) child = cur->llink, /l establish links and delete If(eur — par->llink) par->llink=child, else par->rlink=child; free(our); Case 3: Node to be deleted (cur) has both subtrees Find the inorder successor of ‘cur’ as ‘suc’. Inorder successor of any node will be the left anost node of the sight subtree of that node. Make the left subtree of ‘cur’ as the left subtree of ‘suc’ /! Find the child child=cur->rlink; (Find the inorder successor and make left subtree of cur as left subtree of suc suc = cur->rlink; while(sue->llink !~ NULL) { 3 suc->llink = cur->llink; suic = suc->Tlink: (establish links and delete If(eur = par else par->alink=child; free(cur), Module 5 24Lecture Notes Data Structures and Applications [21CS35] /1 Function to delete a node from a binary search tree NODE deletenode(int item, NODE root) { NODE child, sue, par, cur, If(root = NULL) { printf(“tree is empty'n”); Tetum root, 3 par = NULL; cur = root; while(cur = NULL && item != eur->info) { par= cur; iff tem < cm->info) cur = cur->llink; else 3 Té(eur = NULL) { printf(‘item not foundin”), Tetum root, 3 If(cur->llink == NULL) child = cur->rlink, else if{cur->rlink = NULL) child = cur->link, alse { child = our->rlink, Assoc. Prof suc = cur->rlink; ast while(suc->llink |= NULL) t suc = sue->llink, } sue->llink = cur->Ulink; 3 If(par—NULL) _//if node to be deletedis the root { free(ew); retum child, 3 1f(cur = par->llink) par->llinkchild, else parrlink-child; free(ow);, retum root; 3 Module 5 25Lecture Notes Data Structures and Applications [21CS35] Construction of Binary Search Tree Note: 1) First item to be inserted will be the root node 2) Ifitem to be inserted is less than root insert to appropriate position in left sub tree 3) Ifitem to be inserted is greater than root insert to appropriate position in right sub tree Problem 1: Construct binary search tree for the following input 22, 28, 20, 25, 22, 15, 18, 10, 14 Assumption: If item to be inserted is equal to root insert to right sub tree Dr.Mahesh G Dr.Harish G Assoc. Prof. Assoc. Prof. BM em br. aT Assumption: [fitem to be inserted is equal to root insert to left sub tree Module 5 26Lecture Notes Data Structures and Applications [21CS35] Problem 2: Construct binary search tree for the following input 6,9, 5, 2,8, 15, 24, 14, 7, 8, 5,2 Assumption: If item to be inserted is equal to root insert to right sub tree Module 5 27Lecture Notes Data Structures and Applications [21CS35] Problem 3: Construct binary search tree for the following input 14, 5, 6, 2, 18, 20, 16, 18, -1, 21 Assumption: If item to be inserted is equal to root insert to right sub tree Assumption: [fitem fo be inserted is equal to root insert to left sub tree 14, 5, 6, 2, 18, 20, 16, 18, -1, 21 Dr.Mahesh G Dr.Harish G Assoc. Prof. ASSOC. Pri stem Or. AIT Module 5 28Lecture Notes Data Structures and Applications [21CS35] Design, Develop and Implement a menu driven Program in C for the following operations on Binary Search Tree (BST) of Integers a, Create a BST of N Integers: 6, 9, 5, 2,8, 15, 24, 14, 7,8, 5,2 b. Traverse the BST in Inorder, Preorder and Post Order c. Search the BST for a given element (KEY) and report the appropriate message Delete an element(ELEM) from BST e Exit Hinclude
struct node. { int info; struct node “llink; struct node *link, } typedef struct node* NODE; // Funetion to a create a BST of N Integers: 6, 9, 5, 2, 8, 15, 24, 14, 7,8, 5,2 NODE insert_node(int item, NODE root) t NODE cur,temp,prev; temp = (NODE)malloc(sizeof(struct node)); temp->info = items temp->llink = temp>rlink = NULL; if(root = = NULL) return temp; prev = NULL; cur = root; while(cur != NULL) t prev = curs if(item < cur->info) cur = cur>llink; else cur = cur>rlink; } if(item < prev->info) prey->llink = temp; else prey->rlink = temp; return root; Module 5 29Lecture Notes Data Structures and Applications [21CS35] /! Funetion to Traverse the BST in Inorder void inorder(NODE root) t if(root = = NULL) return; inorder(root->llink); printf("%d\t" root-> info); inorder(root->rlink); 3 /i Function to Traverse the BST in Preorder void preorder(N ODE root) t if(root = = NULL) return; printi(’%d\t" root> info); preorder(root->llink); preorder(root->zlink); 3 // Function to Traverse the BST in Postorder void postorder(NODE root) t if root = = NULL) return; postorder(root->llink); postorder(root->rlink); printf(’%dit" root>info); 3 // Function to search for a key in BST NODE searoh(int item, NODE root) { If(toot—=NULL || item = = root->info) retum root; iffitem < root->info) retum search(item, root->Ilink), return search(item, root->rlink), 3 Module 5 30Lecture Notes Data Structures and Applications [21CS35] /1 Function to delete a node from a binary search tree NODE delete_node(int item, NODE root) { NODE child, sue, par, cur, If(root = NULL) { printf(“tree is empty'n”); Tetum root, 3 par = NULL; cur = root; while(our = NULL && item != cur->info) { par= cur; iff tem < cm->info) cur = cur->llink; else eur = cur->rlink, 3 Té(eur = NULL) { printf(“item not foundin”); Tetum root, 3 If(cur->llink == NULL) child = cur->rlink, else if{cur->rlink = NULL) child = cur->link, alse { child = our->rlink, suc = cur->rlink; while(sue->llink != NULL) t suc = sue->llink, } sue->llink = cur->Ulink; 3 If(par— NULL) _//if node to be deleted is the root { free(ew); retum child, 3 1f(cur = par->llink) par->llinkchild, else parrlink-child; free(cur), retum root; 3 Module 5 31Lecture Notes Data Structures and Applications [21CS35] ‘void main( ) { int choice, item; NODE root = NULL, temp, parent; fort; 5) { printf("1 Createin"), printf("2 Traverse the Tree in Preorder, Inorder, Postorder\n"), printf{"3 Searchin"); printf("4 Delete an element from the Tree\n"); printf("S Exit"); printf{"Enter your choice\n” seang("9%d", &choice), Dr.Mahesh G Dr.Harish G Assoc. Prof. Assoc. Prof. switch (choice) sit Dealt { case 1: printf("Enter the item to be inserted \n"), seanft fd", &citem); nsert_node(item, root); case 2: if (toot = NULL) printf{"Tree Is Not Created”), else € printf{""wThe Inorder display : "), inorder(root), printf("\nThe Preorder display preorder(root), printf("\nThe Postorder display : "); postorder(root), } break, case 3: printf("Enter Element to be searched \n"), scanf("%6d", Stem), temp = search(item, root); ifftemp == NULL) printf("Element does not exists\n"), else printf(”'The element %d is found\n", temp->info), break, case 4: printf{"Enter Element to be deleted \n"): scani("%6d", item), root = delete_node(item, soot); break, default: exit(0), Module 5 32Lecture Notes Data Structures and Applications [21CS35] Forests Definition A forest is a collection of zero or more trees. The following shows a forest with three trees. Converting a Tree into a Binary Tree Algorithm 1) Identify the branch from the parent to its first or leftmost child. These branches from each parent become left pointers in the binary tree 2) Connect siblings, starting with the leftmost child, using a branch for each sibling, to its right sibling, 3) Remove all unconnected branches from the parent to its children Example: Consider the following tree Step 1: Identify all left most children CoS Assoc. Prof, BST aM. Module 5 33Lecture Notes Data Structures and Applications [21CS35] Step 4: The resulting binary tree is ‘Transforming / Converting a Forest into a Binary Tree Definition: If T1, T2,........Ts is a forest of trees, then the binary tree corresponding to this, forest is denoted by BCT), T2,.......Ts), 1) Isempty ifn=0 2) Has a root equal to root(Ti); Has left subtree equal to BCT, Tia,.......Tam), where Tr, Tray........Tim are subtrees of root(T1) Has right subtree equal to B(Ts,........Ts), Procedure 1) Convert each tree in the forest into a binary tree. 2) The root node of the first binary tree obtained is the root for the entire tree. 3) The root node of the second binary tree is attached as the right child of root node of first binary tree, 4) The root node of the third binary tree is attached as the right child of root node of second binary tree and so on, Example: Convert the following forest into a binary tree Module 5 34Lecture Notes Data Structures and Applications [21CS35] Step 1: Convert each tree into a binary tree ge ge % Step 2: Attach root of second tree as right child of root of first tree Dr.Mahesh G Dr.Harish G Assoc. Prof. Assoc. Prof. ist Dra Step 3: Attach root of third tree as right child of root of second tree Module 5 35Lecture Notes Data Structures and Applications [21CS35] Creation of binary tree from preorder and inorder traversal Note. 1) The first value in the preorder traversal gives the root of the tree 2) In inorder traversal, initially the left subtree is traversed, then the root node and then the right subtree. Therefore, data before root node is the left subtree and data after the root node is the tight subtree. Example 1: Using the following inorder and preorder sequence, construct the binary tree. Inorder dbfeageljhk Preorder abdefeghlik Solution: 10: dbfelgcljhk po; JbdefeghIjk Io: dfe io gBljhk po, det po: Bghljk Dr.Mahesh G Dr.Harish G ‘Assoc. Prof. Assoc. Prof. iT Or ar Module 5 36Lecture Notes Data Structures and Applications [21CS35] Example 2: Using the following inorder and preorder sequence, construct the binary tree Inorder dgbaheicf Preorder abdgcehif Solution: 10: dgbQheict po: Jbdgeehif Io: heiflf io de® po: dg 10: Be @ Po Be po: fehif. Module 5 7Lecture Notes Data Structures and Applications [21CS35] Creation of binary tree from postorder and inorder traversal Note. 1) The last value in the postorder traversal gives the root of the tree. 2) In in-order traversal, initially the left subtree is traversed, then the root node and then the right subtree. Therefore, data before root node is the left subtree and data after the root node is the tight subtree. Example 1: Using the following inorder and postorder sequence, construct the binary tree Inorder beedfagh Postorder ce fede bhga Solution: 10 beedfHgh PO: efdebhe & io Bh po: h & po: e fd Dr.Mahesh G Dr.Harish G Assoc. Prof. Assoc. Prof. east am Dr ArT Module 5 38Lecture Notes Data Structures and Applications [21CS35] Expression Tree - Expression tree is a binary tree in which each intemal node corresponds to operator and each leaf node corresponds to operand. Example ~ For the expression 6 ~ (2+ 3) * 5, the expression tree is, Pre-Order (N L R) In-Order (LN R) Post-Order (LR N) be % 6n tp - 6% 6% - 6% 6 +p5p*- = 6* + 2p3Se 6-2 + 8S 6 2p3e + Sp*- -6*+2 3050 6-2+5*5 6232+ 5e*- 642 6-243*5 623+5>*- - 6 *+235 (Prefix Expression) 6-2 + 3* 5 (Infix Expression) | | 6 23 +5 *-@ostfix Expression) Note: 1) Inorder Traversing of an expression tree gives Infix expression 2) Preorder Traversing of an expression tree gives Prefix expression 3) Postorder Traversing of an expression tree gives Postfix expression Creation of Expression Tree for postfix expression While( not end of input) { Obtain the next input symbol if{symbol is an operand) { Create a node (temp) with info field=symbol ——_//operand push(node(temp), top, s) 3 Module 5 39Lecture Notes Data Structures and Applications [21CS35] else { Create a node (temp) with info field= symbol //operator temp -> rlink= pop(top, s); temp ->llink = pop(top, 5); push(node (temp), top, 8); } 3 retu( pop(top, s)); _// retumn the root node of the tree Evaluation of Postfix Expression using Expression Tree Step 1: Ifroot->llink == root->tlink == NULL return root->info Step 2: Ifroot->info is operator retum evaluate(root->llink) operator evaluate(root->rlink) Program to create an expression tree for a postfix expression and evaluate the same #include
#define stacksize 50 struct node { int info; strict node “link: Dr.Mahesh G Dr.Harish G struct node *1link: Assoc. Prof. Assoc. Prof. } * BMSIT EM, br AIT typedef struct node* NODE; void push(NODE item, int *top, NODE s[ ]) { if(*top = = stacksize -1) { printf Tetum; tack overflow\n”), 3 top =*top + 1; s{*top] =item; 3 NODE pop(int *top, NODE sf ]) { NODE item, if(*top==-1) { retum 1; Module 5 40Lecture Notes Data Structures and Applications [21CS35] } item =s[*top]; *top =*top - 1; retumn(item), } NODE create exp _tree(char postfix{]) { NODE s|stacksize], temp; int i, n, top; char symbol; top =-13 n= strlen(postfix); for(i=0; i
info = symbol; temp -> rlink= pop(8top, 5); temp -> Ilink= pop(&top, 5); push(temp, &top, 5); break; default: temp = (NODE) malloc(sizeof(struct node)); temp > info = symbol -'0'; temp > ri temp > push(temp, &top, 3); 3 3 return(pop(&top, 8); 3 Module 5 41Lecture Notes Data Structures and Applications [21CS35] int evaluate(NODE root) { } if(voot->Ilink = = NULL && root->ilink = = NULL) retum root->info; if(root-info =='+") retum (evaluate(root->llink) + evaluate(rootrlink) ); else if(root>info = ='-') return (evaluate(root else if(root->info ==") return (evaluate(toot~>llink) * evaluate(root->rlink) ), else if(root->info = ='") return (evaluate(toot->llink) / evaluate(root->rlink) ); else if(root->info ==") retum (evaluate(root->Llink) % evaluate(root->rlink) ); else if(root->info = =") retum (int)pow((double)evaluate(root->llink) , (double)evaluate(root->rlink) )); ink) - evaluate(root->rlink) ), void main() t int ress NODE root= NULL; _ [Dr Mahesh G DrHarish G char postfix[70]; ‘eerew ne chser0s printf("enter the postfix expression\n"); scanf("%s" postfix) root = create_exp_tree(postfix); res-evaluate(root); printf("the value of the postfix exp is %d", res)s getch(); Module 5 42Lecture Notes Data Structures and Applications [21CS35] Graphs Definitions Vertex ~ It is a synonym for a node and is generally represented by a circle. Example: O © Edge ~ If u’ and ‘v’ are two vertices, then an are or a line joining the two vertices ‘u’ and ‘v” is called an edge. Example: Undirected Edge ~ An edge without any direction is called an undirected edge and is denoted by an ordered pair (u, v) Example: 3, 6) Directed Edge — An edge with a direction is called an directed edge and is denoted by an directed pair
. Example: <4, 7> Graph— A graph G consists of two sets V and E and is denoted as G = (V. E), where, ‘Vis finite, nonempty set of vertices Eis finite set of edges. Directed Graph ~ A graph G ~(V, E) is called a directed graph if all the edges are directed, Itis also called asa digraph Example: The graph G =(V, E), where 1, 2,34} + <1A>, 2,1, 3,15, 34> Undirected Graph — A graph G = (V, E) is called a undirected graph if all the edges are undirected Example: O OD Module 5 @) @) 43Lecture Notes Data Structures and Applications [21CS35] ‘The graph G = (V, E), where 1, 2, 3, 4} E={ (1,2), (2,4). (1,3), 3.4)} Self Loop — A loop is an edge which starts and ends on the same vertex, It is represented by an ordered pait (i), Example: f {\ In the above graph the self loops are (1, 1) and (2, 2) Muttigraph — A graph with multiple occurence of the same edge between any two vertices is called as amultigraph Example’ O—-= © Dr.Mahesh G Dr.Harish G Assoc. Prof. Assoc. Prof. ast rat In the above graph, (1,2) and (1,3) are the multiple edges. ‘omplete Graph — A graph G = (V.E) is said to be a complete graph, if there exists anc between every pair of vertices. Example’ Note: In.a complete graph with ‘n’ vertices there will be n(n-L)/2 edges. Subgraph— A subgraph G’ of a graph Gis graph such that VG") VG) and E(G’) CE(G) Example: Consider the graph G 44Lecture Notes Data Structures and Applications [21CS35] Some of the subgraphs of G are Dr.Mahesh G Dr.Harish G Path — A path from a vertex “u’ to a vertex ‘v’ in a graph G is a sequence of vertices u. it, in. in vsnch that (i, ia), Ge i), ix, v) are edges in E(G) Example: Consider the graph shown below A path fiom vertex | to vertex 5 is given by 1, 3, 4.5 Length of the path — It is the number of edges in the path. Example: In the above graph, the length of the path from vertex 1 to vertex 5 is 3 Cyele ~ A cycle isa simple path in which the first and last vertices are the same. Example: In the above graph the path 1 2 4 3 1 represents a cycle ‘Note: A graph with atleast one cycle is called as a cyclic graph and a graph with no cycles is called as an acyclic graph. Connected Graph — A graph G is said to be a connected graph if and only if there exists a path between every pair of vertices Example: The following 1s a connected graph Module 5 45Lecture Notes Data Structures and Applications [21CS35] Disconnected Graph — A graph Gis said to be a disconnected graph if there exists atleast one vertex in the graph such that it cannot be reached fiom any of the other vertices in the graph Example: The following is a disconnected graph. O O—©O Degree, In-degree and Out-de The degree of a vertex is the number of edges incident to that vertex. Example: Consider the graph G Dr.Mahesh G Dr.Harish G ‘Assoc. Prof. Assoc. Prof. G) BRASTT BM rar Degree of vertex 1 is 3 Degree of vertex 2 is 2 Degree of vertex 3 is 2 Degree of vertex dis 3 If Gis a directed graph, the In-degree of a vertex ‘v” is the number of edges for which ‘v’ is the head and Out-depree of vertex ‘v’ is the number of edges for which “v" is the tail Example: Consider the graph G In-degree of vertex 1 is 1 Out-degtee of vertex 1 is 2 Degree of vertex 1 is 3 Module 5 46Lecture Notes Data Structures and Applications [21CS35] The following are the different representations ofa graph Let G=(V,E) be a graph, where V is the set of vertices and E is the set of edges. The adjacency matrix for the graph G with ‘n’ vertices is a “n xn” two dimensional array af J[ ] such that, afilfj] — Lif there is an edge from vertex ‘i to verte: ali) [i] =0 if there is no edge from vertex ‘to vertex. Example: The following is a directed graph and its adjacency matrix nd @) () o123 ofofifot ifofoli fo 2 [ofofo 3fofofi To The following is @ undirected graph and its adjacency matrix, Z4 =|=|eI=|- |—le]—]e Let G = (V,E) be a graph. An adjacency list is an array of ‘n? linked lists where ‘n’ is the number of vertices in the graph G. Each location of the array represents a vertex of the graph. Example: The following is a directed graph and its adjacency list af] O-O eee 1 TL Oo Jen 3] app Module 5 47Lecture Notes Data Structures and Applications [21CS35] The following is a undirected graph and its adjacency list al] 0 a $2 $3 [i @) i) 1) —pfoT+eD 2 £0 [+41 $3 1h O—’ 3 +01 +21 Weighted Edges and Weighted Graph In many applications, the edges of a graph have weights assigned to them, These weights may represent the distance from one vertex to another or the cost of going from one vertex to an adjacent vertex. Such edges with weights associated to them are called as weighted edges. A graph in which weights (a number) are assigned to each edge is called as a weighted graph. Weighted graphs can be represented using adjacency matrix (known as cost adjaceney matrix) or adjacency list (known as cost adjacency list) Example The following is a directed graph with its cost adjaceney matrix and cost adjacency list. 10 Tf3 [20 [0 10 OO jee, | tere 0 [» 1oT » [20 20 40 1 [fo [oa [a0 | oo 2|S0fa}alo| 2) —oTso[y 6) C) 3[ete pola 30 3) Go 500. Prof. MSH EM Module 5 48Lecture Notes Data Structures and Applications [21CS35] The following is a undirected graph with its cost adjacency matrix and cost adjaceney list. al] 0 afi [10 $2 [50 $31 207) o 123 1 0 [x ao J 50720 TL10] » {40} o 2[sofofa [30] 3 [oT [0] a 3 £0 [20144213011 Dr.Mahesh G Dr.Harish G ‘Assoc. Prof, Module 5 49Lecture Notes Data Structures and Applications [21CS35] Graph Traversal Traversing a graph is the systematic approach of visiting each node of the graph and do the processing (Ex: Printing the nodes information) The two traversal techniques of graphs are 1) Breadth First Search (BFS) 2) Depth First Search (DFS) Breadth First Search (BFS) In this traversal technique, the vertices are visited in the order of their levels from the source node ic. all the vertices at distance 'K’ from the source vertex are visited before visiting the nodes at distance "tI" BES can be used. 1. To check if the graph is connected or not 2. To find the vertices which are reachable from a given vertex 3. To find the spanning tree if it exists. 4. To find whether a graph is acyclic or not. Dr.Mahesh G Dr.Harish G Algorithm Assoc. Prof. ASSOC. Prof. MST Bt Dr. AT Initialize the visited[ }, fand r of ql] Step 1: Visit the source vertex and insert the source vertex to queue. Step 2: As long as the queue is not empty Step 2a: Delete a vertex 'u’ from the queue Step 2b: Find all the nodes which are adjacent to the deleted vertex 'u! and ate not visited eailier 'v ¥ Visit these nodes 'v ¥ Insert them to queue fiom left to right ¥ Store the edges (from deleted vertex 'u! to adjacent nodes 'v') Example: Consider the graph shown below Module 5 50Lecture Notes Data Structures and Applications [21CS35] -l 0 1 2 4 5 6 1 8 all r £ 0 1 2 4 5 6 1 g visited| | 0 0 0 0 0 0 0 Step 1: Assuming source vertex is 1 -l 0 1 2 4 5 6 7 8 al 1 fr 0 1 2 4 5 6 1 8 visited ] 1 0 0 0 0 0 0 Step 2: /I'u! will be the element deleted from the queue ('v! will the nodes adjacent to 'u' and not visited (U SPTE. will be the edges of the Spanning Tree if the graph is connected i.e. all nodes are reachable Visited[ | all ut vf etii| 1]2[3]4{slel7]s8 273] 4[s]e]7[8 wy 2] 12 L}oJofofo}ofolo ea 1fififofofojofo 2\4 rf t}ifafafofofo 4/5 3{o] 3° Too aaa Tsle[7 a[s[ 48 Toe aaa s[ets 3 Toa aaa ol7ls o-- Toe aaa Ths Te Toran 8 3[- List ofnodes visited Queusis emply stop SPTE Module 5 StLecture Notes Data Structures and Applications [21CS35] #include
void main() { int n, i,j, a[20][20], source, visited[20], e[20][2}; printf("Enter the number of vertices\n"), seanf("%d", Sen), 1/ Read the adjacency matrix for( i=l; i<—n; i++) { for( j=l; j<=n; j++) € seanf("%d", &afil[i]); } } print{("Enter the source vertex\n"), fd”, &source); iH) visited{i] - 0, bfs(n, a, source, visited, € ). 1! To print the nodes which are reachable and not reachable from source iffvisited{i] i 9% ptintf("%d is not reachable \n", i), flag = 1; } else { printf(*®%d is reachable \n", i); } 3 11 To check if the graph is connected and for printing spanning tree if(lag == 1) { printf(’The graph is not conneeted\n"), } else { printf("’The graph is connectedi\n"); printf(”"The spanning tree or BFS traversal isin"), for(im1; F< = neds +4) C printf(’Edge from %d to %din", efi][1], efi][2); J 3 Module 5 52Lecture Notes Data Structures and Applications [21CS35] void bfS( int n, int a[20][20}, int source, int visited}, int e[20][2} ) { int f= 0, r=-1, q[20};// queue components int u,v, k=1, 11 visit the source node and insert it into the queue visited[source] = 1; r=r+]; alr] = source, while( £<=r) // as long as the queue is not empty { u-qlf]: _ // delete an element from the queue ffl; 1 find the nodes adjacent to 'w' and not visited for( v=1; vn; v+H) { if aful[v] == 1 && visited{v] == 0) € visited[v] =1; / visit the node rth insert the node to queue I store the edges } } } } Dr.Mahesh G Dr.Harish G soe. Prof. Assoc. Prof. austT £m. a Module 5 53Lecture Notes Data Structures and Applications [21CS35] Depth First Search In this traversal technique, a node 's' is picked as a start node and marked visited, An unmarked adjacent node to's’ is selected to become the new start node and marked, possibly leaving the original start node with unexplored edges for the time being ‘The search continues in the graph until the current path ends or until all the adjacent nodes are already marked. Then the search returns to the previous nodes which still had unmarked adjacent nodes and continues marking until all nodes are marked. Note: We use a recursive call to the DFS fimetion, hence the data structure in use for DFS is stack. Example: Consider the graph shown below Dr.Mahesh G Dr.Harish G ‘Assoc. Prof. Assoc. Prof. ras rar Assuming source = 1, the depth first traversal for the above graph is Module 5 54Lecture Notes Data Structures and Applications [21CS35] Algorithm Initialize the visited| ] Step 1: Visit the source vertex 'w’ Step 2: For every node'V’ adjacent to vertex 'u! If'v is net visited earlier Store the edges (from souree vertex 'u! to adjacent nodes 'v’) Repeat through Step 1 with source as 'v! Hinelude
void dis( int n, int a[20][20}, t u, int visited{ ], int e[20][2] ) int v, static int k- 11 visit the source vertex 'u! visited[u] /1 find the nodes adjacent to 'u' and not visited for( v=; ve=n; v+) { =1 && visited{v] C elk] =u, efkI(21 1/ store the edges k=k+h df3(n, a, V, visited, e), } 3 Module 5 35Lecture Notes Data Structures and Applications [21CS35] void main() { int n, i, j, a[20][20], source, visited(20} printf("Enter the number of vertices\n" seanf("%6d”, &n); 1) Read the adjacency matrix for(i=1;
void bfs( int n, int a[20)[20], int souree, int visited{ ], int e[20][2] ) t int £= 0, r=-1, q[20];// quene components intu,y,k=1; // visit the source node and insert it into the queue visited[source] = 1; arth, alr] = source, while( £<=r) // as long as the queue is not empty { u=qif] _ // delete an element from the queue f=f+1: 11 find the nodes adjacent to 'w’ and not visited for( v=1; vn v+H) { if aful[v] == 1 && visited{v] == 0) € visited[y]=1; // visit the node T +p al]=v; (insert the node to queue elk][1]=u; elkJ[2]=v. (store the edges k=k+1, } } 3 3 Module 5 s7Lecture Notes Data Structures and Applications [21CS35] void dfs( int n, int a[20][20], int u, int visited{ }, int e[20][2] ) { int v, static int k /i visit the source vertex" visited[u] = 1; /find the nodes adjacent to 'w’ and not visited for( v=; vn. v+4) { if a[ullv] { =1 && visited|y elk] =u; 1/ store the edges di5(n, a, ¥, visited, e); Dr.Mahesh G Dr.Harish G 3 Assoc. Pr Assoc. Prof. BMSIT EM. ral void main() { int n, i, j, a[20][20], source, visited[20], e[20][2],choice,flag; printf("Enter the number of vertices\n"), seani("%d", &n); 1 Read the adjacency matrix for( i=1; ia, i+ ) t for( js is j++) € seanf("%d", &ali][il); } } printf("Enter the source vertexin"), seanf("%d", &source); for(i=1s i
[0] | Employee record with Emp IDO Employee record with Emp_ID 1 Employee record with Emp_ID 2 Employee record with Emp_ID 99) An employee record for a particular Emp_ID can be easily accessed because index = Emp_ID. However, this would not be practically feasible Assume that the company uses a five digit Emp ID. In this case the Emp_ID values range fiom 00000 to 99999. If we use the teelmique describe above, then an array of size 100000 is, required to store 100 employee records. This is as shown below. Array of Employees’ Records Employee record with Emp_ID 00000 Employee record with Emp_ID n | Employee record with Emp_ID 99998 Employee record with Emp_ID 99999 Dr.Mahesh G Dr.Harish G Assoc. Prof. Assoc. Prof. us at Module 5 60Lecture Notes Data Structures and Applications [21CS35] Whether we use a 2-digit Emp_ID (primary key) ora S-digit key, the number of employees is limited in this case to 100 and hence it would be impractical to use so much of storage space for storing 100 employee records. Another alternative to reduce the anay size is to use the last 2-digits of the primary key (Emp_ID) to get the index of the array. Example: The employee with Emp_ID 59349 will be stored in the element of the array with index 49, The employee with Emp ID 12345 will be stored in the clement of the array with index 45, In this method the employee record is not stored according to the value of key (Emp_ID), instead, the 5-digit key is converted to 2-digit index. ‘The function which is used to convert the key to index is called hash function and the arra which stores the records is called hash table. Hashing is the process of indexing the data so that sorting, searching, inserting and deleting data becomes fast. Now, if we need to store an employee record with Emp_ID 23749, then index = 49, However, an employee record with Emp ID 59349 would have been already stored at index = 49. This results in collision. Hash Table It is a data structure in which keys are mapped to array positions by a hash function. Exampl ‘he key 23749 is mapped to the array position 49 using the hash fimetion 23749 % 1000. Ina hash table, an element with key’k' is stored at index h(k), The hash function his used to calculate the index at which the element with key 'k’ will be stored. The following shows the relationship between keys and the hash table index Universe of ~ —>(Lo keys (U) 1_| NULL >| 2 =| 3 = 4 [NULL 5 | NULL Actual keys @ IKE (K) ig — @_ | NULL ——>T 9 2 and K6 point to the samme memory location, resulting in collision. 2) Keys KS and K7 also point to the same memory location, and hence collide Module 5 61Lecture Notes Data Structures and Applications [21CS35] Hash Function A hash function is a mathematical formula which when applied to a key, produces an integer which can be used as index for the key in the hash table. Properties / Characteristics of Good Hash Function 1) Low cost- The fimotion must be very easy and quick to compute 2) Determinism - The function must produce the same hash value for a given input value 3) Uniformity - The function must as far as possible, uniformly distribute the keys so that there are minimnm number of collisions. Different Types of Hash Functions 1) Division Method Choose a number 'm' larger than the number of keys 'n!. The hash function divides and uses the remainder, It is defined by H(k) = k mod m H(k) is the hash index generated for key’ and is the remainder when k is divided by m, Example: Consider the keys to be stored in the hash table to be 64, 52, 79, 36. Then using the division method the keys are stored as shown below. Choose a number m = 10 by'm' H(64) = 64% 10=4 1/64 to be placed at address 4 H(2) = 52% 10 1/32 to be placed at address 2 H(79) = 79 % 10 =9 1/79 to be placed at address 9 H(6) = 36 % 10=6 1/36 to be placed at address 6 0 1 2 3 4 5 6 7 8 9 52 64 36. 79 2) Mid Square Method Step 1: Square the value of the key ie. find k* Step 2: Extract the middle 'r digits of k? In this method the key to be stored 'k' is squared and the hash fiction is defined by mid part of k? (k) snust be obtained by deleting digits fiom both ends of k* and the same position of Ke’ must be used for all keys, Example: Consider the data to be stored in the hash table to be 3111, 2345. Then using the mid square method data is stored as shown below. 3111? = 9678321 234: 3499025 Assuming the size of the hash table to be 1000, the middle 3 digits can be taken as hash address HG111)=783 J/ 3111 to be placed at address 783 H(2345) = 990 // 2345 to be placed at address 990 Module 5 62Lecture Notes Data Structures and Applications [21CS35] Assuming the size of the hash table to be 100, the fourth and fifth digits counting from the right can be taken as hash address HG111)=78 1/3111 to be placed at address 78 H(2345) = 99 1) 2345 to be placed at address 99 3) Multiplication Method ‘Step 1: Choose a constant 'A' such that 0 < A <1 Step 2: Multiply the key by A Step 3: Extract the fractional part of "k*A" ‘The hash funetion is given by H(k) =| ((k * A) mod 1) *m| Note : Common value used for A= (stqt(S) - 1) /2=0.6180339887 Example: Consider the key to be stored is 12345, Assuming the size of hash table is 1000, the appropriate location for the key using multiplication method is (12345) =| (( 12345 * 0.618033) mod 1 ) * 1000 | | ( 7629.617385 mod 1 ) * 1000 | | 0.617385 * 1000 | | 617.385 | 617 4) Folding Method Step 1: Divide the key value into a number of parts ie, divide 'K' info ki, ko, ...ku Where each pat, except possibly the last, has the same number of digits as the requized hash address. Step 2: Add the individual parts by ignoring the last carry to get the hash index ie. He Ket. by ignoring the last canry There are two types of folding methods a) Shift Folding - Shift all parts except for the last one, so that the least significant bit of each part lines up with corresponding bit of the b) Folding at the Boundaries - Reverses every other partition before adding Example: Consider the data to be stored in the hash table to be 12320324111220. Then using the folding method data is stored as shown below. Assuming the size of the hash table to be 1000, 12320324111220 is divided into the following parts ks=20 Shift Folding Method H(k) = 123 + 203 + 241 + 112 +20 699 // 12320324111220 to be placed at address 699 Folding at the Boundaries H(k) = 123 + 302+ 241 + 211 + 20=897 // 1320324111220 to be placed at address 897 Module 5 63Lecture Notes Data Structures and Applications [21CS35] Collision occurs when the hash function maps two different keys to the_same location, However, two records cannot be stored in the same location. Therefore a method to solve this, collision called collision resolution technique is applied. Once a collision takes place, open addressing or closed hashing computes new positions using a probe sequence and the next record is stored in that position. In this technique, all the values are stored in the hash table, The hash table contains two types of valtes: sentinel values (¢.g.,—1) and data values. The presence of a sentinel value indicates that the location contains no data value at present but can be used to hold a value. When a key is mapped to a particular memory location, then the value it holds is checked. If it contains a sentinel value, then the location is free and the data value can be stored in it However, if the location already has some data value stored in it, then other slots are examined systematically in the forward direction to find a fiee slot, If fie location is not found, then we have an OVERFLOW condition. The process of examining memory locations in the hash table is called probing. Open addressing technique can be implemented using linear probing, quadratic probing, double hashing, and rehashing Dr.Mahesh G Dr.Harish G "Linear Probing Assoc. Prof. Assoc. Prof. MST & ta Or. AT In this technique, if a value is already stored at a location generated by H(W), then the following hash functions used to resolve the collision. Hk, ) = [H"(&) + i] mod m Where m is the size of the hash table, H'(k) = (k mod m), and ‘i is the probe number that varies from 0 to m—1 Therefore, for a given key k, first the location generated by H'(k) mod m is probed because for the first time iO. If the location is free, the value is stozed in it, else the second probe generates the address of the location given by [H'(k) + l]mod m, Similarly, if the location is occupied, then subsequent probes generate the address as [H'(k) + 2]imod m, [H'(k) + 3]mod m, [H"(k) + 4}mod m, [H'Ck) + 5]mod m, and so on, until a free location is found. Example: Consider a hash table of size 10. Using linear probing, insert the keys 72, 27, 36, 24, 63, 81, 92 and 104 The initial hash table is, 0 1 2 3 4 3 6 7 8 = =I = =I =I =I “1 BT “1 =I Step 1 Key=72 H(72, 0) = (72 mod 10 + 0) mod 10 = (2) mod 10 Since T[2] is vacant, insert key 72 at this location. 0 1 2 3 4 5 6 7 8 “1 “1 2 =I =I =I =I =I “1 =I Module 5 64Lecture Notes Data Structures and Applications [21CS35] Step 2 Key=27 H@QZ7, 0) = (27 mod 10 +0) mod 10 = (7) mod 10 =7 Since T[7] is vacant, insert key 27 at this location. 0 1 2 3 4 5 6 7 8 9 = “I 72 “I “I “I =I 27 “1 “I (36 mod 10 + 0) mod 10 = (6) mod 10 is vacant, insert key 36 at thus location, 2 3 4 3 6 7 8 =I =I 2 =I =I =I 36_ [37 =I =I Dr.Mahesh G Dr.Harish G Step 4 Key=24 H(24, 0) = (24 mod 10 + 0) mod 10 = (4) mod 10 Assoc, Brot. Ass0e. rok Since T[4] is vacant, insert key 24 at this location. 0 1 2 3 4 5 6 7 8 = =I 72 =I 24 =I 36_[_27 =I =I Step 5 Key =63 (63, 0) = (63 mod 10 + 0) mod 10 = (3) mod 10 =3 Since T[3] is vacant, insert key 63 at this location. 0 1 2 3 4 3 6 7 8 9 “1 “1 7m [63 [24 =I 36 1 =I Step 6 Key=81 HG1, 0) = (81 mod 10 + 0) mod 10 = (1) mod 1 Since T[1] is vacant, insert key 81 at this location, 0 1 2 3 4 5 6 7 8 -l 81 72 63 24 1 36, 27 -1 1 Step 7 Key=92 H(92, 0) = (92 mod 10 + 0) mod 10 = (2) mod 10 =2 Now T[2] is occupied, so we cannot store the key 92 in T[2] Therefore, try again for the next location. ‘Thus probe, i= 1, this time H(92, 1) = (92 mod 10 + 1) mod 10 = (2 + 1) mod 10 =3 Now T[3] is occupied, so we cannot store the key 92 in T[3] Therefore, try again for the next location, Thus probe, i=2, this time. H(92, 2) = (02 mod 10 + 2) mod 10 = 2 + 2) mod 10 =4 Now T[4] is occupied, so we cannot store the key 92 in T[4] Therefore, try again for the next location. ‘Thus probe, i=3, this time. H(92, 3) = (92 mod 10 + 3) mod 10 = 2 + 3) mod 10=5 Since T[5] is vacant, insert key 92 at this location. 3 4 5 6 7 8 = 81 4 63 24 92. 36 27 = =I Module 5 65Lecture Notes Data Structures and Applications [21CS35] Step 8 Key= 104 1104, 0) = (104 mod 10 + 0) mod 10 = (4) mod 10 = 4 Now T[4] is occupied, so we cannot store the key 104 in T[4] Therefore, try again for the next location. ‘Thus probe, i= 1, this time. H(104, 1) = (104 mod 10 + 1) mod 10 = (4 + 1) mod 10 =5 Now T[5] is occupied, so we cannot store the key 104 in T[S] ‘Therefore, try again for the next location, Thus probe, i=2, this time (104, 2) = (104 mod 10 + 2) mod 10 = (4 +2) mod 10 =6 Now T[6] is occupied, so we cannot store the key 104 in T[6} Therefore, try again for the next location. ‘Thus probe, i= 3, this time. H(104, 3) = (104 mod 10 + 3) mod 10 = (4 + 3) mod 10 =7 Now T[7] is occupied, so we cannot store the key 104 in T[7] ‘Therefore, try again for the next location. ‘Thus probe, i= 4, this tune, (104, 4) = (104 mod 10 + 4) mod 10 = (4+ 4) mod 10 =8 Since T[8] is vacant, insert key 104 at this location, 1 2 3 4 5 6 7 8 9 0 = 81 72 63 24 92, 36 27 104) =I Searching a Value using Linear Probing The procedure for searching a value in a hash table is same as for storing a value in a hash table. While searching for a value in a hash table, the array index is re-computed and the key of the clement stored at that location is compared with the value that has to be searched, If a ‘match is found, then the search operation is successful. If the key does not match, then the search fumetion begins a sequential search of the array that continues until: Y the value is found, or Y the search function encounters a vacant location in the array, indicating that the value is not present, or Y the search function terminates because it reaches the end of the table and the value is not present. ¥ More complex insert, find, remove methods Y Primary clustering phenomenon - items tend to cluster together in the auza part of the table gets quite dense, even though another part may have relatively few items. As clustering gets worse, inserting a key takes longer time because it must step all the way through a cluster to find a vacant position. Similarly as clustering gets worse, finding a key takes longer tie since elements get placed further and further from their comect hashed index: In this technique, if a value is already stored at a location generated by H(K), then the following hash function is used to resolve the collision: HW") + Cri + Ca"] mod m Module 5 66Lecture Notes Data Structures and Applications [21CS35] where m is the size of the hash table, H'(k) = (k mod m), i is the probe number that varies from 0 tom-1, and C; and C2 are constants such that C) and C4 0. Quadratic probing eliminates the primary clustering phenomenon of linear probing because instead of doing a linear search, it does a quadratic search. For a given key k, first the Tocation generated by H'(k) mod m is probed. If the location is free, the value is stored in it, else subsequent locations probed are offset by factors that depend in a quadratic manner on the probe number i Example: Consider a hash table of size 10. Using quadratic probing, insert the keys 72, 36, 24, 63, 81 and 101. Take Cy = 1 and C2=3 ‘The initial hash table is, 0 1 2 3 4 5 6 7 8 =I =I =I =I =I =I =I =I I =I Step 1 Key =72 , 0) =[72 mod 10 +1 # 0+ 3 * 0] mod 10 =[72 mod 10] mod 10 =2 mod 10 =2 is vacant, insert the key 72 in T[2] 0 2 3 4 5 6 7 8 = 72 =I = =I =I =I =I =I Step 2 Key=27 HQT 10+ 1 * 0+ 3 * 0] mod 10= [27 mod 10] mod 10 = 7 mod 10=7 Since T[7] is vacant, insert the key 27 in T[7] 0 1 2 3 4 5 6 7 8 -l -1 72 1 1 1 1 27 -1 1 Step 3 Key = 36 H(36, 0) = [36 mod 10 + 1 * 0+ 3 * 0] mod 10 = [36 mod 10] mod 10 = 6 mod 10 =6 Since T[6] is vacant, insert the key 36 in T[6], 2 3 4 5 6 7 8 0 1 = = 72 =I = “1 36 27 = “I Step 4 Key=24 [24mod 10+ 1 * 0+ 3 * 0] mod 10 = [24 mod 10] mod 10 = 4 mod 10 = 4 is vacant, insert the key 24 in T[4] 2 3 4 5 6 2 ol 24 “I 36 Step 5 Key=63 H(63, 0) = [63 mod 10 +1 * 0+ 3 * 0] mod 10 ~ [63 mod 10] mod 10 = 3 mod 10 =3 Since T[3] is vacant, insert the key 63 in T[3] 1 2 3 4 5 6 7 9 -l -1 72 63 24 -l 36, 27 -1 -1 Step 6 Key=81 H(81,0) = [81 mod 10+ 1 * 0 +3 * 0] mod 10 =[81 mod 10] mod 10 = 81 mod 10=1 Since T[1] is vacant, insert the key 81 in'T[1] 0 1 2 3 4 5 6 7 8 9 =I 31 m_[ 63 | 24 “I 36_[_ 27 “1 “I Module 5 67Lecture Notes Data Structures and Applications [21CS35] Step 7 Key= 101 (01,0) = [101 mod 10 + 1 #0 +3 * 0] mod 10= [101 mod 10 + 0] mod 10 = 1 mod 10 = 1 Since T[1] is already ocoupied, the key 101 cannot be stored in T[1] Therefore, try again for the next location. ‘Thus probe, i~ 1, this time. HGO011)— =[101 mod 10 +1 * 1+ 3* 1] mod 10 101 mod 10 + 1 +3] mod 10 101 mod 10 + 4] mod 10 1 + 4] mod 10 =5mod 10 Since T[5] is vacant, insert the key 101 in T[S]. The hash table now becomes: 0 1 2 3 4 3 6 7 8 =I 81 72 63 24 Tor 36 27 =I =I Searching a Value using Quadratic Probing ‘The procedure for searching a value in a hash table is same as for storing a value in a hash table. While searching for a value in a hash table, the array index is re-computed and the key of the clement stored at that location is compared with the value that has to be searched, If a match is found, then the search operation is successful. If the key does not match, then the search function begins a sequential search of the array that continues until: Y the valne is found, or Y the search function encounters a vacant location in the array, indicating that the value is not present, or Y the search funetion terminates because it reaches the end of the table and the value is not present. Y One of the major drawbacks of quadratic probing is that a sequence of successive probes may only explore a fraction of the table. and this fraction may be quite small. If this happens, then we will not be able to find an empty location in the table despite the fact that the table is by no means full, Y Secondary clustering - It means that if there is a collision between two keys, then the Same probe sequence will be followed for both With quadratic probing, the Double Hashing This technique uses one hash value and then repeatedly steps forward an interval until an empty location is reached. The interval is decided using a second, independent hash function, hence the name double hashing. In double hashing, we use two hash functions rather than a single function. The hash function in the case of double hashing can be given as Hk, i) = [Hu(k) + i209] mod m, where ‘mn’ is the size of the hash table Dr.Mahesh G Dr-Harish G Hk) =kmodm ‘Assoc. Prof. Assoc. Prof. eM em AT H(k) =k mod m" ‘i is the probe number and m' is chosen to be m-1 or m-2 Module 5 68Lecture Notes Data Structures and Applications [21CS35] To insert a key k in the hash table, we first probe the location given by applying [H(k) mod m] because during the first probe, i = 0. If the location is vacant, the key is inserted into it, else subsequent probes generate locations that are at an offset of [H:(k) mod m] from the previous location. Since the offset may vary with every probe depending on the value generated by the second hash function, the performance of double hashing is very close to the performance of the ideal scheme of uniform hashing. Pros and Cons Double hashing minimizes repeated collisions and the effects of clustering. That is, double hashing is free from problems associated with primary clustering as well as secondary clustering Example: Consider a hash table of size = 10. Using double hashing, insert the keys 72, 27, 36, 24, 63, 81, 92, and 101 into the table. ‘Take Hi = (k mod 10) and He = (k mod 8), Assoc. Prof. Assoc. Prof Here m=10, The initial hash table is StaM oO 1 2 3 4 9 -l -1 -1 -1 -1 -1 Step 1 Key =72 H(72, 0) = [72 mod 10 + (0 * 72 mod 8)] mod 10 = [2 + (0 * 0)] mod 10 = 2 mod 10=2 ‘Since T[2] is vacant, insert the key 72 in T[2]. The hash table now becomes: 0 1 2 3 4 5 6 7 8 9 <1 -1 72. -1 -1 -l -1 -1 -1 -1 * 27 mod 8)] mod 10 = [7+ (0 * 3)] mod 10= Since T[7] is vacant, insert the key 27 in T[7]. 0 1 2 3 4 5 6 7 9 -1 -1 72. 1 1 -1 -1 -1 1 H(36, 0) = [36 mod 10 + (0 * 36 mod 8)] mod 10 = [6 + (0 * 4)] mod 10 = 6 mod 10= 6 Since T[6] is vacant, insert the key 36 in T[6], 0 1 2 3 4 5 6 Z 8 el 1 2 -l -l al 36 27 -l -l Step 4 Key=24 H(24, 0) = [24 mod 10 + (0 * 24 mod 8)] mod 10 = [4 + (0 # 0)] mod 10 = 4 mod 10 = 4 Since T[4] is vacant, insert the key 24 in T[4], 0 1 2 3 4 5 6 7 8 9 -l -l 2 il 24 -l 36 27 -l il H(63, 0) = [63 mod 10 + (0 * 63 mod 8)] mod 10 = [3 + (0 * 7) mod 10 = 3 mod 10=3 Since T[3] is vacant, insert the key 63 in T[3], 0 1 2 3 4 5 6 7 8 -1 -1 2 63 24 ll 36 27 -1 1 Module 5 69Lecture Notes Data Structures and Applications [21CS35] 0) = [81 mod 10 + (0 * $1 mod 8)] mod 10 =[1 + (0 * 1)] mod 10 = 1 mod 10= 1 Since T[1] is vacant, insert the key 81 in T[1] 0 1 2 3 4 5 6 7 8 9 a 81 72 8 24 “I 36 27 “I “I 92 92 mod 10 + (0 * 92 mod 8)] mod 10= [2 + (0 * 4)] mod 10= 2 mod 1 Now T[2] is occupied, so we cannot store the key 92 in T[2] Therefore, try again for the next location, Thus probe, i = 1, this time Key=92 H(02, 1) = [92 mod 10 + (1 * 92: mod 8)] mod 10= mod 10 =6 Now T[6] is occupied, so we cannot store the key 92 in T[6] ‘Therefore, try again for the next location. 2+ (1 * 4)] mod 10 = (2 +4) mod 10 ‘Thus probe, i=2, this time. Key=92 H(92, 2) = [92 mod 10 + (2 * 92 mod 8)] mod 10= [2+ (2 * 4)] mod 10= [2+ 8] mod 10 = 10 mod 10 =0 Since T[0] is vacant, insert the key 92 in T[0] 0 1 2 3 4 5 6 7 8 9 92. 81 72 8 24 =I 36 27 1 1 Step 8 Key = 101 (01, 0)= [101 mod 10 + (0 * 101 mod)] mod 10 =[1 + (0 * 5)] mod 10 = 1 mod 10 = Now T[1] is occupied, so we cannot store the key 101 in T[1] Therefore, try again for the next location. Thus probe, i = 1, this time Key=101 H(O1, 1) = [101 mod 10 + (1 * 101 mod)] mod 10 =[1 + (1 *5)] mod 10 =[1+ 5] mod 10=6 Now T[6] is occupied, so we cannot store the key 101 in T[6], ‘Therefore, try again for the next location. ‘Thus probe, i=2, this time Key=101 (01, 2)= [101 mod 10 + (2 * 101 mod8)] mod 10 =[1 + (2 *5)] mod 10 =[1+ 10] mod 10=1 Now T[1] is oceupied, so we cannot store the key 101 in T[1]. Therefore, try again for the next location. Thus probe, i=3, this time. Key=101 (01, 3)= [101 mod 10 + (3 * 101 mod)] mod 10 =[1 + (3 * 5)] mod 10 =[1+ 15]mod 10=1 Module 5 70Lecture Notes Data Structures and Applications [21CS35] Now T[6] is occupied, so we cannot store the key 101 in T[6] Therefore, try again for the next location. Thus probe, i= 4, this time. Key=101 H(Z01, 4)= [101 mod 10 + (4* 101 mod)] mod 10 =[1 + (4 * 5)] mod 10 =[1 + 20] mod 10=1 Now T[1] is occupied, so we cannot store the key 101 in T[1] Therefore, try again for the next location. Note: Continuing this way, it would be hard to find a vacant space for the key. Although double hashing is a very efficient algorithm, it always requires 'm’ to be a prime number. In the example taken, m=10, which is not a prime number and henee the degradation. Rehashing When the hash table becomes nearly full, the number of collisions increases, thereby degrading the performance of insertion and search operations. In such cases, a better option is to create a new hash table with size double of the original hash table All the entries in the original hash table will then have to be moved to the new hash table This is done by taking each entry, computing its new hash value, and then inserting it in the new hash table. Though rehashing seems to be a simple process, it is quite expensive and must therefore not be done frequently. Consider the hash table of size 5 given below. The hash function used is H(x) = x % 5 Rehash the entuies into toa new hash table. 0 1 2 3 4 =I 26 31 4B 7 ‘Note that the new hash table will have 10 locations. 0 1 2 3 4 3 6 7 8 = = = =I = “1 = = = =I Now, rehash the key values from the old hash table into the new one using hash funetion H(x) =x% 10, oO 1 2 3 4 5 6 7 8 9 “1 31 “1 B “I “I 26 7 “I “I Module 5 nmLecture Notes Collision Resolution by Chaining Data Structures and Applications [21CS35] In chaining, each location in a hash table stores a pointer to a linked list that contains all the key values that were hashed to that location. That is, location | in the hash table points to the head of the linked list of all the key values that hashed to 1. However, ifno key value hashes tol, then location | in the hash table contains NULL. ‘The following figure shows how the key values are mapped to a location in the hash table and stored in a linked list that corresponds to that location. 7 Universe of [6 a+ iKIx keys(U) OS. 1 (NUL F * LI 2 KIX K] [kK] [A$ 3 sk (Kx \ 4 [NULL Ke] [Ke [Ke S| NULL 6 NULL aaatios 77) |_NEL rerx 8 NULL
(24]X] 7 =f) z + >(71x) 8 NULL 8 NULL Module 5 2Lecture Notes Data Structures and Applications [21CS35] Step3 key = 18 n(k)= 18 mod 9 = 0 Create a linked list for location 0 and store the key value 18 in it as its only node Step4 —key- 52 h(i) = 52 nod 9 =7 Insert 52 at the end of the linked list of location o —}>[1eLx] 0 =| >18[xX) 4 |NULL 41_| NULL 2_NULL| [ff Dr.Mahesh G Dr.Harish G 2_| NULL| 3_ NULL ‘Assoc. Prof. ASSOC. Prof. 3_[NULL| ia NOLL Msi aM Dealt = TROL 5 NULL 5 | NULL 6 [24] x) 6 =} > (24| x] 7 (7 D0 7 >> 715 > 82x) 8 NULL 8B | NULL Step 5: key = 26 Step 6: key = 54 h(k)= 36 mod 9=0 Insert 36 at the end of the linked list of location 0. h(k) = $4 mod 9 = 0 Insert 54 at the end of the linked list of location 0. h(k)= 41 mod @ = 2 Create a linked list for location 2 and store the key value 11 in it as its only node. o = {isl Bax 0 fis] 6] =} ax [NOLL 1 [NULL 2_ [NULL 2 (NULL! 3_ [NULL 3__ (NULL 4 [NULL 4_|NULC) 5 [NULL 5 |NULL 6 >a x 6 => Bap z soils > 2x) 7 iT 82x) @_ [NOW @_|NULL| Step7: key = 11 Step 8: key = 23 h(k) = 23 mod 9 = 5 Create a linked list for location 5 and store the key value 23 in it as its only node. 0 => ie >-se X) o >>> SiS ix 1_|NULL, 1_|NULL 2 =x) 2 = >tilx} 3 [NULL 3_{NULL 4 (NULL [NULL [NULL 5 - 6 => aad 6 >24a[X 7 —>_ Rk 7 4-713 >) 8 [NULL 6 NULL Pros and Cons ¥ The main advantage of using a chained hash table is that it remains effective even when the mumber of key values to be stored is much higher than the mumber of Module 5 3Lecture Notes Data Structures and Applications [21CS35] locations in the hash table, However, with the inerease in the number of keys to be stored, the performance of a chained hash table does degrade gradually. Y The other advantage of using chaining for collision resolution is that its performance, unlike quadratic probing, does not degrade when the table is more than half full. This technique is absolutely fiee from clustering problems and thus provides an efficient mechanism to handle collisions. Y Chained hash tables inherit the disadvantages of linked lists. 1. To store a key value, the space overhead of the next pointer in each entry can ve significant. 2. Traversing a linked list has poor cache performance, making the processor cache ineffective Pros and Cons of Hashing Y No extra space is required to store the index as in the case of other data structures ¥ Hash table provides fast data access and has an added advantage of rapid updates. Y Inserting and retrieving data values usually lacks locality and sequential retrieval by key. This makes insertion and retrieval of data values even more random, Y Choosing an effective hash function is more of an art than a science, It is not ‘uncommon to create a poor hash function. Applications of Hashing Hash tables are widely used in sitvations where enormous amounts of data have to be accessed to quickly search and retrieve information, Example: 1) Hashing is used for database indexing, 2) Hashing teclnique is used to implement compiler symbol tables in C+. 3) Hashing is also widely used for Internet search engines, Dr.Mahesh G Dr.Harish G Real World Applications of Hashing Mahesh G Dr-Harish eMsiT 4 Dr. AFT 1) CD Databases ¥ Ibis desirable to have a world-wide CD database so that when users put their disk in the CD player, they get a full table of contents on their own computer’s screen. ¥ These tables are not stored on the disks themselves, rather this information is downloaded from the database. Y Basically, a big number is created from the track lengths, also known as a ‘signature’. ‘This signature is used to identify a particular CD. The signature is a value obtained by hashing 2) Drivers Licenses / Insurance Cards Y The driver’s license mumbers or insurance card numbers are created using hashing from data items that never change: date of birth, name, ete. 3) Sparse Matrix YA sparse matrix is a two-dimensional array in which most of the entries contain a 0 Y Using a 2D array to store this would waste a lot of memory Y The non zero elements of the sparse matrix can be stored in a 1D array using hashing Module 5 4Lecture Notes Data Structures and Applications [21CS35] n n Le hp 0 Table 4 1 + 2 j . Dr.Mahesh G Dr.Harish G k Assoc. Prof. Assoc Prof . Boas Dear : . ¥ From the coordinates for every non zero element (i,j), we can determine the index ‘k' by using a hash function k= H(ij), for some function H. 4) File Signatures ¥ File signatures provide a compact means of identifying files We use a fimnction, hx], the file signature, which is a property of the file Although we can store files by name, signatures provide a compact identity to files. Since a signature depends on the contents of a file, if any change is made to the file, then the signature will change. In this way, the signature of a file can be used as a quick verification to see if anyone has altered the file, or if it has lost a bit during transmission, SSK 5) Game Boards Y In the game board for tic-tac-toe or chess, a position in a game may be stored using a hash fumetion. 6 Graphics Y In graphics, a central problem is the storage of objects in a scene or view. For this, we organize our data by hashing. Hashing can be used to make a grid of appropriate size, an ordinary vertical-horizontal grid, Y A grid is nothing but a 2D array, and there is a one-to-one correspondence when we move from a 2D ammay to a 1D array. Y Westore the grid as a ID array as we did in the case of sparse matrices. Module 5 75Lecture Notes Data Structures and Applications [21CS35] #inchude
#define MAXADDR 100 struct employee { intempid, —_// 4-digit key to determine employee records uniquely int age; char name{20); Jht[MAXADDR], int hash(int key) _// Hash function to convert 4-digit key to 2-digit index (hhash adress) { int index; index = key % MAXADDR; retum (index); 3 void main() t int i, choice, count, key, age, index, char name{20); count =0; (Initialize all the empid in hash table ht to -1 for( i=0; ic MAXADDR: i+) htfi].empid 3 forts) { printf("1. Insert Record 2, Search Record —_3.Exit\n");, printf(’Enter your choice\n"); seanf("%d", &choice), switch(choice) { case 1: if(count = = MAXADDR) € puint{(*No Space Available\n"); } else t Module 5 16Lecture Notes Dr.Mahesh G Dr.H: Module 5 Data Structures and Applications [21CS35] printf("Enter the 4-digit unique key for employee\n"), seanf("%d", &ekey), puint{(*Enter the Employee name'r gets(name), puintf(*Enter the age\n"); scanf("%ed", &age); index = hash(key); iff ht{index] empid= { 1) // Found fiee location (No Collision) hifindex] empid = key; stropy(ht{index] name, name), hifindex] age = age; count = count + 1 break; ase // Collision Resolution (Linear Probing) ‘ for( i=1; iC MAXADDR; i++) ‘ index = ( hash(key) +1) % MAXADDR, iff tfindex].empid = = -1) (/ Found fiee location “Mahesh @ Orhan ‘ htfindex].empid ~key, " ‘an strepyCht[index] name, name); hitlindex].age = age; count = count + 1; break; case 2: printi("Enter the 4-digit unique key of employee to searchin"); seanf("%od", Sekey); index =hash(key); if{ ht[index] empid ~~ key) // Found Suecessfully C printf(’Suecessful Searchin"); printf(’Name = %s'n", htfindex} name), printf("Age = %d\n", ht{index] age);Lecture Notes Data Structures and Applications [21CS35] break; } else if( htlindex] empid == -1 ) // Found Vacant Position € puintf(*Unsnecessful Searchin"), printi(’Key not found\n’),; break; } else // Search using Linear Probing € for( i=1; ic MAXADDR; i++) { index = ( hash(key) +1) % MAXADDR, iff ht[index] empid = = key) // Found Successfully { printf("Suceessfull Searchin"), puintf("Name ~%s\n’, ht{index] name), printf("Age = %din", ht[index] age); Dr.Mahesh G Dr-Harish G Assoc. Prof. Assoe. Prof break, aus eM Dealt else iff htfindex].empid ==-1 ) // Found Vacant Position { puintf("Unsuecessful Searchin"); puintf("Key not found\n"); break; 3 } } printf(’Unsuecessfil Searchin"), printf("Key not foundin"); break; default: Exit (0); Module 5 8
You might also like
Module 4 Notes
PDF
No ratings yet
Module 4 Notes
20 pages
21CS32 Module 4
PDF
No ratings yet
21CS32 Module 4
25 pages
UNIT-3
PDF
No ratings yet
UNIT-3
36 pages
Ds 03
PDF
No ratings yet
Ds 03
20 pages
DS. Unit IV
PDF
No ratings yet
DS. Unit IV
22 pages
Unit - 4 Nonlinear Data Structure Tree Part - 1 Concepts & Basic Notations
PDF
No ratings yet
Unit - 4 Nonlinear Data Structure Tree Part - 1 Concepts & Basic Notations
65 pages
Tree and Huffman Coding
PDF
No ratings yet
Tree and Huffman Coding
87 pages
Unit 4 - Binary Tree
PDF
No ratings yet
Unit 4 - Binary Tree
96 pages
Trees and Binary Trees
PDF
No ratings yet
Trees and Binary Trees
40 pages
Final Tree
PDF
No ratings yet
Final Tree
39 pages
8_DSA
PDF
No ratings yet
8_DSA
209 pages
FPGA.PDF
PDF
No ratings yet
FPGA.PDF
42 pages
Tree
PDF
No ratings yet
Tree
192 pages
Unit 4 Graph and Tree Algorithms 1
PDF
No ratings yet
Unit 4 Graph and Tree Algorithms 1
16 pages
Trees Data Structure
PDF
No ratings yet
Trees Data Structure
42 pages
Trees and Graphs ppt
PDF
No ratings yet
Trees and Graphs ppt
168 pages
Unit 5
PDF
No ratings yet
Unit 5
37 pages
Module4 Trees
PDF
No ratings yet
Module4 Trees
152 pages
DSPD Unit-IV Notes
PDF
No ratings yet
DSPD Unit-IV Notes
15 pages
Vtuupdates DSA M - 4
PDF
No ratings yet
Vtuupdates DSA M - 4
24 pages
Tree
PDF
No ratings yet
Tree
53 pages
Adobe Scan 29 Aug 2023
PDF
No ratings yet
Adobe Scan 29 Aug 2023
17 pages
Tree (3)
PDF
No ratings yet
Tree (3)
39 pages
8. Trees
PDF
No ratings yet
8. Trees
75 pages
Unit 2 Tree
PDF
No ratings yet
Unit 2 Tree
55 pages
Unit-4
PDF
No ratings yet
Unit-4
212 pages
7.0 Tree Data Structure
PDF
No ratings yet
7.0 Tree Data Structure
36 pages
DS Module 3 Trees VTU BCS304 Notes/PPT
PDF
No ratings yet
DS Module 3 Trees VTU BCS304 Notes/PPT
49 pages
Unit4 Trees
PDF
No ratings yet
Unit4 Trees
51 pages
DS Module-4 Notes
PDF
No ratings yet
DS Module-4 Notes
21 pages
WINSEM2024-25_STS4003_TH_AP2024254001066_2025-02-25_Reference-Material-I
PDF
No ratings yet
WINSEM2024-25_STS4003_TH_AP2024254001066_2025-02-25_Reference-Material-I
42 pages
Module 4
PDF
No ratings yet
Module 4
75 pages
Tree Data Structure Notes
PDF
No ratings yet
Tree Data Structure Notes
99 pages
Tree Unit-5
PDF
No ratings yet
Tree Unit-5
10 pages
DSU
PDF
No ratings yet
DSU
13 pages
Tree
PDF
No ratings yet
Tree
60 pages
FALLSEM2024-25 BCSE202L TH VL2024250101821 2024-09-23 Reference-Material-I
PDF
No ratings yet
FALLSEM2024-25 BCSE202L TH VL2024250101821 2024-09-23 Reference-Material-I
47 pages
Tree Notes
PDF
No ratings yet
Tree Notes
39 pages
Tree
PDF
No ratings yet
Tree
19 pages
chap 3 Trees-1
PDF
No ratings yet
chap 3 Trees-1
51 pages
Unit 3 Trees Notes
PDF
No ratings yet
Unit 3 Trees Notes
57 pages
DSU Unit 5 Notes Complete
PDF
No ratings yet
DSU Unit 5 Notes Complete
32 pages
Trees
PDF
No ratings yet
Trees
19 pages
Tree & Binary Tree in NCMT PDF
PDF
No ratings yet
Tree & Binary Tree in NCMT PDF
13 pages
Module3(Trees
PDF
No ratings yet
Module3(Trees
42 pages
Trees
PDF
No ratings yet
Trees
26 pages
3 Binary Trees
PDF
No ratings yet
3 Binary Trees
115 pages
Trees
PDF
No ratings yet
Trees
77 pages
DS-UNIT - 4
PDF
No ratings yet
DS-UNIT - 4
49 pages
Tree
PDF
No ratings yet
Tree
50 pages
Trees in Data Structures
PDF
No ratings yet
Trees in Data Structures
122 pages
Tree Terminology.pptx
PDF
No ratings yet
Tree Terminology.pptx
45 pages
Unit 4
PDF
No ratings yet
Unit 4
25 pages
Unit-4 - Data Structures Using C
PDF
No ratings yet
Unit-4 - Data Structures Using C
24 pages
Data Structures Using C, 2e Reema Thareja: © Oxford University Press 2014. All Rights Reserved
PDF
No ratings yet
Data Structures Using C, 2e Reema Thareja: © Oxford University Press 2014. All Rights Reserved
19 pages
UNIT -V-Trees Material Complete Material-updated
PDF
No ratings yet
UNIT -V-Trees Material Complete Material-updated
34 pages
DS L-5
PDF
No ratings yet
DS L-5
29 pages
Trees
PDF
No ratings yet
Trees
26 pages
Module 1
PDF
No ratings yet
Module 1
45 pages
Module 4
PDF
No ratings yet
Module 4
62 pages
Module 2
PDF
No ratings yet
Module 2
27 pages
Module 3
PDF
No ratings yet
Module 3
25 pages