Você está na página 1de 96

ADVANCED DATASTRUCTURES LAB MANUAL

EXERCISE-1: AIM: To implement functions of Dictionary using Hashing method, Multiplication method) DESCRIPTION:Dictionary is a collection of data elements uniquely identified by a field called key. A dictionary supports the operations of search,insert and delete. A dictionary supports both sequential and random access. These are useful in implementing symbol tables,text retrieval systems,data base systems,etc. Hash tables: Hash table is a data structure in which keys are mapped to array positions by a hash function. Hash function: A Hash function is simply a mathematical formula which when applied to a key,produce an integer which can be used as an index for the key in the hash table. Hashing:The process of mapping the keys to appropriate locations(or indexes) in a hash table is called Hashing There are different types of hash functions to calculate the hash value.They are 1.Division method 2.Multiplication method 5.Universal hashing Division method: It is the most simple method of hashing an integer x.This method divides x by M and then uses the remainder that is obtained.The hash function can be given as H(z)=z mod M (Division

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

ADVANCED DATASTRUCTURES LAB MANUAL


The division method is good for any value of M because it requires only a single division method or operation .It works very fast.But care must be taken to select a suitable value for M. Generally it is best to choose M to be a prime number . And M should also be not too close to the exact powers of 2.

Code: int const M=97; //prime value int h(int x) { return(x%M); } Example: calculate the hash values of keys 1234 and 5462 assume M=97. h(1234)=1234%97=70 h(5462)=5462%97=16 Multiplication method: The steps involved in multiplication method are as follows: Step1: Choose a constant R such that 0<A<1. Step2: Multiply the key K by A. Step3: Extract the fractional part of KA. Step4: Multiply the result of step3 by M and take the floor. Hence the hash function can be given as h(x)=[m(KA mod 1)] where (KA mod 1) gives the fractional part of KA and M is the total number of indices in the hash table.The greatest advantage of this method is that it works with any value of A. The best choice of A is (sqrt1)/2=0.61803398. Example: Given a hash table of size 1000,map the key 12345 to an appropriate location in the hash table.
BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

ADVANCED DATASTRUCTURES LAB MANUAL


Sol: We will use A=0.618033,m=1000,k=12345 h(12345)=[1000(12345*0.618033)] =[1000(7629.617385 mod 1)] =[1000(0.617385)] =[617.385] =617

SAMPLE PROGRAM: /*implement functions of Dictionary using Hashing ( Division method)*/ #include<stdio.h> #include<conio.h> #include<math.h> #define MAX 10 struct DCT { int k; int val; }a[MAX]; voidDicHash(); int hash(int); void insert(int,int,int); void display(); void size(); void search(int); void DicHash() { int i; for(i=0;i<MAX;i++) a[i].k=a[i].val=-1;

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

ADVANCED DATASTRUCTURES LAB MANUAL


} int hash(int num) { int hkey; hkey=num%10; return hkey; }

void display() { int i; printf("Hash Table is\n "); for(i=0;i<MAX;i++) printf("%d\t%d\t%d\n",i,a[i].k,a[i].val); } void insert(int index,int key,int value) { int flag=0,i,count=0; if(a[index].k==-1) { a[index].k=key; a[index].val=value; } else { i=0; while(i<MAX) { if(a[i].k != -1) count++;

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

ADVANCED DATASTRUCTURES LAB MANUAL


i++; } if(count==MAX) { printf("Hash Table is Full "); return; } for(i=index+1;i<MAX;i++)

if(a[i].k==-1) { a[i].k=key; a[i].val=value; flag=1; break; } for(i=0;i<index&&flag==0;i++) if(a[i].k==-1) { a[i].k=key; a[i].val=value; flag=1; break; } } } void size() { int i,len=0; for(i=0;i<MAX;i++) if(a[i].k != -1)

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

ADVANCED DATASTRUCTURES LAB MANUAL


len++; printf("size of the Dictionary is len %d",len); } void search(int search_key) { int i,j; i=hash(search_key); if(a[i].k==search_key) { printf("The record is present at location %d\n",i); return ; } if(a[i].k!=search_key) { for(j=i+1;j<MAX;j++) { if (a[j].k==search_key) { printf("The record is present at location %d\n" ,j); return; } } for(j=0;j<i;j++) if (a[j].k==search_key) { printf("The record is present at location %d\n",j); return; } printf("The record not found\n"); } else

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

ADVANCED DATASTRUCTURES LAB MANUAL


printf("The record is not present in the hash table\n"); } void main() { int ch; int hkey,key,value; clrscr(); DicHash();

do { printf("\n1.insert 2.search 3.display 4.size 5.exit\n enter your choice"); scanf("%d",&ch); switch(ch) { case 1:printf("enter key and value:"); scanf("%d%d",&key,&value); hkey=hash(key); insert(hkey,key,value); break; case 2:printf("enter key "); scanf("%d",&key); search(key); break; case 3:display(); break; case 4:size(); break; } }while(ch!=5);

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

ADVANCED DATASTRUCTURES LAB MANUAL


}

EXPECTED OUTPUT: 1.insert 2.search 3.Display 4.size 5.exit Enter your choice: 1 Enter key and value: 12 13 Enter your choice: 1 Enter key and value: 14 29 Enter your choice: 3 Hash table Index 0 1 2 3 4 5 6 7 8 9 10 is: key -1 -1 12 -1 14 -1 -1 -1 -1 -1 -1 13 -1 29 -1 -1 -1 -1 -1 -1 -1 -1 value

Enter your choice: 2


BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

ADVANCED DATASTRUCTURES LAB MANUAL


Enter key: 14 The record is present at location 4. Enter your choice: 4 Size of dictionary is : 3

/*implement functions of Dictionary using Hashing ( Multiplication method)*/ #include<stdio.h> #include<conio.h> #include<math.h> #define MAX 200 struct DCT { int k; int val; }a[MAX]; voidDicHash(); int hash(int); void insert(int,int,int); void display(); void size(); void search(int); void DicHash() { int i; for(i=0;i<MAX;i++)
BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

ADVANCED DATASTRUCTURES LAB MANUAL


a[i].k=a[i].val=-1; } int hash(int key) { int hkey; float A=0.618; hkey=floor(2*(key*A)); return hkey; } void display() { int i; printf("Hash Table is\n "); for(i=0;i<MAX;i++) { if(a[i].k!=-1) printf("%d\t%d\t%d\n",i,a[i].k,a[i].val); } } void insert(int index,int key,int value) { int flag=0,i,count=0; if(a[index].k==-1) { a[index].k=key; a[index].val=value; } else { i=0; while(i<MAX) {

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

10

ADVANCED DATASTRUCTURES LAB MANUAL


if(a[i].k != -1) count++; i++; } if(count==MAX) { printf("Hash Table is Full "); return; } for(i=index+1;i<MAX;i++) if(a[i].k==-1) { a[i].k=key; a[i].val=value; flag=1; break; } for(i=0;i<index&&flag==0;i++) if(a[i].k==-1) { a[i].k=key; a[i].val=value; flag=1; break; } } } void size() { int i,len=0; for(i=0;i<MAX;i++)

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

11

ADVANCED DATASTRUCTURES LAB MANUAL


if(a[i].k != -1) len++; printf("size of the Dictionary is len %d",len); } void search(int search_key) { int i,j; i=hash(search_key); if(a[i].k==search_key) { printf("The record is present at location %d\n",i); return ; } if(a[i].k!=search_key) { for(j=i+1;j<MAX;j++) { if (a[j].k==search_key) { printf("The record is present at location %d\n" ,j); return; } } for(j=0;j<i;j++) if (a[j].k==search_key) { printf("The record is present at location %d\n",j); return; } printf("The record not found\n"); }

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

12

ADVANCED DATASTRUCTURES LAB MANUAL


else printf("The record is not present in the hash table\n"); } void main() { int ch; int hkey,key,value; clrscr(); DicHash();

do { printf("\n1.insert 2.search 3.display 4.size 5.exit\n enter your choice"); scanf("%d",&ch); switch(ch) { case 1:printf("enter key and value:"); scanf("%d%d",&key,&value); hkey=hash(key); insert(hkey,key,value); break; case 2:printf("enter key "); scanf("%d",&key); search(key); break; case 3:display(); break; case 4:size(); break; }

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

13

ADVANCED DATASTRUCTURES LAB MANUAL


}while(ch!=5);

EXPECTED OUTPUT: 1.Insert 2.search 3.display 4.size 5.exit Enter your choice: 1 Enter key and value: 23 456 Enter your choice:1 Enter key and value: 12 359 Enter your choice: 3 Hash table is 14 28 12 359 23 456

Enter your choice: 2 Enter key: 12 The record is present at location : 14


BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

14

ADVANCED DATASTRUCTURES LAB MANUAL


Enter your choice : 4 Size of the dictionary is : 2 Enter your choice: 5

EXERCISE2: AIM: To perform various operations i.e, insertions and deletions on AVL tree DESCRIPTION: AVL tree is a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees cannot be more than one for all nodes. INSERTION: To make sure that the given tree remains AVL after every insertion, we must augment the standard BST insert operation to perform some rebalancing. Following are two basic operations that can be performed to rebalance a BST without violating the BST property (keys(left)<key(root)<keys(right)). 1)LeftRotation 2)Right Rotation
T1, T2 and T3 are subtrees of the tree rooted with y (on left side) or x (on right side) y x / \ Right Rotation / \ x T3 - - - > T1 y / \ < - - - - - - / \ T1 T2 Left Rotation T2 T3 Keys in both of the above trees follow the following order keys(T1) < key(x) < keys(T2) < key(y) < keys(T3) So BST property is not violated anywhere.

