Escolar Documentos
Profissional Documentos
Cultura Documentos
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
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
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;
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++;
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)
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);
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
/*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
10
11
12
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; }
13
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
14
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.
15
z / \ / \ T1 T2 T3 T4
16
x / \ T3 T4
T1
y T4
/ \ T3
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
17
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
19
20
21
22
23
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);
24
25
26
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;
27
/* 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;
28
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;
29
30
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
31
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
32
33
34
35
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
36
SAMPLE PROGRAM: /* Program to implement Binary heap operations */ #include<stdio.h> #include<conio.h> struct heap { int h[50]; int hsize; }he; void create();
37
38
39
40
41
42
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.
43
when a vertex is deleted,all connecting edges are also removed .The first
44
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:-
45
46
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
47
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
48
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 : " );
49
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;
50
} /*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;
51
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;
52
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;
53
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 ; }
54
55
{ 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" );
56
} 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
57
58
59
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 ->
60
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:
61
62
63
64
65
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.
66
SAMPLE PROGRAM: /*program for Breadth first search */ #include<stdio.h> #include<conio.h> int adj[30][30];
BVC COLLEGE OF ENGINEERING RAJAHMUNDRY
67
68
disp() ; i=i+1; } printf(\n BFS for the graph \n); for(i=0;i<nodes;i++) printf(%d\t,BFS[i]);
69
70
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
71
EXERCISE-8: AIM: To implement KRUSKAL'S algorithm to generate a min-cost spanning tree. DESCRIPTION:
72
SAMPLE PROGRAM:
73
74
75
76
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(); }
77
MINIMUM SPANNING TREE LIST OF EDGES 1------2=2 2------4=2 2------5=1 3------4=1 Total Weight:6
78
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 }
79
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)
80
{ 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);
81
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)
82
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
83
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
84
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
85
86
87
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
if c is in P otherwise
88
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
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
89
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;
90
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)
91
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:
92
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;
93
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++)
94
95
96