You are on page 1of 26
I M-Tech I Sem CSE ADS &A Unit-2 (R19) Prepared by: Dr. Md. Umar khan, KHIT, Guntur Syllabus: Searching-L inear and Binary, Search Methods, Sorting-Bubble Sort, Selection Sort, Insertion Sort, Quick Sort, Merge Sort. Trees- Binary trees, Properties, Representation and Traversals (DFT, BFT), Expression Trees (Infix, prefix, postfix). Graphs-Basic Concepts, Storage structures and Traversals. UNIT I SEARCHING AND SORTING 1) Linear Search: Definition > In computer science, a linear search or sequential search is a method for finding an element within a list. > It sequentially checks each element of the list until a match is found or the whole list has been searched. Algorithm Step 1: Read elements in array Step 2: Read the element to search Step 3: Compare the element to sear and each element in array sequentially Step 4: If match is found then the search success Step 5: If match is not found upto the end then the search un success Program: import java.uti.*; class linear { public static void main(String args[]) { Scanner s=new Scanner(System.in); int al}=new int{ 100}, int n,i,num; ‘System.out.printin("Enter Number of Elements in Array:"); n=s.nextint(); System.out printin("Enter numbers: for(i = 0; 1 Binary search is the most popular Search algorithm. It is efficient and also one of the most commonly used techniques that are used to solve problems. > Binary search sorts the records either in ascending or descending order to gain much better performance than linear search. > Now suppose we have an ascending order record. At the time of search it takes the middle record/element, if the searching element is greater than middle element then the element mush be located in the second part else its in the first half. In this way this search algorithm divides the records in the two parts in each iteration and thus called binary search. Definition > A technique for searching an ordered list in which it first checks the middle item and based on that comparison it discards the other half the records. The same procedure is then applied to the remaining half until a match is found or there are no more items left. Algorithm: Step 1: Read sorted elements in array Step 2: Read the element to search Step 3: Compare the element to sear and middle element in array. If match is found the search success. Step 4: If match is not found check the search element with middle element. If search element is greater than the middle element then search on right side of middle element otherwise search on left : This process is repeated for all elements in array. If no match is found upto the end then the search is not success Prepared by: Dr. Md. Umar khan, KHIT, Guntur Progra import java.util”; class A { void binarysearch(int al].int key. int low, int high) { int mid; if(low>high) { System.out printin("Search element not found"); return; } else { mid=(low+high)2; if(key==almid]) ‘System.out printin(key+" element is found at position:"+(mid+1)); return ; } if(keya{mid]) low=mid+1; binarysearch(a,key,/ow, high); } } } Page2 M.Tech I Sem CSE ADS &A Unit-2 (R19) Prepared by: Dr. Md. Umar khan, KHIT, Guntur class binary public static void main(String args{)) { ‘Scanner s=new Scanner(System.in); Aat=new AQ); int al}=new int(50}; int i key,n,result; int low,mid,high ‘System.out.printin("Enter total no of elements:"); n=s.nextint(); ‘System out printin(“enter “+n+"elements in ascending order); for(i=0;i alj+1)) Step 4: swap(al].al+1]) Step 5: end if Step 6: end for Step 7: end for Progra _import java.util; class bubble { public static void main(String args[]) { ‘Scanner s=new Scanner(System.in); int n,tem int af}=new int{20}; System.out printin("Enter total numbers of elements:"); n=s.nextint(); ‘System.out printin("Enter elements:"); for(int i=0;i In first pass the first element is compared with second and exchange element if first one is greater than second. Similarly second element is compared with third and exchange element if second one is greater than third. Repeat this so that at the end of first pass the largest value is in last place. Leave this element. 54, 26) 93| 17| 77| 31) 44| 55) 20| Exchange 26 54, 93] 17| 77| 31| 44) 55| 20|No Exchange 26 | 54| 93| 47| 77| 31| 44/ 55| 20|Exchange 26 | 54| 17| 93| 77| 31| 44) 55) 20| Exchange 26 54| 17| 77| 93] 31| 44| 55| 20) Exchange 26 | 54| 17| 77| 31| 93| 44| 55| 20) Exchange 26 | 54| 17| 77| 31] 44| 93) 55| 20) Exchange 26 54 17| 77| 34] 44| 55| 93| 20) Exchange 93 in place 26 54/ 17| 77| 31| 44| 55| 20] 93) after first pass > In second pass compare up to before last place value and put the next largest value, that before last place. Leave this element. > This process is repeated til all the elements are placed. Now we get the sorted elements. (A) Selection Sort: © In selection sort we select first element and it compared to all remaining elements and exchange element if first one is greater than second so that the smallest value is in first place. > Now leave the first element and compare second element to remaining elements and swap it so that next smallest element in second place. Continue this all elements are sorted. Algorithm Step 1: for(i=0;i afi) Step 4: swap(ali].ali]) Step 5: end if Step 6: end for Step 7: end for Page 4 TM.Tech I Sem CSE ADS &A Unit-2 (R19) Prepared by: Dr. Md. Umar khan, KHIT, Guntur Progra import java.util.*; class selection { public static void main(String args[]) { Scanner s=new Scanner(System.in); int n,temp,min; int af}=new int{20}; System.out printin(“Enter total numbers of elements:"); n=s.nextint(); ‘System.out printin("Enter elements:"); for(int i=0;i The following figure shows the first pass of a selection sort > In first pass the first element is compared with all remaining elements and exchange element if first one is greater than second so that the smallest value is in first place. Leave this element. irst pass 54| 26 | 93] 17| 77] 31] 44| 10| 5 |Exchange 26| 54| 93| 17| 77| 31| 44| 10| 5 |No Exchange 26| 54| 93] 17| 77] 31] 44| 10| 5 | Exchange a7 93| 26 | 77| 31] 44) 10| 5 | No Exchange cd 93| 26 | 77| 31] 44| 10| 5 | No Exchange w 93|26| 77] 31| 44] 10| 5 | Exchange 54 54 54 a7 | 54[ 93] 26| 77] 31] 44/ 10| 5 | No Exchange 54 54 54 10 | 54] 93] 26[ 77] 31] 44] 17] 5 | Exchange 5in place 5 [4] o3[26| 77] 31] 44117 | 10| Snertrst pass > In second pass compare second element to last element and put the next smallest value, in second place. Leave this element. > This process is repeated till all the elements are placed. Now we get the sorted elements. £ Page 5 TM.Tech I Sem CSE ADS &A Unit-2 (R19) Prepared by: Dr. Md. Umar khan, KHIT, Guntur ) Insertion Sort: + In this sorting technique first elements are stored in an array. + The process of sorting starts with second element. First the second element is picked and is placed in specified order Next third element is picked and is placed in specified order. Similarly the fourth, fifth, ...n!" element .is placed in specified order + Finally we get the sorting elements. Algorithm: Step 1: Check second element of array with element before it and insert it in proper position. Step 2: Checking third element of array with element before it and inserting it in proper position. Step 3: Repeat this til all elements are checked. Step 4: Stop Progra import java.util* class A int n key, void insertion(int af]) for(int i=ti=0 && key < afj}) { alj+1}Fali}; FH } alj+1]-key; } } class insertion public static void main(String args()) { ‘Scanner s=new Scanner(System.in); Aat=new A); int al]=new int{50}; int key,n,tesult; int low, mid, high: System out printin("Enter total no of elements:"); ai.n=s.nextint(); ‘System.out printin(‘enter "+a1.n+"elements:"); for(int i=O;i Ina quick sort we take first element as pivot, then we list all the smaller elements than pivot, and greater elements than pivot. After partitioning we have pivot in the final position. > After recursively sorting the partition array, we get the sorted elements. Algorithm: Step 1: Let the first element taken as pivot Step 2: List all elements lesser than pivot in left direction and all greater than pivot in right direction of pivot Step 3: Repeat step 1 and 2 till there is no pivot element can be considered. ‘Step 4: All pivot elements considered to be sorting elements. Step 5: Stop Program: import java.util”; class A { void quicksort(int af] int lowint high) int pivot,temp,ij; if(lowshigh) pivot=atiow}; islow+1; jFhigh; while(true) while(pivot>ai]&&i=low) if(s)) { else break; } aflow|=al]: afjj=pivot, quicksort(a,low,j-1); Page7 IM.Tech I Sem CSE ADS &A Unit-2 (R19) Prepared by: Dr. Md. Umar khan, KHIT, Guntur quicksort(a,j+1 high); } } Class quicksort public static void main(String args) { ‘Scanner s=new Scanner(System.n); Aat=new AQ); int alj=new int{50}; int n; ‘System.out printin("Enter No of Elements:"); nes.nextint(); ‘System out printin( "Enter Numbers for(int i = O:i < mi++) afil=s.nextint(); at quicksort(a,0,n-1) ‘System out printin("Sorted Array is:") for(int i= 0:1 < njit+) ‘System out print(afij+" } } Exampl > Let us consider the elements: 14, 12, 16, 13, 11, 15 Initially let pivot=14 14 | [42] [46] [43] [47] [5 eee Soe Elements less than pivot(14) Elements more than pivot(14) 12] G3] [11 16 | [15 Elements less than | Elements more than Elements less than pivot(12) pivot(12) pivot(16) "1 13 15 14 12 13 14 15 16 The sorted elements are: 11,12,13,14,15,16 (2) Merge Sort: > It divides input array into two halves, calls itself for the two halves and then sorted and merged that two halves. Algorithm: Step 1 - Ifitis only one element in the list then itis already sorted Step 2 - Divide the list recursively into two halves till the size beoomes one. Step 3 - Once the size becomes 1, the merge process comes into action and starts merging with sorted array till the complete array is merged Program: import java.util.*; class A Void merge(int af] int low. nt mid int high) int temp}=new int{50}; int ij.k; i=low, Page 8 I M-Tech I Sem CSE ADS &A Unit-2 (R19) Prepared by: Dr. Md. Umar khan, KHIT, Guntur jemid+1; kelow; while((is=mid) && (/<=high)) { if(a[>=ali) temp[k++}=alj++]; else templk++}-alit+], } while(i<=mid) temp{k++]-ali++]; while(j<=high) } void mergesort(int al],int low,int high) { int mid; if(low!=high) { mid=((low+high)/2); mergesort(a low, mid); mergesort(a,mid+1 high); merge(a,low, mid, high); } } } class mergesort { public static void main(String args[]) { Scanner s=new Scanner(System in); Aat=new A(); int n; int alJ=new int{50}; System.out printin(’Enter No of Elements:"); n=s.nextint(); System out printin(’Enter Numbers:") for(int i = O;1< nji++) a{i]=s.nextint(); a1 mergesort(a,0,n-1); for(int i = Osi < nji++) System.out print(afij+" "); } } > For example consider the array of elements: 38, 27, 43, 3, 9, 82, 10 > Now the array is recursively divided into two halves till the size becomes one which is shown in the following figure. 38 [27 [43 [3 [9 [e2 [10 38 [a7 [43 [3 9 [e2 [10 x3 [27] [als 9 | 82 10 iy if \ q 38 | [27] [3] [3 9] [2 10 Page I M-Tech I Sem CSE ADS &A Unit-2 (R19) Prepared by: Dr. Md. Umar khan, KHIT, Guntur > Once the size becomes one, the merge process comes into action and starts merging with sorted array till the complete array is merged TREES 1) Bina: rees: > A binary tree consists of a node with left child tree and right child tree. > The different binary trees are shown below. ) @® > The (a) binary tree has an empty right subtree, while the (b) has an empty left subtree. > The tree (c) is called a complete binary tree. (2) Properties of Binary Trees: A tree with n nodes has exactly n-1 edges. Ina tree the root node does not contain any parent. > There is exactly one parent connecting any two nodes in a tree. > The maximum number of nodes in a binary tree of depth k is 2-4, k>1 > The maximum number of leaf nodes in a binary tree is L=(n+1)/2 where n is number of nodes. > For any nonempty binary tree T, if no is the number of leaf nodes and n2 the number of nodes of degree 2, then no = n2+ 1. The full binary tree of depth 4 is shown below. > For the above tree > The edges =n-1=15-1=14 > The maximum number of nodes=2"1=2'-1=15. The maximum number of leaf nodes=(15#1)/2=8 G) Binary Tree Representations: (i) Array Representation: > Consider the following two trees. Page 10 I M-Tech I Sem CSE ADS &A Unit-2 (R19) Prepared by: Dr. Md. Umar khan, KHIT, Guntur > The following figure shows the array representation for both trees shown in the above figure. tree tree oC— [Ta fe 3 ro 3] [= mt (61| "> (9) [_— f= fo} [2]ofof>. (b) tree of figure(ii) (19 [TE (a) tree of figure(i) > For complete binary tree such as figure (b) the representation is ideal, as no space is wasted. For the tree such as figure (a) memory is wasted. (ii) Linked Representatio: > Array representation is good for complete binary trees and wasteful for many other trees. > Insertion and deletion of nodes of a tree is easy and useful using linked representation. > Here each node has three fields leftChild, data, rightChild. > Itis represented as class TreeNode int data; TreeNode “leftChild, *rightChild; > The node representation is shown in the following figure. leftChild _rightchild > Consider the following two trees. 0) w > The representation of binary trees of the above trees using node structure is given below. get ropt Alo A Blo clo Di ofelo olF[o] fo Do / OTE] ) Gi), IM.Tech I Sem CSE ADS &A Unit-2 (R19) 4) Binary Tree Traversal: > Here we traverse a tree or visit each node in the tree exactly once. > When a node is visited, some operation is performed on it. > When traversing a binary tree we want to treat each node and its subtrees in the same fashion. > Let L, V, and R stands for moving leff, visiting the node, and moving right then there are six possible combinations of traversal viz: LVR, LRV, VLR, VRL, RVL, RLV. > In this we consider only three traversals LVR,VLR ,LRV, which we assign the names inorder, preorder, and postorder respectively. > For example in inorder first we traverse left subtree, visit a node and then traverse right subtree > In preorder first we visit a node and then traverse left and right subtree. > In postorder first we traverse left and right subtree and then visit a node. > Consider the binary tree of the following figure. Prepared by: Dr. Md. Umar khan, KHIT, Guntur Inorder Traversal > The algorithm for inorder traversal of a binary tree is given below. void BST-inorder(Node *T) if(T !=NULL) { inorder(T-=left), cout<data<<" "; inorder(T->right); } > This traversal is also known as traversing leftChild, root and rightChild. > In the above example of binary tree for inorder traversal First we traverse -D-J_- it complete left part of B Vist node B and traverse F -It complete left part of A Visit node A and traverse right part So we traverse G-K - It complete left part of C Visit node C and traverse H -It complete traverse Finally the inorder traversal is: |-D-J-B-F-A-G-K-C-H Gi) Preorder Traversal: > The algorithm for preorder traversal of a binary tree is given below. void BST:;preorder(Node *T) { if(T !=NULL) if cout<data<<" "; preorder(T->left) preorder(T->right); } } » This traversal is also known as traversing root, leftChild, and rightChild. > In the above example of binary tree for preorder traversal First we visit & traverse A-B-D-I - It complete left nodes Page 12 IM.Tech I Sem CSE ADS &A Unit-2 (R19) Prepared by: Dr. Md. Umar khan, KHIT, Guntur Next we traverse J-F It completes left part For right part we visit & traverse C-G - It completes right part left nodes Next we traverse K-H_- It complete traverse > Finally the preorder traversal is: A-B-D-l-J-F-C-G-K-H Gi) Postorder Traversal: > The algorithm for postorder traversal of a binary tree is given below. void BST::postorder(Node *T) { if(T I=NULL) postorder(T->left); postorder(T->right); cout<data <<" *, ; i > This traversal is also known as traversing leftChild, rightChild and root. > In the above example of binary tree for postorder traversal First we traverse IJ Vist node D and traverse F Visit node B. - It completes haif part For next part traverse K Visit node G and traverse H Visit node C-A It completes traverse > Finally the postorder traversal is: 1-J-D-F-B-K-G-H-C-A (5) Constructing binary tree using traversal @ Construct a binary tree using the following inorder and preorder Tnorder: QBKCFAGPEDAR Preorder:GBQACKFPDERH > The steps for construction of a tree is given by First node ‘G’ of Preorder is a root. Find G in inorder. Consider the left part QBKCFA and right part PEDHR of ‘G’ in inorder. For QBKCFA the next root is B in preorder. So take B as a root, and its left part is Q and right part is KCFA . For PEDHR the next root is P in preorder. So take P as a root, and its no left part but right part is EDHR. . For KFA the next root is A in preorder. So take A as @ root, and its left part is KCF and no right part For EDHR the next root is D in preorder. So take D as a root, and its left part is E and right part is HR For KCF the next root is C in preorder. So take C as a root, and its left part is K and right part is F For HR the next root is R in preorder. So take R as a root, and its left part is H and no right part low draw the tree G B P (a x D (e R) Me ww eno Zornowas K H) (i) Construct a binary tree using the following inorder and postorder Tnorder: QBKCFAGPEDHR Postorder:K FCAQBEHRDPG Page 13 I M.Tech I Sem CSE ADS &A Unit-2 (R19) Prepared by: Dr. Md. Umar khan, KHIT, Guntur > The steps for construction of a tree is given by 1. Last node ‘G’ of Postorder is a root. 2. Find G in inorder. Consider the left part QBKCFA and right part PEDHR of ‘G’ in postorder. 3. For QBKCFA the next root is B in postorder. So take B as root, and its left part is Q and right part is KCFA For PEDHR the next root is P in postorder. So take P as a root, and its no left part but right partis EDHR For KCFA the next root is A in postorder. So take A as a root, and its left part is KCF and no right part For EDHR the next root is D in postorder. So take D as a root, and its left partis E and right part is HR For KCF the next root is C in postorder. So take C as a root, and its left part is K and right part is F For HR the next root is R in postorder. So take R as a root, and its left partis H and no right part low draw the tree x 5, 6 7. 8. No iti) Construct a binary tree using the following preorder and postorder Preorder:GBQACKFPDERH Postorder:K FCAQBEHRDPG > The steps for construction of a tree is given by 1. First node ‘G' of Preorder or last node ‘G' of Postorder is a root. 2. The successor of root node in Preorder is B. The predecessor of root node in Postorder is P. So the left node of G is B and right node of G is P The part of next of B and before P in preorder is: QACKF and the part of next P is DERH The successor of B in Preorder is Q. The predecessor of P in Postorder is D. So the left node of B is Q and right node of P is D ‘The successor of Q in Preorder is A. The predecessor of D in Postorder is R. From point 3, the right node of Q is A, the left node of D is E and right node of D is R ‘The successor of A in Preorder is C. The predecessor of R in Postorder is H From point 3,the right node of A is C and right node of R is H 9. The successor of C in Preorder is K > Now draw the tree Re enon Page 14 IM.Tech I Sem CSE ADS &A Unit-2 (R19) Prepared by: Dr. Md. Umar khan, KHIT, Guntur (© Expression Postfix & Prefix Notation > Postfix notation is a notation for writing arithmetic expressions in which the operands appear before their operators. There are no precedence rules to leam, and parentheses are never needed. Similarly prefix notation is a notation for writing arithmetic expressions in which the operands appear after their operators. There are no precedence rules to learn, and parentheses are never needed > The following figure shows several infix expressions and their postfix & prefix expression notation Infix expression Postfix expression Prefix expression 243%4 234% +°432 10+5°6-1 1056"+1- “176501 arbr5 ab’S+ +5%ba (42)7 127° "721 atbie abtcl Te*ba arbiod aber ~aFcba (Application of Stacks: ‘(Conversion of Infix to Postfix expression: Algorithm: > To convert infix to postfix the algorithm is given by. Step 1: Create an empty stack. Read & add each input sequentially one by one from left to right to OS Step 2: If the input is an operand then add to the output string(OS). Step 3: If the input is an operator and if the stack is empty then push the operator into the stack, Step 4: Repeat Step2 otherwise if the input is an operator and if the stack is not empty then compare it precedence with top of the stack. If operator has high precedence then push input into the stack. Else pop the stack and add to the output string. Step 5: Repeat step 4 till all the input is completed Step 6: After all input is completed pop the stack and add to the output string Step 7: Now stack is empty. So retum the output string, Example(i): > Let the infix expression be: a+b*c-d. To convert postfix the steps are given by S.No ‘Action Stack | Output String 1 - empty ‘empt 2 | Read ‘a’ and add to the output string. Read ‘+’ and push it into the stack. + a 3 | Read ’b’ and add to the output string. Read *" and compare the precedence with top of stack. “* has “ ab high precedence so push it into the stack. 4 Read ‘c’ and add to the output string, Read ‘-’ and compare the precedence with top of stack. ‘has = abe*+ low precedence so pop the elements & add to output string __| and next push ‘into the stack. 5 Read ‘d’ and add to the output string. Pop “- and add to the output string. empty abe’+d- Example(ii) > Let the infix expression be: a*b+(c-d)*e. To convert postfix the steps are given by S.No ‘Action Stack | Output Strin; 1 = empty empty 2 | Read ‘a’ and add to the output string. Read *" and push it into the stack * a 3 | Read ‘b’ and add to the output string. Read ‘+" and compare the precedence with top of stack. "has | + ab* low precedence so pop the element & add to output string and next push ‘+ into the stack.. 4 | Read ‘( and compare the precedence with top of stack. has high precedence so push it into the stack +( ab’c Page 15 I M.Tech I Sem CSE ADS &A Unit-2 (R19) Prepared by: Dr. Md. Umar khan, KHIT, Guntur [Read ‘c’ and add to the output string. 5 | Read“ and push it into the stack Read ‘d’ and add to the output string. +¢ ab‘ed 6 | Read’) and pop — and (.from stack. Add — to the output string, + ab’cd- 7 | Read * and compare the precedence with top of stack(+). ~ has high precedence so push it into the stack z ab’od- 8 | Read ‘e' and add to the output string. ind “+ and add to the output string. empt abtcd-e*+ Gi)Conversion of Infix to Prefix expression: Algorithm: > To convert infix to prefix the algorithm is given by. Step 1: Create an empty stack. Read & add each input sequentially one by one from right to left to the output string. Step 2: If the input is an operand then add to the output string Step 3: If the input is an operator and if the stack is empty then push the operator into the stack Step 4: Repeat Step2 otherwise if the input is an operator and if the stack is not empty then compare it precedence with top of the stack. If operator has high precedence then push input into the stack Else pop the stack and add to the output string Step 5: Repeat step 4 til all the input is completed Step 6: After all input is completed pop the stack and add to output string, Step 7: Now stack is empty. So retum the Output string. > Let the infix expression be: a+b*c-d. To convert prefix the steps are given by S.No | ‘Action Stack | Output String 1 - empl empl 2 | Read ‘a’ and add to the output string, Read ‘+’ and push it into the stack. + a 3 Read ‘b’ and add to the output string. Read’ and compare the precedence with top of stack. has . ba high precedence so push it into the stack. 4 | Read‘ and add to the output string. Read“ and compare the precedence with top of stack. “" has = +¥cba low precedence so pop the elements & add to output string and next push ~~" into the stack. 5 | Read ‘d’ and add to the output string. Pop ‘~ and add to the output string. empt -d#*cba Conversion of Postfix to Prefix expressic ‘Algorithm: > To convert postfix to prefix the algorithm is given by. Step 1: Create an empty stack. Read each input sequentially one by one from left to right. Step 2: If the input is operand then push it into the stack. Step 3: If the input is an operator then pop two elements from the stack and create it as a string by placing the operator before the elements and push the resulted string back to stack Step 4: Repeat steps 2 and 3 till the end of the prefix expression Examp! > Let the postfix expression be: abc*+d-. To convert prefix expression the steps are given by S.No ‘Action Stack 1 = empty 2 _| Read’a.b,c’ and push this one by one into the stack. a,b,c | Read ™ is a operator. So pop two elements from stack and create as string by placing the operator before the elements and push the a,*be resulted string back to stack 4 | Read is a operator so pop two elements from stack and create as a string by placing the operator before the elements and push the +arbe resulted string back to stack . Page 16 I M.Tech I Sem CSE ADS &A Unit-2 (R19) Prepared by: Dr. Md. Umar khan, KHIT, Guntur 5 | Read d is an operand. So push d into the stack +a°bo,d & | Read "is a operator so pop two elements from stack and create as a string by placing the operator before the elements and push the -tatbed resulted string back to stack (iv) Conversion of Prefix to Postfix expression: ‘Algorithm: > To convert prefix to postfix the algorithm is given by. Step 1: Create an empty stack. Read each input sequentially one by one from right to left. Step 2: If the input is operand then push it into the stack. Step 3: If the input is an operator then pop two operands from the stack and create it as a string by placing the operator after the elements and push the resulted string back to stack. Step 4: Repeat steps 2 and 3 till the end of the prefix expression. > Let the prefix expression be: -ta*bed. To convert postfix expression the steps are given by S.No ‘Action Stack 1 = empty 2 | Read ‘d,c.b’ and push this one by one into the stack. d,c,b 3 _| Read ™ is a operator. So pop two elements from stack and create as a string by placing the operator after the elements and push the resulted dbe* string back to stack 4 | Read a is an operand. So push a into the stack d.be*a 5 _| Read ‘+’ is a operator so pop two elements from stack and create as a string by placing the operator after the elements and push the resulted dabe"+ string back to stack @ | Read "is a operator so pop two elements from stack and create as a string by placing the operator after the elements and push the resulted abe"+d- string back to stack . ‘Conversion of postfix to infix expr ‘Algorithm: > To convert postfix to infix the algorithm is given by. Step 1: Create an empty stack with size equal to number of characters in postfix expression. Step 2: Push the postfix expression elements one by one into stack like leftmost element at top and right most element at bottom sequentially ‘Step 3: Apply pop operation on all elements one by one starting from top of stack. ‘Step 4: When an operand is popped take that operands separately by putting comma(,) in between operands. Step 5: When an operator is popped, take that operator between last two preceding operands and then enclose with two brackets ( ) Step 6: Repeat 4.5 steps till the end Examp! > For example let the postfix expression: xyz*+nm-+o+p/- Step 1: Create an empty stack with size equal to number of characters in postfix expression. Step 2: Push the postfix expression elements one by one into stack like leftmost element at top and right most element at bottom sequentially jon: x Page 17 I M-Tech I Sem CSE ADS &A Unit-2 (R19) Prepared by: Dr. Md. Umar khan, KHIT, Guntur Step 3: Apply pop operation on all elements one by one starting from top of stack. Step 4: When an operand is popped take that operands separately by putting comma(,) in between operands xyz Step 5: When an operator is popped, take that operator between last two preceding operands and then enclose with two brackets ( ) xy2" x(y"Z) Step 6: Repeat 4,5 steps till the end x (YZ) (x+(y"Z)),0,m,+ (x+(y"Z)),(n+m) (x+(y‘z)),(n+m),0,+ (x+(y'z)),(n+mto) (x+(y*z)),(n+m+o),p,/ (x+(y"z)),(n+m+o)/p,- (x+(y"z)){(n+m+o)/p) (vi) Conversion of prefix to infix expressi Algorithm: > To convert prefix to infix the algorithm is given by. Step 1: Create an empty stack with size equal to number of characters in prefix expression. Step 2: Push the prefix expression elements one by one into stack like rightmost element at top and left most element at bottom sequentially Step 3: Apply pop operation on all elements one by one starting from top of stack. Step 4: When an operand is popped take that operands separately by putting comma(,) in between operands. Step 5: When an operator is popped, take that operator between last two preceding operands and then enclose with two brackets ( ). Step 6: Repeat 4.5 steps till the end. Step 7: Reverse the expression Examp! > For example let the prefix expression: -+x*yz-+n+mo/p Step 1: Create an empty stack with size equal to number of characters in prefix expression. Step 2: Push the prefix expression elements one by one into stack like rightmost element at top and left most element at bottom sequentially L m ‘Stack ‘Step 3: Apply pop operation on all elements one by one starting from top of stack Step 4: When an operand is popped take that operands separately by putting comma(,) in between operands pl Step 5: When an operator is popped, take that operator between last two preceding operands and then enclose with two brackets ( ). If no preceding operands then take as it is with no brackets. pi p/o,m.+ pi(o+m) Step 6: Repeat 4,5 steps til the end pi(o+m),n,+ pi(otm+n) potmen).zy," (plo#men)),(z"y) Page 18 IM.Tech I Sem CSE ADS &A Unit-2 (R19) Prepared by: Dr. Md. Umar khan, KHIT, Guntur (pl(orm#n))(z'y).x+ (pi(o#m+n)).((z"y)+x) (pi(o+men)).((2"y)+x),- (pi(o+m+n))((2"y)+x) Step 7: Reverse the above expression (x+(y"Z))-((n+m+o)/p) (8) Evaluating Postfix Expressi Algorithm: > To evaluate the postfix expressions the algorithm is given by. Step 1: Create an empty stack. Read each input sequentially one by one from left to right. Step 2: If the input is an operand then push it into the stack Step 3: If the input is an operator, then pop two elements from stack and perform the operation on these two elements and push the resultant into the stack. Step 4: Repeat steps 2 and 3 til the end of the postfix expression. Example: > Let the postfix expression be: 1056*+1-. To evaluate postfix expression the steps are given by S.No ‘Action Stack 1 5 empty 2 | Read 10.5.6’ and push this one by one into the stack. 10,5, 6 3 _| Read™'is a operator so pop two elements 6, 5 from stack and perform 6°5 which is 30 pushed into the stack. 10, 30 @_[ Read ‘+’is a operator so pop two elements 30, 10 from stack and perform 30+10 which is 40 pushed into the stack 40,4 Read ‘1’ and push it into the stack. 3 | Read ~'is a operator so pop two elements 7, 40 from stack and perform 40-1 which is 39 pushed into the stack. 39 | Now the input string is completed. So pop the element from the stack itis the required value Result=39 (9) Evaluating Prefix Expression: Algorithm: > To evaluate the prefix expression the algorithm is given by. Step 1: Create an empty stack. Read each input sequentially one by one from right to left Step 2: f the input is an operand then push it into the stack. Step 3: f the input is an operator, then pop two elements from stack and perform the operation on these two elements and push the resultant into the stack Step 4: Repeat steps 2 and 3 til the end of the prefix expression. Example: > Let the prefix expression be: +10-+561 To convert postfix the steps are given by S.No ‘Action Stack 4 = empty 2 Read '1,6,5’ and push this one by one into the stack. 1,6, 5 3 | Read *'is a operator so pop two elements 5, 6 from stack and perform 5*6 which is 30 pushed into the stack. 1,30 4 | Read “is a operator so pop two elements 30, 1 from stack and perform 30-1 which is 29 pushed into the stack. 29, 10 | Read ‘10’ and push it into the stack. - 5 | Read +’ is a operator so pop two elements 10, 29 from stack and perform 29+10 which is 39 pushed into the stack. 39 & | Now the input string is completed. So pop the element from the stack, itis the required value. Result=39 Page 19 M.Tech I Sem CSE ADS &A Unit-2 (R19) Prepared by: Dr. Md. Umar khan, KHIT, Guntur GRAPHS ) Basic Concepts: (a) Definition: > A Graph(G) consists of two sets V and E where Vis called vertices and E is called edges. > We also write G = (V,E) to represent a graph. > A Graph may be directed graph and undirected graph. > Inan undirected graph the pairs (u,v) and (v,u) represent the same edge. > Ina directed graph the pairs and represent two different edges > The following figure shows three graphs : G1, G2, Gs. The graphs G1, G2 are undirected graphs. > The Gs is a directed graph. 0 (a)G: > The set representation of each of this graph is MG1)= {0,1,2,3}; V(G2)={0,1,2,3,4,5,6}; W(G3)={0,1,2); E(G1)= {(0,1),(0,2),(0,3),(1,2),(1,3),(2,3)}; E(G2)= {(0,1),(0,2),(1,3),(1,4),(2,5), (2,6) E(Gs)={<0,1>,<1,0>,<1,2>}, > Notice that the edges of a directed graph are drawn with an arrow from the tail to the head. > The Graph Gz is a tree but the graphs G; and Gs are not trees. b)Restrictions on graphs > A graph may not have an edge from a vertex v back to itself. Such edges are known as self edges or self loops. > Agraph may not have multiple occurrences of the same edge. It creates multi graph. In the following figure(a) contains self loops & figure (b) contains multi graph. ()G > In undirected graph, if the max number of edges with n vertices =.n(n-1)/2. > This exactly n(n-1)/2 edges is said to be complete. Page 20 I M.Tech I Sem CSE ADS &A Unit-2 (R19) Prepared by: Dr. Md. Umar khan, KHIT, Guntur > For example in the above undirected graph is the complete graph > The maximum number of edges=4(4-1)/2=6 > In directed graph the maximum number of edges with n vertices= n(n-1) > In the above directed graph the maximum number of edges with 2 vertices=2(2-1)=2 > Itis a complete graph. (@)Adjacent and Incider in a directed graph if (u,v) is an edge then we say the vertices u and v are called adjacent and that edge (u,v) is incident on vertices u and v. > For example the vertices adjacent to vertex 1 in the above undirected graph are 3,4,0. The edges incident on vertex 1 are (0,1), (1,3), (1,4). > Similarly the vertices adjacent to vertex 2 are 5,6,0. The edges incident on vertex 2 are (0,2), (2,5), (2,6) > In directed graph if is a edge then vertex u is adjacent to v, and v is adjacent from u. > The edge is incident to u and v. > For example the vertices adjacent to vertex 1 to the above directed graph are 0,2. The edges incident to vertex 1 are <0,1>, <1,0> and <1,2> (e)sub grap! > A sub graph of Gis a graph G’ such that V(G’) ¢ V(G) and E(G') < E(G). > Let us consider the following graph @ @ 0 (il) (ii) ‘DLGiaph Storage Structures (or) Graph Representatio > There are several representations for graphs are possible. In that the following three Graph Representations are most commonly used. a)Adjacency Matrix: > Let G(V.E) be a graph with n vertices n 2 1 > The adjacency matrix of G is a two dimensional n x n array say a, with the property that afiiJ=1 if the edge (i,) is in E(G), afil[J=0 if there is no such edge in G. > For example consider the following graphs. Page 21 M.Tech I Sem CSE ADS &A Unit-2 (R19) Prepared by: Dr. Md. Umar khan, KHIT, Guntur K ZA 10) xX 10) e @ 10) (a) G1 (b) G3 (9) G4 = The Adjacency matrix of the above graphs G1, G3 and Gé are given below. 0123 012 012345 67 ofo 141 ofo 1 0] of 11000 00 4j10 141 4]1 04 1f001 0000 2\1104 2lo 0 o| 2110010000 3/4110 3j0 110 00 00 (b) GS 4000001090 (a) Gt 8000010 14 Slo 0000101 Tlo000001 (©) G4 b)Adjaceney Lists: In this representation, the n rows of the adjacency matrix are represented as n chains. > There is one chain for each vertex. > The nodes in chain i represent the vertices that are adjacent from vertex i > The data field of a chain node stores the index of an adjacent vertex value. > For example consider the following graphs. SPOS (aet (0)63 () G4 > The Adjacency lists for G1, G3 and G4 is shown in the following figure. p—aclktsS | data lnk [0] 4 T 2 uy ol +2 | =131 0 fy o +-G 3[ 0 i) ol CLT (a)Gt adjLists data link to] ilo uy) — e+e lo (b) G3 Page 22 M.Tech I Sem CSE ADS &A Unit-2 (R19) Prepared by: Dr. Md. Umar khan, KHIT, Guntur adiLists [9 a Q 3 [4 65 [6 (7 (c) Ga ©Adjacency Multiists > In the adjacency-list representation of an undirected graph, each edge (u,v) is represented by two entries, one on the list for u and the other on the list for v > In some situations it is necessary to determine the second entry for a particular edge and mark that edge has been examined. This can be accomplished easily in multilists > For each edge there will be exactly one node, but this node will be in two lists. > The new node structure is given by m | vertext | vertex? | inkt [link2 > Where mis a Boolean value that may be used to indicate whether or not the edge has been examined, For example consider the following graph. In this graph E1 to E7 represents edges from Edge1 to Edge7 respectively. > The following figure shows the adjacency multiists for the above figure. Edget 0 [4 Edge2 [Edges] Edge2 o L2 [ nuttfEdses) edges (_T4 [3 TnuttJédge4 Edge 213 Tnurifedges}] EdgeS 214 | NULLJEdge6| edges (_[4 [5 | Edge? NULL Edge7 4 16 | NUL NULL > The adjacent multi list for vertices is shown in the following figure. i___Listofedges _ | Edget,Edge2 |—Edge1. Fdge3__ Edge2, Edge4 Edge3, Edge4, Edge5 Edges, Edge6, Edge7 Edge6 Edge7_ lor jen fa bo fro b+ fo |S e Page 23 TM.Tech I Sem CSE ADS &A Unit-2 (R19) Prepared by: Dr. Md. Umar khan, KHIT, Guntur 3) Graph Traversals (or) Elementary Graph Operation: > It represents traversing a graph. It consists of. @® Depth First Search: > Depth First Search (DFS) algorithm traverses a graph in a depth ward motion and uses a stack for search. Algorithm: Step 1: Initialize the stack. Consider 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 adjacent vertex of the vertex which is not visited and push it on to the stack. Step 4: Repeat step 3 until there are no new vertex to be visit from the vertex. Step 5: When there is no new vertex to be visit then use back tracking and pop one vertex from the stack Step 6: Repeat steps 3, 4 and 5 until there is no unvisited nodes. Step 7: Now pop the nodes until stack becomes Empty. Step-2 > Select any vertex say 1 as starting point for traversal. Visit this vertex and push it on to the stack and specify that vertex in output output: 1 1 stack Stey > Visit any one of the adjacent vertex say 2 of the vertex 1 which is not visited and push it on to the stack and same specify in output. output: 12 2 4 ‘stack Step-4 ® Visit the adjacent vertex 5 of the vertex 2 which is not visited and push it on to the stack and same specify in output. 5. output: 12.5 2 1 stack Step. > Visit the adjacent vertex 7 of the vertex 5 which is not visited and push it on to the stack specify same in output. 7 5 output: 1257 2 1 ‘stack Step-6 > The vertex 7 having adjacent vertices 1,5 already visited. So back track to 5 and pop 7. At this point 5 also no adjacent vertices which is not visited. Page 24 I M-Tech I Sem CSE ADS &A Unit-2 (R19) Prepared by: Dr. Md. Umar khan, KHIT, Guntur > Again backtrack to 2 and pop 5. Now the vertex 2 having adjacent vertex 6 which is not visited. So push 6 into stack and same specify in output 6 output: 12576 2 1 stack step-7 > Now visit the adjacent vertex 3 of the vertex 6 which is not visited and push it on to the stack. Same ify in output. 3 6 output: 125763 2 1 stack i 5 Step-8 > sit the adjacent vertex 8 of the vertex 3 which is not visited and push it on to the stack. Same specify in output 6 output: 1257638 > The vertex 8 does not contain any unvisited vertex. So backtrack to 3 and pop 8. Similarly the vertex 3 does not contain any unvisited vertex. So backtrack to 6 and pop 3. Now the vertex contains unvisited vertex 4. So visit that vertex and push it on to the stack and also specify in output. output: 12576384 Pf] stack Step-10 > From the output itis clear that all nodes are visited. Hence pop the elements in the stack till the stack is empty. Now the output is required one. output: 12576384 stack > Now visiting the nodes in this depth first search is 12576384 (it) Breadth First Search: Breadth First Search (BFS) algorithm traverses a graph in a breadthward motion and uses a queue for search Algorithm: Step 1: Inilialize the queue. Consider 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 adjacent vertices of the vertex one after the other which is not visited and insert them into the Queue. Step 4: When there is no new vertex to be visit from the vertex then delete that vertex from the Queue. Page 25 I M-Tech I Sem CSE ADS &A Unit-2 (R19) Prepared by: Dr. Md. Umar khan, KHIT, Guntur Step 5: Repeat step 3 and 4 until there is no unvisited nodes. ‘Step 6: Now delete the nodes until the queue becomes empty. Step. > Consider the following graph. Initialize the queue. ae GA Step-2 > Select any vertex say 1 as starting point for traversal. Visit this vertex and insert it into the queue and also specify as output. 1 output: 1 queue w queue Stey > Visit the adjacent vertices 2, 4, 7 of the vertex 1 which is not visited and insert into the queue respectively one after the other and also specify as output. tl2fa}7 output: 12.47 queue Step-4 > Now the vertex 1 does not contain any new adjacent vertex which is not visited. So delete 1 from the queue. Now consider the vertex 2 adjacent vertices 5,6 which is not visited and insert into the queue respectively and also specify in output. 2}al7|5|6 output: 124756 queue Step-5 > Now the vertex 2 does not contain any new adjacent vertex which is not visited. So delete 2 from the queve. Similarly the vertices 4,7.5 does not contain any new adjacent vertex which is not visited. So delete 4,7,5 from the queue Now consider the vertex 6 adjacent vertex 3 which is not visited and insert into the queue and also specify in output 63] output: 1247563 queue Step-6 > The vertex 3 adjacent vertex 8 is not visited. So insert 8 into the queue and also specify in output. [ele |e] output: 12475638 queue > From the output it is clear that all the vertices are visited. So delete the vertices from the queue until the queue is empty. output: 12475638 queue > Now visiting the nodes in this breadth first search is 12475638 Page 26

You might also like