STEPS TO FOLLOW FOR INSERTION Let the newly inserted node be w

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

15

ADVANCED DATASTRUCTURES LAB MANUAL


step1) Perform standard BST insert for w. step2) Starting from w, travel up and find the first unbalanced node. Let z be the first unbalanced node, y be the child of z that comes on the path from w to z and x be the grandchild of z that comes on the path from w to z. step3) Rebalance the tree by performing appropriate rotations on the subtree rooted with z There can be 4 possible cases that needs to be handled as x, y and z can be arranged in 4 ways. Following are the possible 4 arrangements: a) y is left child of z and x is left child of y (Left Left Case) b) y is left child of z and x is right child of y (Left Right Case) c) y is right child of z and x is right child of y (Right Right Case) d) y is right child of z and x is left child of y (Right Left Case)

a) Left Left Case


T1, T2, T3 and T4 are subtrees. z / \ y T4 Right Rotate (z) / \ - - - - - - - - -> x T3 / \ T1 T2 y x / T1 / \ T2 \ / T3 z \ T4

b) Left Right Case


z / \ / \ T1 T2 x / \ T3 T1 y T4 Left Rotate (y) - - - - - - - - -> / y / \ T2 x / \ T3 z \ T4 / Right Rotate(z) - - - - - - - -> y x \

z / \ / \ T1 T2 T3 T4

c) Right Right Case


z / \ / y \

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

16

ADVANCED DATASTRUCTURES LAB MANUAL


T1 / T2 y \ Left Rotate(z) - - - - - - - -> z x / \ / \ T1 T2 T3 T4

x / \ T3 T4

d) Right Left Case


z / \ x / \ z / \ / T2 x x \ / T3 y \ Left Rotate(z) - - - - - - - -> T4 z / \ / \ T1 T2 x / \ T3 T4

T1

y T4

/ \ T3

Right Rotate (y) - - - - - - - - ->

T1

T2

DELETION: To make sure that the given tree remains AVL after every deletion, we must augment the standard BST delete operation to perform some rebalancing. Following are two basic operations that can be performed to rebalance a BST without violating the BST property (keys(left)<key(root)<keys(right)). 1)LeftRotation 2) Right Rotation

STEPS TO FOLLOW FOR DELETION: Step1: Perform the normal BST deletion Step2: The current node must be one of the ancestors of the deleted node.Update the height of the current node. Step3:Get the balance factor of the current node Step4:If balance factor is greater than 1,then the current node is unballenced and we are either in left left case or left right case. To check whether it is Left Left case or Left Right case, get the balance factor of left subtree.If balance factor of the left subtree is greater than or equal to 0, then it is Left Left case, else Left Right case. Step5: If balance factor is less than -1, then the current node is unbalanced and we are either in Right Right case or Right Left case. To check whether it is Right Right case or Right Left case, get the balance

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

17

ADVANCED DATASTRUCTURES LAB MANUAL


factor of right subtree. If the balance factor of the right subtree is smaller than or equal to 0, then it is Right Right case, else Right Left case.

SAMPLE PROGRAM: /*C Program to insert and delete elements in an AVL Tree*/ #include<stdio.h> #include<conio.h> #include<alloc.h> #define FALSE 0 #define TRUE 1 struct AVLNode { int data; int balfact; struct AVLNode *left;
BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

18

ADVANCED DATASTRUCTURES LAB MANUAL


struct AVLNode *right; }; struct AVLNode * avlinsert(struct AVLNode *,int,int *); struct AVLNode * avldelete(struct AVLNode *,int,int *); struct AVLNode * del(struct AVLNode *,struct AVLNode *,int *); struct AVLNode * balr(struct AVLNode *,int *); struct AVLNode * ball(struct AVLNode *,int *); void display(struct AVLNode *); struct AVLNode * deltree(struct AVLNode *); int h; void main() { int ch,item; struct AVLNode *avl=NULL; clrscr(); do { printf("\n1.insert ...\n2.Deletion of an item...\n 3.Deletion of an avltree....\n 4.display 5.exit\n"); printf("Enter ur choice:"); scanf("%d",&ch); switch(ch) { case 1:printf("Enter item to be inserted in the avl tree:"); scanf("%d",&item); avl=avlinsert(avl,item,&h); break; case 2:printf("Enter item to be deleted from the avl tree:"); scanf("%d",&item); avl=avldelete(avl,item,&h);

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

19

ADVANCED DATASTRUCTURES LAB MANUAL


break; case 3:avl=deltree(avl); case 4:display(avl); break; } }while(ch!=5); } /* Inserts an element intp tree */ struct AVLNode * avlinsert(struct AVLNode *root,int data,int *h) { struct AVLNode *node1,*node2; if(!root) { root=(struct AVLNode *)malloc(sizeof(struct AVLNode)); root->data=data; root->left=NULL; root->right=NULL; root->balfact=0; *h=TRUE; return(root); } if(data < root->data) { root->left=avlinsert(root->left,data,h); /* If left subtree is higher */ if(*h) { switch(root->balfact) { case 1:

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

20

ADVANCED DATASTRUCTURES LAB MANUAL


node1=root->left; if(node1->balfact==1) { printf("\n Right Rotation alond %d. ",root->data); root->left=node1->right; node1->right=root; root->balfact=0; root=node1; } else { printf("\n Double rotation , left along %d",node1>data); node2=node1->right; node1->right=node2->left; printf(" then right along %d. \n",root->data); node2->left=node1; root->left=node2->right; node2->right=root; if(node2->balfact==1) root->balfact=-1; else root->balfact=0; if(node2->balfact==-1) node1->balfact=1; else node1->balfact=0; root=node2; } root->balfact=0; *h=FALSE;

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

21

ADVANCED DATASTRUCTURES LAB MANUAL


break; case 0: root->balfact=1; break; case -1: root->balfact=0; *h=FALSE; } } } if(data > root->data) { root->right=avlinsert(root->right,data,h); /* If the right subtree is higher */ if(*h) { switch(root->balfact) { case 1: root->balfact=0; *h=FALSE; break; case 0: root->balfact=-1; break; case -1: node1=root->right; if(node1->balfact==-1) { printf("\n Left rotation along %d. ",root->data); root->right=node1->left;

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

22

ADVANCED DATASTRUCTURES LAB MANUAL


node1->left=root; root->balfact=0; root=node1; } else { printf("\n Double rotation , right along %d",node1->data); node2=node1->left; node1->left=node2->right; node2->right=node1; printf(" then left along %d. \n",root->data); root->right=node2->left; node2->left=root; If(node2->balfact==-1) root->balfact=1; else root->balfact=0; if(node2->balfact==1) node1->balfact=-1;

else node1->balfact=0; root=node2; } root->balfact=0; *h=FALSE; } } } return(root); }

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

23

ADVANCED DATASTRUCTURES LAB MANUAL


/* Deletes an item from the tree */ struct AVLNode * avldelete(struct AVLNode *root,int data,int *h) { struct AVLNode *node,*tp; node=root;/*if there is only one node*/ if((root)&&(node->left==NULL)&&(node->right==NULL)) { *h=TRUE; free(node); root=NULL; return (root); } if(!root) { printf("\n No such data. "); return (root); } else {

if(data < root->data) { root->left=avldelete(root->left,data,h); if(*h) root=balr(root,h); } else { if(data > root->data) { root->right=avldelete(root->right,data,h);

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

24

ADVANCED DATASTRUCTURES LAB MANUAL


if(*h) root=ball(root,h); } else { node=root; if((node->right==NULL)&&(node->data==data)) { tp=node; root=node->left; printf("new:%d",root->data); getch(); tp->left=NULL; free(tp); *h=TRUE; return(root); } else { if(node->left==NULL) { root=node->right; *h=TRUE; free(node); } else { node->right=del(node->right,node,h); if(*h) root=ball(root,h); }

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

25

ADVANCED DATASTRUCTURES LAB MANUAL


} } } } return(root); } struct AVLNode * del(struct AVLNode *succ,struct AVLNode *node,int *h) { struct AVLNode *temp=succ; if(succ->left!=NULL) { succ->left=del(succ->left,node,h); if(*h) succ=balr(succ,h); } else { temp=succ; node->data=succ->data; succ=succ->right; free(temp); *h=TRUE; } return(succ); } /* Balance the tree , if right subtree is higher */ struct AVLNode * balr(struct AVLNode *root,int *h) { struct AVLNode *node1,*node2; switch(root->balfact) { case 1:

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

26

ADVANCED DATASTRUCTURES LAB MANUAL


root->balfact=0; break; case 0: root->balfact=-1; *h=FALSE; break; case -1: node1=root->right; if(node1->balfact <= 0) { printf("\n Left rotation along %d. ",root->data); root->right=node1->left; node1->left=root; if(node1->balfact==0) { root->balfact=-1; node1->balfact=1; *h=FALSE; }

else { root->balfact=node1->balfact=0; } root=node1; } else { printf("\n Double rotation , right along %d ",node1->data); node2=node1->left; node1->left=node2->right;

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

27

ADVANCED DATASTRUCTURES LAB MANUAL


node2->right=node1; printf(" then left along %d. \n",root->data); root->right=node2->left; node2->left=root; if(node2->balfact==-1) root->balfact=1; else root->balfact=0; if(node2->balfact==1) node1->balfact=-1; else node1->balfact=0; root=node2; node2->balfact=0; } } return (root); }

/* Balances the tree , if the left subtree is higher */ struct AVLNode * ball(struct AVLNode * root,int *h) { struct AVLNode *node1,*node2; switch(root->balfact) { case -1: root->balfact=0; break; case 0: root->balfact=1;

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

28

ADVANCED DATASTRUCTURES LAB MANUAL


*h=FALSE; break; case 1: node1=root->left; if(node1->balfact >= 0) { printf("]n Right rotation along %d. ",root->data); root->left=node1->right; node1->right=root; if(node1->balfact==0) { root->balfact=1; node1->balfact=-1; *h=FALSE; } else { root->balfact=node1->balfact=0; }

root=node1; } else { printf("\n Double rotation , left along %d ",node1->data); node2=node1->right; node1->right=node2->left; node2->left=node1; printf(" then right along %d .\n",root->data); root->left=node2->right; node2->right=root;

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

29

ADVANCED DATASTRUCTURES LAB MANUAL


if(node2->balfact==1) root->balfact=-1; else root->balfact=0; if(node2->balfact==-1) node1->balfact=1; else node1->balfact=0; root=node2; node2->balfact=0; } } return (root); } /*n Displays the tree in-order */ void display(struct AVLNode *root) { if(root!=NULL) { display(root->left); printf("%d\t",root->data); display(root->right); } } /* Deletes the tree */ struct AVLNode *deltree(struct AVLNode * root) { int h; root->left=NULL; root->right=NULL; free(root);

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

30

ADVANCED DATASTRUCTURES LAB MANUAL


root=NULL; return(root); }

EXPECTED OUTPUT: 1.INSERT 2.DELETE AN ITEM 3.DELETION OF AN AVL TREE 4.DISPLAY 5.EXIT ENTER UR CHOICE:1 Enter an element to be inserted in the AVL Tree:23 1.INSERT 2.DELETE AN ITEM 3.DELETION OF AN AVL TREE

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

31

ADVANCED DATASTRUCTURES LAB MANUAL


4.DISPLAY 5.EXIT ENTER UR CHOICE:1 Enter an element to be inserted in the AVL Tree:45 1.INSERT 2.DELETE AN ITEM 3.DELETION OF AN AVL TREE 4.DISPLAY 5.EXIT ENTER UR CHOICE:1 Enter an element to be inserted in the AVL Tree:12 1.INSERT 2.DELETE AN ITEM 3.DELETION OF AN AVL TREE 4.DISPLAY 5.EXIT ENTER UR CHOICE:4 12 23 45

1.INSERT 2.DELETE AN ITEM 3.DELETION OF AN AVL TREE 4.DISPLAY 5.EXIT ENTER UR CHOICE:1 Enter an element to be inserted in the AVL Tree:18 1.INSERT 2.DELETE AN ITEM 3.DELETION OF AN AVL TREE 4.DISPLAY 5.EXIT

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

32

ADVANCED DATASTRUCTURES LAB MANUAL


ENTER UR CHOICE:1 Enter an element to be inserted in the AVL Tree:22 Left Rotation along 12 1.INSERT 2.DELETE AN ITEM 3.DELETION OF AN AVL TREE 4.DISPLAY 5.EXIT ENTER UR CHOICE:4 12 18 22 23 45 1.INSERT 2.DELETE AN ITEM 3.DELETION OF AN AVL TREE 4.DISPLAY 5.EXIT ENTER UR CHOICE:1 Enter an element to be inserted in the AVL Tree:17 Right Rotation along 23 1.INSERT 2.DELETE AN ITEM 3.DELETION OF AN AVL TREE 4.DISPLAY 5.EXIT ENTER UR CHOICE:4 12 17 18 22 23 45 1.INSERT 2.DELETE AN ITEM 3.DELETION OF AN AVL TREE 4.DISPLAY 5.EXIT ENTER UR CHOICE:2 Enter element to be deleted:17

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

33

ADVANCED DATASTRUCTURES LAB MANUAL


1.INSERT 2.DELETE AN ITEM 3.DELETION OF AN AVL TREE 4.DISPLAY 5.EXIT ENTER UR CHOICE:4 12 18 22 23 45 1.INSERT 2.DELETE AN ITEM 3.DELETION OF AN AVL TREE 4.DISPLAY 5.EXIT ENTER UR CHOICE:1 Enter an element to be inserted in the AVL Tree:40 Left Rotation along 18 1.INSERT 2.DELETE AN ITEM 3.DELETION OF AN AVL TREE 4.DISPLAY 5.EXIT ENTER UR CHOICE:4 12 18 22 23 40 45 1.INSERT 2.DELETE AN ITEM 3.DELETION OF AN AVL TREE 4.DISPLAY 5.EXIT ENTER UR CHOICE:2 Enter Element to be deleted from the AVL Tree:23 1.INSERT 2.DELETE AN ITEM 3.DELETION OF AN AVL TREE
BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

34

ADVANCED DATASTRUCTURES LAB MANUAL


4.DISPLAY 5.EXIT ENTER UR CHOICE:2 Enter Element to be deleted from the AVL Tree:18 1.INSERT 2.DELETE AN ITEM 3.DELETION OF AN AVL TREE 4.DISPLAY 5.EXIT ENTER UR CHOICE:2 Enter Element to be deleted from the AVL Tree:40 Right Rotation along 45 1.INSERT 2.DELETE AN ITEM 3.DELETION OF AN AVL TREE 4.DISPLAY 5.EXIT ENTER UR CHOICE:4 12 22 45 EXERCISE:4 AIM:To implement operations on Binary heap DESCRIPTION: Binary Heap: A binary heap is defined as a complete binary tree with elements at every node being either less than or equal to the element at its left and the right child. MAX HEAP:The elements at every node will either be less than or equal to the element at its left and right child MIN HEAP:The elements at every node will either be greater than or equal to the element at its left and right child. There are two types of operations that are performed in Binary heap Insertion in a binary heap Deleting an element from a binary heap

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

35

ADVANCED DATASTRUCTURES LAB MANUAL


INSERT AN ELEMENT:In binary heap elements can be added randomly. ALGORITHM FOR INSERTION: Step1:Add the new value and set its pos SET N=N+1,POS=N Step2:SET HEAP[N]=VAL; Step3:Find appropriate location of VAL .Repeat steps 4,5 while POS<0 Step4:SET PAR=POS/2; Step5:if HEAP[POS]<=HEAP[PAR],then goto step6 Else swap HEAP[POS],HEAP[PAR] POS=PAR Step6:return DELETE AN ELEMENT:In binary heap only the element with the higest value is removed in case of MAX HEAP,and the element with the minimum value is removed in case of MINHEAP ALGORITHM FOR DELETION: Step1: [Remove the last node from the heap] SET LAST=HEAP[N],SET N=N-1 Step2: [Initialize]SET PTR=0,LEFT=1,RIGHT=2 Step3: SET HEAP[PTR]=LAST

Step4: Repeat steps 5 to 7 while LEFT<=N Step5: if HEAP[PTR]>=HEAP[LEFT] & goto step 8. Step6: if HEAP[RIGHT]<=HEAP[LEFT] then Swap HEAP[PTR],HEAP[LEFT] SET PTR=LEFT Else Swap HEAP[PTR],HEAP[RIGHT] SET PTR=RIGHT Step7: SET LEFT=2*PTR & RIGHT=LEFT+1 Step8: return HEAP[PTR]>=HEAP[RIGHT],then

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

36

ADVANCED DATASTRUCTURES LAB MANUAL

SAMPLE PROGRAM: /* Program to implement Binary heap operations */ #include<stdio.h> #include<conio.h> struct heap { int h[50]; int hsize; }he; void create();

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

37

ADVANCED DATASTRUCTURES LAB MANUAL


void insert(); int delete(); void size(); void display(); void size() { he.hsize=0; } void create() { Int i,root,ch; int p; printf("\n Enter Heap size: \n"); scanf("%d",&he.hsize); printf("\n Enter Elements of Heap : \n"); for(i=1;i<=he.hsize;i++) { scanf("%d",&he.h[i]); } for(root=he.hsize/2;root>=1;root--) { p=he.h[root]; ch=root*2; while(ch<=he.hsize) { if(ch<he.hsize&&he.h[ch+1]>he.h[ch]) ch++; if(p>he.h[ch]) break; he.h[ch/2]=he.h[ch]; ch=ch*2;

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

38

ADVANCED DATASTRUCTURES LAB MANUAL


} he.h[ch/2]=p; } } void display() { int i; if(he.hsize==0) printf("heap empty\n"); else { printf("\n\n HEAP ELEMENTS \n\n"); for(i=1;i<=he.hsize;i++) printf("%d\t",he.h[i]); } } void insert() { int el; int cn; printf("\n Enter Element: \n"); scanf("%d",&el); he.hsize++; cn=he.hsize; while(cn!=1 && he.h[cn/2]<el) { he.h[cn]=he.h[cn/2]; cn=cn/2; } he.h[cn]=el; }

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

39

ADVANCED DATASTRUCTURES LAB MANUAL


int delete() { int i,ch,el,le; if(he.hsize==0) { printf("\n heap empty. \n"); return(0); } else { el=he.h[1]; le=he.h[he.hsize]; he.hsize--; ch=2; while(ch<=he.hsize) { if(ch<he.hsize &&he.h[ch+1]>he.h[ch]) ch++; if(le>he.h[ch]) break; he.h[ch/2]=he.h[ch]; ch=ch*2; } he.h[ch/2]=le; return(el); } } void main() { int x,opt,i; size();

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

40

ADVANCED DATASTRUCTURES LAB MANUAL


do { printf(\n BINARY HEAP OPERATIONS); printf("\n1.Create \n2.Insert \n3.DELETE \n4.Display \n5.Exit"); printf("\n Enter Option \n"); scanf("%d",&opt); switch(opt) { case 1: create(); break; case 2: insert(); break; case 3: x=delete(); if(x!=0) printf("\n Deleted Element : \t %d",x); break; case 4:display(); break; case 5:break; }while(opt!=5); getch(); } EXPECTED OUTPUT: BINARY HEAP OPERATIONS 1.Create 2.Insert 3.Delete 4.Display 5.Exit Enter option:1 Enter Heap Size:5 }

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

41

ADVANCED DATASTRUCTURES LAB MANUAL


Enter Elements of Heap:12 45 23 86 56 BINARY HEAP OPERATIONS 1.Create 2.Insert 3.Delete 4.Display 5.Exit Enter option:4 Heap Elements: 86 56 23 12 45 BINARY HEAP OPERATIONS 1.Create 2.Insert 3.Delete 4.Display 5.Exit Enter option:2 Enter Element: 28 BINARY HEAP OPERATIONS 1.Create 2.Insert 3.Delete 4.Display 5.Exit Enter option:4 Heap Elements: 86 56 28 12 45 23 BINARY HEAP OPERATIONS 1.Create 2.Insert 3.Delete 4.Display 5.Exit

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

42

ADVANCED DATASTRUCTURES LAB MANUAL


Enter option:3 Deleted Element:86 BINARY HEAP OPERATIONS 1.Create 2.Insert 3.Delete 4.Display 5.Exit Enter option:4 Heap Elements : 56 45 28 12 23 BINARY HEAP OPERATIONS 1.Create 2.Insert 3.Delete 4.Display 5.Exit Enter option:5

EXERCISE-5: AIM: To implement operations on graphs DESCRIPTION: GRAPH: A graph is a collection of nodes called vertices and a collection of segments called lines,connecting parts of vertices Graphs may be Directed or Un-Directed. OPERATIONS ON GRAPHS: There are several primitive graph operations that provide the basic modules needed to maintain a graph.

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

43

ADVANCED DATASTRUCTURES LAB MANUAL


1. Insert a vertex. 2. Delete a vertex 3. Find a vertex. 4. Insert an edge. 5. Delete an edge. 6. Find edge. 1.INSERT A VERTEX:- Insert vertex adds a new vertex to a graph.When a vertex is inserted,it is disjoint,That is,it is not connected to any other vertices is just the first step in the insertion process. After a vertex is inserted,it must be connected. Algorithm for Insert Vertex: It allocates memory for a new vertex and copies the` data to it. Input:Graph is a reference to graph head structure datain contains data to be inserted into vertex. Output: New vertex allocated and data copied. Algorithm insertvertex(graph,datain) : Step1: Allocate memory for new vertex. Step2: Store datain in new vertex. Step3: Initialize metadata elements in newnode. Step4: Increment graph count. Step5: if(graph is empty) 5.1 Set graph first to newnode. STEP : 6 else 6.1 Search for insertion point 6.2 If(inserting before first vertex Set graph first to new vertex. 6.3 else insert new vertex in sequence. end insert vetex. 2.DELETE VERTEX: Delete vertex removes a vertex from the graph

when a vertex is deleted,all connecting edges are also removed .The first

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

44

ADVANCED DATASTRUCTURES LAB MANUAL


thing we have to do to delete a vertex is find it. Once we have found it, however we also need to make sure that it is disjoint,that is we need to ensure that there are no arcs leaving (or) entering the vertex. Algorithm for Delete Vertex:degree os 0. Input: Graph is a reference pointer to graph head key is the key of the vertex to be deleted. Output: Vertex deleted(if degree zero) Return: +1 if successful -1 if degree not zero -2 if key not found Algorithm delete vertex(graph,key) STEP : 1 STEP : 2 STEP : 3 STEP : 4 if(empty graph) 1.1 return -2 Search for vertex to be deleted. If vertex not found 3.1 return -2 Test degree of the vertex If(vertex indegree>0 OR outdegree>0) 4.1 return -1 STEP : 5 STEP : 6 STEP : 7 Delete vertex Decrement graph count return 1 It deletes an existing vertex only if its

End delete vertex. 3.FIND VERTEX:-Find vertex traverses a graph, looking for a special vertex. If the vertex is found its data are returned. If it is not found, an error is indicated. Algorithm to Find Vertex:-

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

45

ADVANCED DATASTRUCTURES LAB MANUAL


Input : Graph is reference to a graph head structure key is the key of Dataout is reference to data variable. Output Vertex data copied to dataout. Return: +1 isf successful -2 if key not found Algorithm retrieve vertex(graph,key,dataout) STEP : 1 If graph is empty return -2 STEP : 2 Search for vertex STEP : 3 if vertex found 3.1 move location pointer data to dataout Return 1 STEP : 4 otherwise return -2 End find vertex. 4.INSERT EDGE:- Add edge connects a vertex to a destination vertex. Two vertices must be specified, to add an edge. If the graph is a digraph, one of the vertices must be specified as the source and the other one as the destination. If a vertex tequires multiple edges, add an edge must be called once for each adjacent vertex.Insert arc (or) edge requires two points in the graph. The source vertex (fromptr) and the destination vertex(toptr).Each vertex is identified by its key value rather than by its physical address. Algorithm for Insert Edge: Input: Graph is reference to graph head structure fromkey is the key of the source vertex to key is the key of destination vertex. Output: Arc added to adjacency list. Return: +1 if successful

the vertex data.

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

46

ADVANCED DATASTRUCTURES LAB MANUAL


-2 if fromkey not found -3 if tokey not found

Algorithm insertArc(graph,fromkey,tokey) STEP : 1 Allocate memory for new arc STEP : 2 Search and set fromvertex. STEP : 3 if(from vertex not found) Return -2 STEP : 4 Search and set tovertex STEP : 5 if(tovetex not found) Return -3 STEP : 6 From and to vertices located, Insert new arc STEP : 7 Increment fromvertex outdegree STEP : 8 Increment tovertex indegreee STEP : 9 Set arc destination to tovertex STEP : 10 if(fromvertex arc list empty) 10.1 Set fromvertex first arc to new arc 10.2 Set new arc next arc to null 10.3 return 1 STEP : 11 Find insertion point in the arc list. STEP : 12 if(insert at beginning of arc list) 12.1 Insertion before first arc i.e set fromvertex First arc to new arc STEP : 13 Insert in arc list STEP : 14 return 1 End insertArc 4.DELETE EDGE: Delete edge removes one edge from a graph.to identify an arc, we need two vertices. The vertices are identified by their key. The algorithm therefore first searches the vertex list for the start vertex and searches the vertex list for the start vertex and searches its adjacency list

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

47

ADVANCED DATASTRUCTURES LAB MANUAL


for the destination vertex. After locating and deleting arc, the dergree in the form and to vertices is adjusted and the memory recycled.

Algorithm for Delete Edge: Input:Graph is reference to a graph head structure fromkey is the key of the source vertex tokey is the key of destination vertex Output: Vertex deleted. Return: +1 if successful -2 if fromkey not found -3 if tokey not found STEP 1 : if(empty graph) Return -2 STEP : 2 Search and set fromvertex to vertex with key equal to fromkey. STEP : 3 if(fromvertex not found) Return -2 STEP : 4 if(fromvertex arc list null) then Return -3 STEP : 5 Search and find arc with key equql to tokey STEP : 6 if(tokey not found) then Return -3 STEP : 7 7.1 Set tovertex to arc destination 7.2 delete arc 7.3 decrement fromvertex outdegree 7.4 decrement tovertex indegree 7.5 return End deleteArc

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

48

ADVANCED DATASTRUCTURES LAB MANUAL

SAMPLE PROGRAM: #include<stdio.h> struct node { struct node *next; char name; struct edge *adj; }*start = NULL; struct edge { char dest; struct edge *link; }; struct node *find( char item ); main() { int choice; char node, origin, destin; while ( 1 ) { printf(\n GRAPH OPERATIONS \t ); printf( "1.Insert a node\n" ); printf( "2.Insert an edge\n" ); printf( "3.Delete a node\n" ); printf( "4.Delete an edge\n" ); printf( "5.Display\n" ); printf( "6.Exit\n" ); printf( "Enter your choice : " );

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

49

ADVANCED DATASTRUCTURES LAB MANUAL


scanf( "%d", &choice );

switch ( choice ) { case 1:printf( "Enter a node to be inserted : " ); fflush( stdin ); scanf( "%c", &node ); insert_node( node ); break; case 2: printf( "Enter an edge to be inserted : " ); fflush( stdin ); scanf( "%c %c", &origin, &destin ); insert_edge( origin, destin ); break; case 3:printf( "Enter a node to be deleted : " ); fflush( stdin ); scanf( "%c", &node ); /*This fn deletes the node from header node list*/ delete_node( node ); /* This fn deletes all edges coming to this node */ delnode_edge( node ); break; case 4:printf( "Enter an edge to be deleted : " ); fflush( stdin ); scanf( "%c %c", &origin, &destin ); del_edge( origin, destin ); break;

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

50

ADVANCED DATASTRUCTURES LAB MANUAL


case 5:display(); break; case 6:exit(); default:printf( "Wrong choice\n" ); break;

} /*End of switch*/ } /*End of while*/ } /*End of main()*/ insert_node( char node_name ) { struct node * tmp, *ptr; tmp = malloc( sizeof( struct node ) ); tmp->name = node_name; tmp->next = NULL; tmp->adj = NULL; if ( start == NULL ) { start = tmp; return ; } ptr = start; while ( ptr->next != NULL ) ptr = ptr->next; ptr->next = tmp; } /*End of insert_node()*/ delete_node( char u ) { struct node * tmp, *q;

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

51

ADVANCED DATASTRUCTURES LAB MANUAL


if ( start->name == u ) { tmp = start; start = start->next; /* first element deleted */ free( tmp ); return ; }

q = start; while ( q->next->next != NULL ) { if ( q->next->name == u ) /* element deleted in between */ { tmp = q->next; q->next = tmp->next; free( tmp ); return ; } q = q->next; } /*End of while*/ if ( q->next->name == u ) /* last element deleted */ { tmp = q->next; free( tmp ); q->next = NULL; } } /*End of delete_node()*/ delnode_edge( char u ) { struct node * ptr; struct edge *q, *start_edge, *tmp;

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

52

ADVANCED DATASTRUCTURES LAB MANUAL


ptr = start; while ( ptr != NULL ) { /* ptr->adj points to first node of edge linked list */ if ( ptr->adj->dest == u ) { tmp = ptr->adj;

ptr->adj = ptr->adj->link; /* first element deleted */ free( tmp ); continue; /* continue searching in another edge lists */ } q = ptr->adj; while ( q->link->link != NULL ) { if ( q->link->dest == u )/* element deleted in between */ { tmp = q->link; q->link = tmp->link; free( tmp ); continue; } q = q->link; } /*End of while*/ if ( q->link->dest == u ) /* last element deleted */ { tmp = q->link;

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

53

ADVANCED DATASTRUCTURES LAB MANUAL


free( tmp ); q->link = NULL;} ptr = ptr->next; } /*End of while*/ } /*End of delnode_edge()*/ insert_edge( char u, char v ) { struct node * locu, *locv; struct edge *ptr, *tmp; locu = find( u ); locv = find( v );

if ( locu == NULL ) { printf( "Source node not present ,first insert node %c\n", u ); return ; } if ( locv == NULL ) { printf( "Destination node not present ,first insert node %c\n", v ); return ; } tmp = malloc( sizeof( struct edge ) ); tmp->dest = v; tmp->link = NULL; if ( locu->adj == NULL ) /* item added at the begining */ { locu->adj = tmp; return ; }

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

54

ADVANCED DATASTRUCTURES LAB MANUAL


ptr = locu->adj; while ( ptr->link != NULL ) ptr = ptr->link; ptr->link = tmp; } /*End of insert_edge()*/ struct node *find( char item ) { struct node *ptr, *loc; ptr = start; while ( ptr != NULL ) { if ( item == ptr->name ) { loc = ptr; return loc; } else ptr = ptr->next; } loc = NULL; return loc; } /*End of find()*/ del_edge( char u, char v ) { struct node * locu, *locv; struct edge *ptr, *tmp, *q; locu = find( u ); if ( locu == NULL ) { printf( "Source node not present\n" ); return ;

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

55

ADVANCED DATASTRUCTURES LAB MANUAL


} if ( locu->adj->dest == v ) { tmp = locu->adj; locu->adj = locu->adj->link; /* first element deleted */ free( tmp ); return ; } q = locu->adj; while ( q->link->link != NULL ) { if ( q->link->dest == v ) /* element deleted in between */

{ tmp = q->link; q->link = tmp->link; free( tmp ); return ; } q = q->link; } /*End of while*/ if ( q->link->dest == v ) /* last element deleted */ { tmp = q->link; free( tmp ); q->link = NULL; return ; } printf( "This edge not present in the graph\n" );

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

56

ADVANCED DATASTRUCTURES LAB MANUAL


} /*End of del_edge()*/ display() { struct node * ptr; struct edge *q; ptr = start; while ( ptr != NULL ) { printf( "%c ->", ptr->name ); q = ptr->adj; while ( q != NULL ) { printf( " %c", q->dest ); q = q->link;

} printf( "\n" ); ptr = ptr->next; } } /*End of display()*/ SAMPLE OUTPUT: GRAPH OPERATIONS 1.Insert a node 2.Insert an edge 3.Delete an edge 4.Display 5.Exit Enter your choice :1 Enter a node to be inserted:1 GRAPH OPERATIONS

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

57

ADVANCED DATASTRUCTURES LAB MANUAL


1.Insert a node 2.Insert an edge 3.Delete an edge 4.Display 5.Exit Enter your choice :1 Enter a node to be inserted:2 GRAPH OPERATIONS 1.Insert a node 2.Insert an edge 3.Delete an edge 4.Display 5.Exit Enter your choice :1 Enter a node to be inserted:3 GRAPH OPERATIONS 1.Insert a node 2.Insert an edge 3.Delete an edge 4.Display 5.Exit Enter your choice :5 1 -> 2 -> 3 -> GRAPH OPERATIONS 1.Insert a node 2.Insert an edge 3.Delete an edge 4.Display 5.Exit

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

58

ADVANCED DATASTRUCTURES LAB MANUAL


Enter your choice :2 Enter an edge to be inserted:1 2 GRAPH OPERATIONS 1.Insert a node 2.Insert an edge 3.Delete an edge 4.Display 5.Exit Enter your choice :2 Enter a edge to be inserted:2 3 GRAPH OPERATIONS 1.Insert a node 2.Insert an edge 3.Delete an edge 4.Display 5.Exit Enter your choice :2 Enter a fdge to be inserted:3 1 GRAPH OPERATIONS 1.Insert a node 2.Insert an edge 3.Delete an edge 4.Display 5.Exit Enter your choice :5 1 ->2 2 ->3 3 ->1 GRAPH OPERATIONS 1.Insert a node 2.Insert an edge

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

59

ADVANCED DATASTRUCTURES LAB MANUAL


3.Delete an edge 4.Display 5.Exit Enter your choice :3 Enter a node to be deleted:3 GRAPH OPERATIONS 1.Insert a node 2.Insert an edge 3.Delete an edge 4.Display 5.Exit Enter your choice :5 1 ->2 2->

GRAPH OPERATIONS 1.Insert a node 2.Insert an edge 3.Delete an edge 4.Display 5.Exit Enter your choice :4 Enter an edge to be deleted:1 2 GRAPH OPERATIONS 1.Insert a node 2.Insert an edge 3.Delete an edge 4.Display 5.Exit Enter your choice :5 1 ->

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

60

ADVANCED DATASTRUCTURES LAB MANUAL


2 -> GRAPH OPERATIONS 1.Insert a node 2.Insert an edge 3.Delete an edge 4.Display 5.Exit Enter your choice :6

EXERCISE:6 AIM:To implement Depth First Search for a graph nonrecursively. DESCRIPTION: Graph: A graph is a collection of nodes called vertices, and a collection of segments called lines, connecting parts of vertices. Graph Traversals: Traversal means visiting each node at least once in a graph. There are multiple paths to a vertex we may arrive at it from more than one direction as we traverse the graph. The traditional solution to this problem is to introduce a visited flag at each vertex. Before the traversal we can set the visited flag in each vertex to off. Then, as we set the visited flag to on to indicate that the data have been processed. Depth First Search:

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

61

ADVANCED DATASTRUCTURES LAB MANUAL


STACK data structure is suitable to achieve data first structure. Stack is a lost in first out structure. Stack data structure is used to traverse the graph in DFS manner. As the algorithm proceeds, nodes status will be changed. Initially, we assume all the nodes will be in un-processed state. When they are in stack, we assume they are in the ready state. When they leave the stack, we consider them that they are processed. DFS ALGORITHM: Step 1: Initialization a) Initialize stack to empty. b) Mark all nodes as not visited.Push node 0 onto the stack and mark it as visited. Step 2: While (stack is not empty) { a) Pop value from stack. b) Push all nodes adjacent to popped node and which have not been visited as yet onto the stack. c) Mark all pushed nodes as visited. } /*To implement Depth first search of a graph non-recursively*/ #include<stdio.h> #include<conio.h> #include<stdlib.h> int adj[5][5]={{0,1,1,1,0}, {1,0,1,0,1}, {1,1,0,1,0}, {1,0,1,0,1}, {0,1,0,1,0}}; int visited[30];

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

62

ADVANCED DATASTRUCTURES LAB MANUAL


struct stack { int s[30]; int sp; }; typedef struct stack stk; stk st; void push(int val); int pop(); int isempty(); void disp(); void main() { int i,j,val; int dfs[30]; st.sp=-1; clrscr(); for(i=0;i<5;i++) { printf(\n); for(j=0;j<5;j++) printf(%d\t,adj[i][j]); } i=0; push(i); visited[i]=1; disp(); while(isempty()==0) { val=pop(); dfs[i]=val;

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

63

ADVANCED DATASTRUCTURES LAB MANUAL


for(j=0;j<5;j++) { if(adj[val][j]==1) { if(visited[j]==0) { push(j); visited[j]=1; } } } disp(); i=i+1; } printf(\nDfs for the graph); for(i=0;i<5;i++) printf(%d\t,dfs[i]); getch(); }

int isempty() { if(st.sp==-1) { return1; } else return0; } void push(int val) {

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

64

ADVANCED DATASTRUCTURES LAB MANUAL


st.sp++; st.s[st.sp]=val; } int pop() { int val,ans; ans=isempty(); if(ans==0) { val=st.s[st.sp]; st.sp--; } else printf(\n stack is empty ); return(val); } void disp() { int i; printf(\n); if(isempty()==0) { printf(\n Elements of stack); for(i=st.sp;i>=0;i--) printf(\n%d\t,st.s[i]); } } EXPECTED OUTPUT: 0 1 1 0 1 1 1 0 0 1

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

65

ADVANCED DATASTRUCTURES LAB MANUAL


1 1 0 1 0 1 0 1 0 1 0 1 0 1 0

Elements of stack 0 Elements of stack 3 2 1 Elements of stack 4 2 1 Elements of stack 2 1 Elements of stack 1 Dfs for the graph 0 3 4 2 1

Exercise7:
AIM: Program for Breadth First Search algorithm DESCRIPTION: Graph: A graph is a collection of nodes called vertices and collection ofsegments called lines connecting parts of vertices. Graph Traversals: Traversals means visiting each node atleast once in a graph.There are multiple paths to a vertex.We may arrive at it from more than one direction as we traverse the graph.

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

66

ADVANCED DATASTRUCTURES LAB MANUAL


The traditional solution to this problem is to include a visited flag at each vertex. Before the traversal we set the visited flag in each vertex to off.Then,as we traverse the graph,we set the visited flag to on to indicate that the data have been processed. Breadth First search: Data structure Queue is used for BFS. Queue is a First In First Out (FIFO) structure. Queue Data structure is used to traverse the graph in BFS manner. As the algorithm proceeds,nodes status will be changed. Initially,we assume all the nodes will be in un-processed state. When they are in Queue,we assume they are in ready state. When they leave the Queue,we consider them that they are processed. BFS ALGORITHM: Step 1: Initialization a) Initialize Queue to empty. b) Mark all nodes as not visited. c) Insert node 0 and mark it as visited. Step 2: while(Queue is not empty) { Delete element from Queue. d) Insert nodes adjacent to deleted node and which have not been visited. e) Mark all inserted nodes as visited. }

SAMPLE PROGRAM: /*program for Breadth first search */ #include<stdio.h> #include<conio.h> int adj[30][30];
BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

67

ADVANCED DATASTRUCTURES LAB MANUAL


int visited[30]; struct queue { int data[30]; int front,rear; }; typedef struct queue que; que q; void insert(int val); int delete(); int isempty(); void disp(); void main() { int nodes; int i,j,val; int bfs[30]; q.rear=-1; q.front=0; clrscr(); printf(\n enter number of nodes in the graph); scanf(%d,&nodes); for(i=0;i<nodes;i++) { for(j=0;j<nodes;j++) { printf(n enter edges[%d][%d],i,j); scanf(%d,&adj[i][j]); } } for(i=0;i<nodes;i++)

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

68

ADVANCED DATASTRUCTURES LAB MANUAL


{ printf(\n); for(j=0;j<nodes;j++) printf(%d\t,adj[i][j]); } i=0; insert(i); visited[i]=1; disp(); while(isempty()==0) { val=delete(); bfs[i]=val; for(j=0;j<nodes;j++) { if(adj[val][j]==1) { if(visited[j]==0) { insert(j); visited[j]=1; } } }

disp() ; i=i+1; } printf(\n BFS for the graph \n); for(i=0;i<nodes;i++) printf(%d\t,BFS[i]);

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

69

ADVANCED DATASTRUCTURES LAB MANUAL


getch(); } void insert(int val) { q.rear++; q.data[q.rear]=val; } int delete() { int k,ans; k=isempty(); if(k==0) { ans=q.data[q.front]; q.front++; } else { printf(Queue is empty); ans=-1; } return(ans); }

int isempty() { int ans; if(q.rear<q.front) ans=1; else

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

70

ADVANCED DATASTRUCTURES LAB MANUAL


ans=0; return(ans); } void disp() { int ans,I; printf(data elements in Queue:\n); ans=isempty(); if(ans==0) { for(i=q.front;i<=q.rear;i++) printf(%d\n,q.data[i]); } else printf(Queue is empty \n); }

SAMPLE OUTPUT : Enter no.of nodes in the graph: 4 Enter Enter Enter Enter Enter Enter edges[0][0]: edges[0][1]: edges[0][2]: edges[0][3]: edges[1][0]: edges[1][1]: 0 1 1 1 0 0

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

71

ADVANCED DATASTRUCTURES LAB MANUAL


Enter Enter Enter Enter Enter Enter Enter Enter Enter Enter 0 0 0 0 0 Data elements in the Queue 3 2 1 Data elements in the Queue 2 1 Data elements in the Queue 1 Data elements in the Queue Queue is empty Bfs for the graph 0 3 2 1 edges[1][2]: 0 edges[1][3]: 1 edges[2][0]: 0 edges[2][1]: 0 edges[2][2]: 0 edges[2][3]: 1 edges[3][0]: 0 edges[3][1]: 0 edges[3][2]: 0 edges[3][3]: 0 1 1 1 0 0 0 0 0 0 1 1 0

Data elements in the Queue

EXERCISE-8: AIM: To implement KRUSKAL'S algorithm to generate a min-cost spanning tree. DESCRIPTION:

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

72

ADVANCED DATASTRUCTURES LAB MANUAL


Spanning tree: Let G be a graph containing n verticies.Then a tree which is derived from Gis called spanning tree if and only if the number of verticies in G should like in the derived tree Minimal Spanning Tree:A spanning tree whose total weight is least among the group of spanning trees is said to be Minimal Spanning Tree. KRUSKALS Algorithm:KRUSKALSalgorithm builds a minimum spanning tree by adding at each step the smallest weighted edge that has not all ready been added,provided it does not create a cycle.The algorithm stops when all edges are connected. Algorithm: Step1:Let G ={V,E} be a graph Step2:MST={} //MST is the set of all edges that make up minimal spanning tree Step3:Select the starting node While(MST has <n-1 edges) && (Eis not empty) { 3.1.Select(u,v) from E such that its weight is minimal 3.2. delete (u,v) from E 3.3. If adding (u.v) does not create a cycle,then add it to MST. }

SAMPLE PROGRAM:

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

73

ADVANCED DATASTRUCTURES LAB MANUAL


/* program to find minimum spanning tree using KRUSKALS Algorithm */ #include<stdio.h> #define INF 1000 char vertex[10]; int wght[10][10]; int span_wght[10][10]; int source struct Sort { int v1,v2; int weight; }que[20]; int n,ed,f,r; int cycle(int s,int d) { int j,k; if(source==d) return 1; for(j=0;j<n;j++) if(span_wght[d][j]!=INF && s!=j) { if(cycle(d,j)) return 1; } return 0; } void build_tree() { int i,j,w,k,count=0;

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

74

ADVANCED DATASTRUCTURES LAB MANUAL


for(count=0;count<n;f++) { i=que[f].v1; j=que[f].v2; w=que[f].weight; span_wght[i][j]=span_wght[j][i]=w; source=i; k=cycle(i,j); if(k) span_wght[i][j]=span_wght[j][i]=INF; else count++; } } void swap(int *i,int *j) { int t; t=*i; *i=*j; *j=t; } void main() { int i,j,k=0,temp; int sum=0; clrscr(); printf("\n\n\tKRUSKAL'S ALGORITHM TO FIND SPANNING TREE\n\n"); printf("\n\tEnter the No. of Nodes : "); scanf("%d",&n);

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

75

ADVANCED DATASTRUCTURES LAB MANUAL


for(i=0;i<n;i++) { printf("\n\tEnter %d value : ",i+1); fflush(stdin); scanf("%c",&vertex[i]); for(j=0;j<n;j++) { wght[i][j]=INF; span_wght[i][j]=INF; } } printf("\n\nGetting Weight\n"); for(i=0;i<n;i++) for(j=i+1;j<n;j++) { printf("\nEnter 0 if path Doesn't exist between %c to %c : ",vertex[i],vertex[j]); scanf("%d",&ed); if(ed>=1) { wght[i][j]=wght[j][i]=ed; que[r].v1=i; que[r].v2=j; que[r].weight=wght[i][j]; if(r) { for(k=0;k<r;k++) if(que[k].weight>que[r].weight) { swap(&que[k].weight,&que[r].weight); swap(&que[k].v1,&que[r].v1);

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

76

ADVANCED DATASTRUCTURES LAB MANUAL

swap(&que[k].v2,&que[r].v2); } } r++; } } clrscr(); printf("\n\tORIGINAL GRAPH WEIGHT MATRIX\n\n"); printf("\n\tweight matrix\n\n\t"); for(i=0;i<n;i++,printf("\n\t")) for(j=0;j<n;j++,printf("\t")) printf("%d",wght[i][j]); build_tree(); printf("\n\n\t\tMINIMUM SPANNING TREE\n\n"); printf("\n\t\tLIST OF EDGES\n\n"); for(i=0;i<n;i++) for(j=i+1;j<n;j++) if(span_wght[i][j]!=INF) { printf("\n\t\t%c ------ %c = %d ",vertex[i],vertex[j],span_wght[i][j]); sum+=span_wght[i][j]; } printf("\n\n\t\tTotal Weight : %d ",sum); getch(); }

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

77

ADVANCED DATASTRUCTURES LAB MANUAL


EXPECTED OUTPUT: KRUSKALS ALGORITHM TO FIND SPANNING TREE Enter the No. of Nodes:5 Enter 1 value:1 Enter 2 value:2 Enter 3 value:3 Enter 4 value:4 Enter 5 value:5 Getting Weight: Enter 0 if path doesnt exist between 1 to 2:2 Enter 0 if path doesnt exist between 1 to 2:4 Enter 0 if path doesnt exist between 1 to 2:3 Enter 0 if path doesnt exist between 1 to 2:0 Enter 0 if path doesnt exist between 1 to 2:0 Enter 0 if path doesnt exist between 1 to 2:2 Enter 0 if path doesnt exist between 1 to 2:1 Enter 0 if path doesnt exist between 1 to 2:1 Enter 0 if path doesnt exist between 1 to 2:0 Enter 0 if path doesnt exist between 1 to 2:4 ORIGINAL GRAPH WEIGHT MATRIX Weight matrix 1000 2 4 3 1000 2 1000 1000 2 1 4 1000 1000 1 1000 3 2 1 1000 4 1000 1 1000 4 1000

MINIMUM SPANNING TREE LIST OF EDGES 1------2=2 2------4=2 2------5=1 3------4=1 Total Weight:6

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

78

ADVANCED DATASTRUCTURES LAB MANUAL

Exercise 9: AIM: To implement Prims algorithm to generate a min-cost spanning tree. DESCRIPTION: Spanning tree: Let G be a graph containing n verticies.Then a tree which is derived from Gis called spanning tree if and only if the number of verticies in G should like in the derived tree Minimal Spanning Tree:A spanning tree whose total weight is least among the group of spanning trees is said to be Minimal Spanning Tree. PRIMS Algoritham:PRIMS algorithm builds a minimum spanning tree by deleting the edges sequentially that does not effect the graph.i.e that does not disconnect the graph until n-1 edges remain. Algorithm: Step1:Let G ={V,E} be a graph Step2:MST={}//MST is the set of all edges that make up minimal spanning tree Step3:Select the starting node While(MST has <n-1 edges) && (Eis not empty) { 3.1.Select a node from adjacent nodes to the node selected such that its Weight is minimal. 3.2. If deletion of that edge does not disconnect the graph then delete edge (u,v) from E.Otherwise add it to MST }

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

79

ADVANCED DATASTRUCTURES LAB MANUAL

SAMPLE PROGRAM: /* program to implement prims algorithm*/ #include<stdio.h> #define INF 1000 int vertex[10]; int wght[10][10]; int new_wght[10][10]; int closed[10]; int n; int inclose(int i,int n1) { /*chk for the ith vertex presence in closed*/ int j; for(j=0;j<=n1;j++) if(closed[j]==i) return 1; return 0; } void buildtree() { int i=0,j,count=0; int min,k,v1=0,v2=0; closed[0]=0; while(count<n-1)

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

80

ADVANCED DATASTRUCTURES LAB MANUAL


{ min=INF; for(i=0;i<=count;i++) for(j=0;j<n;j++) if(wght[closed[i]][j]<min && !inclose(j,count))

{ min=wght[closed[i]][j]; v1=closed[i]; v2=j; } new_wght[v1][v2]=new_wght[v2][v1]=min; count++; closed[count]=v2; printf("\nScan getch(); } } void main() { int i,j,ed,sum=0; clrscr(); printf("\n\n\tPRIM'S ALGORITHM TO FIND SPANNING TREE\n\n"); printf("\n\tEnter the No. of Nodes : "); scanf("%d",&n); for(i=0;i<n;i++) { vertex[i]=i+1; for(j=0;j<n;j++) { : %d %d---------%d wght = %d \n",count,v1+1,v2+1,min);

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

81

ADVANCED DATASTRUCTURES LAB MANUAL


wght[i][j]=INF; new_wght[i][j]=INF; } } printf("\n\nGetting Weight.\n");

printf("\n\tEnter 0 if path doesn't exist between {v1,v2} else enter the wght\n"); for(i=0;i<n;i++) for(j=i+1;j<n;j++) { printf("\n\t%d -------- %d : ",vertex[i],vertex[j]); scanf("%d",&ed); if(ed>=1) wght[i][j]=wght[j][i]=ed; } getch(); clrscr(); printf("\n\n\t\tNODES CURRENTLY ADDED TO SPANNING TREE\n\n"); buildtree(); printf("\n\tNEW GRAPH WEIGHT MATRIX\n\n"); printf("\n\tweight matrix\n\n\t"); for(i=0;i<n;i++,printf("\n\t")) for(j=0;j<n;j++,printf("\t")) printf("%d",new_wght[i][j]); printf("\n\n\t\tMINIMUM SPANNING TREE\n\n"); printf("\n\t\tLIST OF EDGES\n\n"); for(i=0;i<n;i++) for(j=i+1;j<n;j++) if(new_wght[i][j]!=INF)

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

82

ADVANCED DATASTRUCTURES LAB MANUAL


{ printf("\n\t\t%d ------ %d = %d ",vertex[i],vertex[j],new_wght[i][j]); sum+=new_wght[i][j];} printf("\n\n\t Total Weight : %d ",sum); getch(); }

EXPECTED OUTPUT: Enter the No. of Nodes:5 Getting Weight: Enter 0 if path doesnt exist between {v1,v2} else enter the wght 1--------2:2 2--------3:4 1--------4:3 1--------5:0 2--------3:0 2--------4:2 2--------5:1 3--------4:1 3--------5:0 4--------5:4 NODES CURRENTLY ADDED TO SPANNING TREE Scan:1 1---------2 Scan:2 2---------5 Scan:3 2---------4 Scan:4 4---------3 Wght=2 Wght=1 Wght=4 Wght=1

NEW GRAPH WEIGHT MATRIX Weight matrix 1000 2 1000 1000 1000 2 1000 1000 2 1 1000 1000 1000 1 1000 10000 2 1 1000 1000 1000 1 1000 1000 1000

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

83

ADVANCED DATASTRUCTURES LAB MANUAL


MINIMUM SPANNING TREE LIST OF EDGES 1------2=2 2------4=2 2------5=1 3------4=1 Total Weight:6

EXERSICE10: AIM: To implement Dijkstras algorithm to find shortest path in the graph. DESCRIPTION: DIJKSTRAS Algorithm:For finding shortest path by using Dijkstras algorithm we have given a weighted graph and we need to find out minimum distance route between any given two stations Algorithm: Step1:select the source node and mark it as processed Step2: select all the stations i.e neighbours of source station and mark them as ready and update their mininmum distances as the distances from source Step3:Repeat step4 till destination station status becomes processed Step4:Select the station which is having minimum distance out of the stations which are in the ready status.Make status of selected station as processed and update all of its unprocessed,and update ready state nodes minimum distance by adding distance from selected station to that station and distance of selected station from source

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

84

ADVANCED DATASTRUCTURES LAB MANUAL

SAMPLE PROGRAM: /*program queue*/ #include<stdio.h> #include<stdlib.h> int main() { int dist[10][10],sta[10],min[10],via[10]; int i,j,k,source,dest,amin,n,dd,t; printf("Enter Number Of Nodes"); scanf("%d",&n); printf("Enter Weights"); for(i=0;i<n;i++) for(j=0;j<n;j++) scanf("%d",&dist[i][j]); for(i=0;i<n;i++) { sta[i]=0; min[i]=32767; } to implement dijkstras algorithm using priority

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

85

ADVANCED DATASTRUCTURES LAB MANUAL


printf("Enter Source AND Destination indexes"); scanf("%d%d",&source,&dest); k=source; amin=0; while(sta[dest]!=2) { sta[k]=2; for(i=0;i<n;i++) { if(dist[k][i]&&sta[i]!=2) { dd=amin+dist[k][i]; if(dd<min[i]) { min[i]=dd; via[i]=k; } sta[i]=1; } } amin=32767; for(i=0;i<n;i++) if(sta[i]==1 && min[i]<amin) { amin=min[i]; k=i; } } printf("Backtracking"); printf("%c->",'A'+dest); for(k=via[dest];k!=source;k=via[k])

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

86

ADVANCED DATASTRUCTURES LAB MANUAL


printf("%c->",'A'+k); printf("%c",'A'+source); return 0; }

EXPECTED OUTPUT: Enter Number Of Nodes:5 Enter Weights: 0 3 4 2 0 3 0 0 6 7 4 0 0 1 0 2 6 1 0 5 0 7 0 5 0

Enter Source AND Destination indexes: 0 4 Backtracking:E->D->A

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

87

ADVANCED DATASTRUCTURES LAB MANUAL

EXERCISE-11: AIM: To implement BOYER-Moore algorithm for pattern matching. DESCRIPTION: The Boyer-Moore algorithm scans the characters of the pattern from right to left beginning with the rightmost character. During the testing of a possible placement of pattern P against text T, a mismatch of text character T[i] = c with the corresponding pattern character P[j] is handled as follows: If c is not contained anywhere in P, then shift the pattern P completely past T[i]. Otherwise, shift P until an occurrence of character c in P gets aligned with T[i].This technique likely to avoid lots of needless comparisons by significantly shifting pattern relative to text. Last Function: We define a function last(c) that takes a character c from the alphabet and specifies how far may shift the pattern P if a character equal to c is found in the text that does not match the pattern

index of the last occurrence last(c)= of c in pattern P -1


For example consider

if c is in P otherwise

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

88

ADVANCED DATASTRUCTURES LAB MANUAL


T: 0 1 2 3 4 5 6 7 8 9 a b a c A A B A C C a b a C A B 0 1 2 3 4 5

P:

last(a) is the index of the last (rightmost) occurrence of 'a' in P, which is 4. last(c) is the index of the last occurrence of c in P, which is 3 'd' does not exist in the pattern there we have last (d) = -1. c last(c ) A 4 B C 3 D -1

Now, for 'b' notice T: a b A C A a B a C c P: a b A C A b

Therefore, last(b) is the index of last occurrence of b in P, which is 5 The complete last(c) function c last(c ) A 4 B 5 C 3 D -1

Boyer-Moore algorithm : BOYER_MOORE_MATCHER (T, P) Input: Text with n characters and Pattern with m characters Output: Index of the first substring of T matching P 1. 2. 3. 4. 5. 6. 7. 8. Compute function last i m-1 j m-1 Repeat If P[j] = T[i] then if j=0 then return i // we have a match else

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

89

ADVANCED DATASTRUCTURES LAB MANUAL


9. 10. 11. 12. 13. 14. 15. i i -1 j j -1 else i i + m - Min(j, 1 + last[T[i]]) j m -1 until i > n -1 Return "no match"

SAMPLE PROGRAM: #include<stdio.h> #include<conio.h> void preBmBc(char *x, int m, int bmBc[ ]) { int i; for (i = 0; i < ASIZE; ++i) bmBc[i] = m; for (i = 0; i < m - 1; ++i) bmBc[x[i]] = m - i - 1; } void suffixes(char *x, int m, int *suff) { int f, g, i; suff[m - 1] = m; g = m - 1;

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

90

ADVANCED DATASTRUCTURES LAB MANUAL


for (i = m - 2; i >= 0; --i) { if (i > g && suff[i + m - 1 - f] < i - g) suff[i] = suff[i + m - 1 - f]; else { if (i < g) g = i; f = i; while (g >= 0 && x[g] == x[g + m - 1 - f]) --g; suff[i] = f - g; } } }

void preBmGs(char *x, int m, int bmGs[]) { int i, j, suff[XSIZE]; suffixes(x, m, suff); for (i = 0; i < m; ++i) bmGs[i] = m; j = 0; for (i = m - 1; i >= 0; --i) if (suff[i] == i + 1) for (I=1; j < m - 1 - i; ++j) if (bmGs[j] == m) bmGs[j] = m - 1 - i; for (i = 0; i <= m - 2; ++i) bmGs[m - 1 - suff[i]] = m - 1 - i; } void BM(char *x, int m, char *y, int n)

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

91

ADVANCED DATASTRUCTURES LAB MANUAL


{ int i, j, bmGs[XSIZE], bmBc[ASIZE]; /* Preprocessing */ preBmGs(x, m, bmGs); preBmBc(x, m, bmBc); /* Searching */ j = 0; while (j <= n - m) { for (i = m - 1; i >= 0 && x[i] == y[i + j]; --i); if (i < 0) { OUTPUT(j); j += bmGs[0]; }

else j += MAX(bmGs[i], bmBc[y[i + j]] - m + 1 + i); } } void main( ) { char *x,*y; int bmBc[ ], bmGs[ ] ,*suff char *p="advanced data structures"; char *q="nced"; int m=strlen(p); int n=strlen(q); } EXPECTED OUTPUT: Pattern nced is present in text:

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

92

ADVANCED DATASTRUCTURES LAB MANUAL


inadvanced data structures

EXERCISE-12: AIM: To implement Knuth-Morris-Pratt algorithm for pattern matching. DESCRIPTION: DEFINITION: The KMP algorithm compares the pattern to the text in leftto-right, but shifts the pattern, P more intelligently than the brute-force algorithm. When a mismatch occurs, what is the most we can shift the pattern so as to avoid redundant comparisons. The answer is that the largest prefix of P[0..j] that is a suffix of P[1..j] EXPLANATION:The KnuthMorrisPratt string searching algorithm searches for occurrences of a "word" W within a main "text string" S by employing the observation that when a mismatch occurs, the word itself embodies sufficient information to determine where the next match could begin, thus bypassing re-examination of previously matched characters. performs the comparisons from left to right; preprocessing phase in O(m) space and time complexity;

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

93

ADVANCED DATASTRUCTURES LAB MANUAL


searching phase in O(n+m) time complexity (independent from the

alphabet size);

SAMPLE PROGRAM: /*Program to implement Knuth-Morris-Pratt pattern matching */ #include<stdio.h> #include<string.h> #include<stdlib.h> void cp(char p[],int pp[]) { int q,k,m; m=strlen(p); pp[1]=0; k=0; for(q=2;q<m;q++)

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

94

ADVANCED DATASTRUCTURES LAB MANUAL


{ while(k>0 && p[k+1]!=p[q]) k=pp[k]; if(p[k+1]==p[q]) k=k+1; pp[q]=k; } } void kmp(char t[],char p[]) { int pp[50],i,q,k,m,n; n=strlen(t); m=strlen(p); cp(p,pp); q=0; for(i=1;i<n;i++) { while(q>0 && p[q+1]!=t[i]) q=pp[q]; if(p[q+1]==t[i]) q++; if(q==m-1) { printf("String Found"); break; } } if(i==n) printf("String Not Found"); } void main()

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

95

ADVANCED DATASTRUCTURES LAB MANUAL


{ char t[100],p[50]; clrscr(); printf("Enter Actual String"); scanf("%s",&t); printf("Enter String To Be Found"); scanf("%s",&p); kmp(t,p); getch(); } EXPECTED OUTPUT: Enter Actual String:acaabcaaba Enter String To Be Found:bca String Found Enter actual String:aaabbbacaaa Enter String To Be Found:bca String Not Found

EXERCISE 13: AIM: To implement a program for Radix sort DESCRIPTION:

BVC COLLEGE OF ENGINEERING RAJAHMUNDRY

96

Você também pode gostar