You are on page 1of 29

7.

IMPLEMENTATION OF AVL TREE INSERTION


AIM Write a C program to implement insertion on AVL Tree using single rotation and double rotation. ALGORITHM 1. 2. Initialize node structure containing a data element X and two pointers for left subtree and right subtree. If the choice is Insert, a. Accept the data element X and subtree Ts address b. If the subtree T is null, then create a new treenode T and set X as Ts element and Ts left & Ts right as NULL. c. Otherwise if X is less than the data element of treenode T, recursively insert the element as Ts left. i. Check if the difference between the height of left and right subtree is equal to 2 a) If insertion is at left subtree do the single rotation with left. b) Else do the double rotation with left. d. Otherwise if X is greater than the data element of treenode T, recursively insert the element as Ts left. i. Check if the difference between the height of left and right subtree is equal to 2 a) If insertion is at left subtree do the single rotation with right. b) Else do the double rotation with right.

SOURCE CODE #include<stdio.h> #include<conio.h> #include<stdlib.h> struct node { int data; struct node *left; struct node *right; int ht; }*root=NULL; int height(struct node *p) { if(p==NULL) return -1; else return p->ht; } struct node *singlerotatewithleft(struct node *k2) { struct node *k1; k1=k2->left; k2->left=k1->right; k1->right=k2; k2->ht=max(height(k2->left),height(k2->right))+1; k1->ht=max(height(k1->left),k2->ht)+1; return k1; } struct node *singlerotatewithright(struct node *k1) { struct node *k2; k2=k1->right; k1->right=k2->left; k2->left=k1; k1->ht=max(height(k1->right),height(k1->left))+1; k2->ht=max(height(k2->right),k1->ht)+1; return k2; } struct node *doublerotatewithleft(struct node *k3) { k3->left=singlerotatewithright(k3->left); return singlerotatewithleft(k3); }

struct node *doublerotatewithright(struct node *k1) { k1->right=singlerotatewithleft(k1->right); return singlerotatewithright(k1); } void inorder(struct node *t) { if(t!=NULL) { inorder(t->left); printf("%d ",t->data); inorder(t->right); } } struct node *insert(int x,struct node *t) { if(t==NULL) { t=(struct node *)malloc(sizeof(struct node)); t->data=x; t->left=NULL; t->right=NULL; t->ht=0; } else if(x<t->data) { t->left=insert(x,t->left); if(height(t->left)-height(t->right)==2) if(x<t->left->data) t=singlerotatewithleft(t); else t=doublerotatewithleft(t); } else if(x>t->data) { t->right=insert(x,t->right); if(height(t->right)-height(t->left)==2) if(x>t->right->data) t=singlerotatewithright(t); else t=doublerotatewithright(t); } t->ht=max(height(t->left),height(t->right))+1; return t; }

void main() { int ch,x; struct node *t; clrscr(); do { printf("enter the data"); scanf("%d",&x); if(root==NULL) { root=insert(x,root); } else root=insert(x,root); printf("do u want to continue inserting node? 1/0?"); scanf("%d",&ch); }while(ch!=0); inorder(root); getch(); } OUTPUT enter the data3 do u want to continue inserting node? 1/0?1 enter the data2 do u want to continue inserting node? 1/0?1 enter the data1 do u want to continue inserting node? 1/0?1 enter the data4 do u want to continue inserting node? 1/0?1 enter the data 5 do u want to continue inserting node? 1/0?1 enter the data 6 do u want to continue inserting node? 1/0?1 enter the data 7 do u want to continue inserting node? 1/0?1 enter the data 16 do u want to continue inserting node? 1/0?1 enter the data 15

do u want to continue inserting node? 1/0?1 enter the data 14 do u want to continue inserting node? 1/0?1 enter the data 13 do u want to continue inserting node? 1/0?1 enter the data 12 do u want to continue inserting node? 1/0?1 enter the data 11 do u want to continue inserting node? 1/0?1 enter the data 10 do u want to continue inserting node? 1/0?1 enter the data 8 do u want to continue inserting node? 1/0?1 enter the data 9 do u want to continue inserting node? 1/0?0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

RESULT The AVL Tree insertion is implemented in C using the single rotation, double rotation operations and is executed and verified.

8. IMPLEMENTATION OF PRIORITY QUEUE USING HEAPS


AIM Write a C program to implement priority queue using heaps. ALGORITHM Insertion 1. Add the element to the bottom level of the heap. 2. Compare the added element with its parent; i. ii. Deletion 1. Replace the root of the heap with the last element on the last level. 2. Compare the new root with its children; i. ii. If they are in the correct order, stop. If not, swap the element with one of its children and return to the previous step. (Swap with its smaller child in a min-heap and its greater child in a max-heap.) Findmin In a min-heap the minimum element will be at the root;display the root element. SOURCE CODE #include<stdio.h> #include <stdlib.h> #define MinData (-32767) typedef int ElementType; typedef struct HeapStruct *PriorityQueue; struct HeapStruct { int Capacity; int Size; ElementType *Elements; }; If they are in the correct order(if min-heap parent should be smaller than children and in max-heap parent should be greater than children), stop. If not, swap the element with its parent and return to the previous step.

PriorityQueue Initialize (int MaxElements) { PriorityQueue H; H = malloc(sizeof ( struct HeapStruct)); if (H == NULL) printf("Out of space!!!"); else { H->Elements = malloc((MaxElements + 1)*sizeof(ElementType)); if (H->Elements == NULL) { printf("Out of space!!!"); } else { H->Capacity = MaxElements; H->Size = 0; H->Elements[ 0 ] = MinData; } return H; } } void MakeEmpty(PriorityQueue H) { H->Size = 0; } void Insert(ElementType X, PriorityQueue H) { int i; if (IsFull(H)) { printf("Priority queue is full"); return; } for (i = ++H->Size; H->Elements[ i / 2 ] > X; i /= 2) H->Elements[ i ] = H->Elements[ i / 2 ]; H->Elements[ i ] = X;

int IsEmpty(PriorityQueue H) { return H->Size == 0; }

int IsFull(PriorityQueue H) { return H->Size == H->Capacity; } ElementType DeleteMin(PriorityQueue H) { int i, Child; ElementType MinElement, LastElement; if (IsEmpty(H)) { printf("Priority queue is empty"); return H->Elements[ 0 ]; } MinElement = H->Elements[ 1 ]; LastElement = H->Elements[ H->Size-- ]; for (i = 1; i * 2 <= H->Size; i = Child) { Child = i * 2; if (Child != H->Size && H->Elements[ Child + 1 ] < H->Elements[ Child ]) Child++; if (LastElement > H->Elements[ Child ]) H->Elements[ i ] = H->Elements[ Child ]; break; H->Elements[ i ] = LastElement; return MinElement; } ElementType FindMin(PriorityQueue H) { if (!IsEmpty(H)) return H->Elements[ 1 ]; printf("Priority Queue is Empty"); return H->Elements[ 0 ]; } void Destroy(PriorityQueue H) { free(H->Elements); free(H); }

else }

void display(PriorityQueue H) { int i; for(i=1;i<=H->Size;i++) printf("%d ",H->Elements[i]); } void main() { PriorityQueue h; int x,y,z,u,v; char ch; clrscr(); printf("\nEnter the maximum number of elements for the Priority Queue: "); scanf("%d",&x); h=Initialize(x); menu: printf("\nPriority Queue"); printf("\n1.Insert\n2.Delete\n3.Display\n4.FindMin\n5.Exit"); while(1) { printf("enter the choice "); scanf("%d",&u); switch(u) { case 1:printf("Enter the Data: "); scanf("%d",&z); Insert(z,h); break; case 2:v=DeleteMin(h); printf("\nThe deleted element is: %d",v); break; case 3:display(h); break; case 4:z=FindMin(h); printf(The minimum element is %d ,z); break; case 5: exit(0); } } }

OUTPUT Enter the maximum number of elements for the Priority Queue:8 Priority Queue 1.Insert 2.Delete 3.Display 4.FindMin 4.Exit enter the choice 1 Enter the Data: 50 enter the choice 1 Enter the Data: 40 enter the choice 1 Enter the Data: 67 enter the choice 1 Enter the Data: 23 enter the choice 1 Enter the Data: 45 enter the choice 1 Enter the Data: 33 enter the choice 1 Enter the Data: 24 enter the choice 1 Enter the Data: 18 enter the choice 3 18 23 24 40 45 67 33 50 enter the choice 1 Enter the Data: 19 Priority queue is full enter the choice 2 The deleted element is: 18 enter the choice 3

23 40 24 50 45 67 33 enter the choice 4 The minimum element is 23 enter the choice 5

RESULT Thus a C program is written to implement priority queues using heaps ad executed and verified.

9. IMPLEMENTATION OF HASHING TECHNIQUES


AIM Write a C Program to implement the hashing techniques using separate chaining and linear probing methods. ALGORITHM Separate Chaining method 1. Define the node (listnode)with a data element and pointer to the node. 2. Define a structure (hash table) with tablesize and pointer to the pointer of the listnode. 3. Allocate space for the hash table. 4. Create a header node for the lists in the hash table. 5. Insert new element into the hash table by applying hash function to the data and locate the corresponding list. 6. If collision occurs the data goes to the same list at the end. 7. To find a data element , apply the hash function and locate the list in the hash table, then Locate the element in the identified list. 8. Linear Probing method 1. Allocate an array(table) of size n (n depends on the number of elements). 2. Use the hash function Hash(x)+F(i)) mod tablesize to find the slot (key) for insertion i. If the slot is free insert the element. ii. If not, search for free slots sequentially till end of the array is reached and insert the element in the free slot found. iii. If no slot is free, then wrap around and search to find free slots till key-1. a. If a slot is found insert the element b. Otherwise display the table is full.

SOURCE CODE Separate Chaining method #include<stdio.h> #include<conio.h> typedef struct listnode *list,*position; typedef struct hashtbl* hashtable; #define tablesize 10 struct listnode { int element; struct listnode *next; }; struct hashtbl { int tabsize; list thelists[tablesize]; }; hashtable initialize_table(int tabsize ) { hashtable h; int i; h = malloc ( sizeof (struct hashtbl) ); if( h == NULL ) printf("Out of space!!!"); h->tabsize = tablesize; for(i=0; i<h->tabsize; i++ ) { h->thelists[i] = malloc( sizeof (struct listnode) ); if(h->thelists[i] == NULL ) printf("Out of space!!!"); else h->thelists[i]->next = NULL; } return h; } void display(hashtable h) { position p; list l; int i; for(i=0;i<h->tabsize;i++) { l = h->thelists[i]; p = l->next; printf("Bucket %d: ",i); while( p != NULL)

{ } printf("\n");

printf("%d ",p->element); p = p->next;

} }

position find( int key, hashtable h) { position p; list l; l = h->thelists[ key % h->tabsize]; p = l->next; while( (p != NULL) && (p->element != key) ) p = p->next; return p; } void insert( int key, hashtable h ) { position pos, newcell; list l; pos = find( key, h ); if( pos == NULL ) { newcell = malloc(sizeof(struct listnode)); if( newcell == NULL ) printf("Out of space!!!"); else { l = h->thelists[ key % h->tabsize]; newcell->element = key; newcell->next = l->next; l->next = newcell; } } } void main() { int i,num; hashtable h; h=initialize_table(tablesize); printf("\n Collision handling by separate chaining\n Table size is 10\n"); for(i=0;i<tablesize;i++) { printf("enter the element to be inserted\n"); scanf("%d",&num);

insert(num,h); } display(h); } Linear Probing method #include<stdio.h> #include<conio.h> #define max 10 int a[max],count=0; void display(int a[max]) { int i; printf("\n HASH TABLE "); for(i=0; i<max; i++) printf("\n%d\t%d",i,a[i]); } void linearprobing(int key, int num) { int i=0,flag=0; if(a[key]==-1) a[key]=num; else { if(count==max) { printf("Hash table is full\n"); display(a); getch(); exit(0); } for(i=key+1; i<max; i++) if(a[i]==-1) { a[i]=num; flag=1; break; } for(i=0; i<key && flag==0; i++) if(a[i]==-1) { a[i]=num; flag=1; break; } }

count++;

void main() { int num,key,i; char ans; clrscr(); printf("\n Collision handling by linear probing\n Table size is 10\n"); for(i=0; i<max; i++) a[i]=-1; i=1; do { printf("\n Enter the element to be inserted:\n "); scanf("%d",&num); key=num%max; linearprobing(key,num); }while(i<=max); display(a); getch(); } OUTPUT Collision handling by linear probing Table size is 10 Enter the element to be inserted: 5 Enter the element to be inserted: 10 Enter the element to be inserted: 11 Enter the element to be inserted: 4 Enter the element to be inserted: 15 Enter the element to be inserted: 6 Enter the element to be inserted: 12 Enter the element to be inserted: 22 Enter the element to be inserted: 8

Enter the element to be inserted: 9 Enter the element to be inserted: 2 Hash table is full HASH TABLE Slot Element 0 1 2 3 4 5 6 7 8 9 10 11 12 22 4 5 15 6 8 9

Collision handling by separate chaining Table size is 10 enter enter enter enter enter enter enter enter enter enter the the the the the the the the the the 0: 1: 2: 3: 4: 5: 6: 7: 8: 9: element element element element element element element element element element 11 22 12 15 25 36 6 7 17 9 to to to to to to to to to to be be be be be be be be be be inserted inserted inserted inserted inserted inserted inserted inserted inserted inserted 6 12 25 15 11 17 9 22 7 36

Bucket Bucket Bucket Bucket Bucket Bucket Bucket Bucket Bucket Bucket

RESULT Thus the C program to implement hashing techniques using separate chaining and linear probing methods is implemented, executed and verified.

11. IMPLEMENTATION OF DIJKSTRA'S ALGORITHM USING PRIORITY QUEUES


AIM Write a program to implement Dijkstras algorithm using priority queues. ALGORITHM 1. Let the node at which we are starting be called the initial node. Let the distance of node Y be the distance from the initial node to Y. 2. Assign to every node a tentative distance value: set it to zero for our initial node and to infinity for all other nodes. 3. Mark all nodes unvisited. Set the initial node as current. Create a set of the unvisited nodes called the unvisited set consisting of all the nodes except the initial node. 4. For the current node, consider all of its unvisited neighbors and calculate their tentative distances. For example, if the current node A is marked with a distance of 6, and the edge connecting it with a neighbor B has length 2, then the distance to B (through A) will be 6 + 2 = 8. If this distance is less than the previously recorded tentative distance of B, then overwrite that distance. Even though a neighbor has been examined, it is not marked as "visited" at this time, and it remains in the unvisited set. 5. When we are done considering all of the neighbors of the current node, mark the current node as visited and remove it from the unvisited set. A visited node will never be checked again. 6. If the destination node has been marked visited (when planning a route between two specific nodes) or if the smallest tentative distance among the nodes in the unvisited set is infinity (when planning a complete traversal), then stop. The algorithm has finished. 7. Select the unvisited node that is marked with the smallest tentative distance, and set it as the new "current node" then go back to step 4.

SOURCE CODE #include<stdio.h> #include<conio.h> #define zero 998 #define max 7 int allselected(int *selected) { int i; for(i=0; i<max; i++) if(selected[i]==0) return 0; return 1; } void shortpath(int cost[][max],int *preced, int *dist) { int selected[max]={0}; int current=0,i,k,dc,smalldist,newdist; for(i=0; i<max; i++) dist[i]=zero; selected[current]=1; dist[0]=0; current=0; while(!allselected(selected)) { smalldist=zero; dc=dist[current]; for(i=0; i<max; i++) { if(selected[i]==0) { newdist=dc+cost[current][i]; if(newdist<dist[i]) { dist[i]=newdist; preced[i]=current; } if(dist[i]<smalldist) { smalldist=dist[i]; k=i; } } } current=k; selected[current]=1; }

} void main() { int cost[max][max]={{zero,2,zero,1,zero,zero,zero}, {zero,zero,zero,3,10,zero,zero}, {4,zero,zero,zero,6,zero,zero}, {zero,zero,2,zero,2,8,4}, {zero,zero,zero,zero,zero,zero,6}, {zero,zero,zero,zero,zero,zero,zero}, {zero,zero,zero,zero,zero,1,zero} }; int i,preced[max]={0},dist[max]; clrscr(); shortpath(cost,preced,dist); for(i=0; i<max; i++) printf("\n Shortest path from 1 to i+1=%d",i,dist[i]); getch(); } OUTPUT Shortest Shortest Shortest Shortest Shortest Shortest Shortest RESULT Thus the C program to implement Dijkstras algorithm using priority queues is written, executed and verified. path path path path path path path from from from from from from from 1 1 1 1 1 1 1 to to to to to to to 1=0 2=2 3=3 4=1 5=3 6=6 7=5

12.
AIM

A. IMPLEMENTATION OF PRIMS ALGORITHM

Write a C program to implement prims algorithm.

ALGORITHM 1. Get the number of vertices n and the cost adjacency matrix as input. 2. Get the weight for all the edges. 3. Choose a vertex as starting vertex v 4. After a vertex is selected declare it known and update dw =min (dw,cw,v) for each unknown vertex w adjacent to v. 5. Continue step 4 until all vertices are declared known SOURCE CODE #include<stdio.h> #include<conio.h> int a,b,u,v,n,i,j,ne=1; int visited[10]={0},min,mincost=0,cost[10][10]; void main() { clrscr(); printf("\n Enter the number of vertices:"); scanf("%d",&n); printf("\n Enter the cost adjacency matrix:\n"); for(i=1;i<=n;i++) for(j=1;j<=n;j++) { scanf("%d",&cost[i][j]); if(cost[i][j]==0) cost[i][j]=999; } visited[1]=1; printf("\n"); while(ne<n) { for(i=1,min=999;i<=n;i++) for(j=1;j<=n;j++) if(cost[i][j]<min) if(visited[i]!=0) {

min=cost[i][j]; a=u=i; b=v=j; } if(visited[u]==0 || visited[v]==0) { printf("\n Edge %d:(%d %d) cost:%d",ne++,a,b,min); mincost+=min; visited[b]=1; } cost[a][b]=cost[b][a]=999; } printf("\n Minimum cost=%d",mincost); getch(); } OUTPUT Enter the number of nodes: 7 Enter the cost adjacency matrix: 0241000 2003700 4002050 1320784 0 10 0 7 0 0 6 0058001 0004610 Edge 1:(1 4) cost:1 Edge 2:(1 2) cost:2 Edge 3:(4 3) cost:2 Edge 4:(4 7) cost:4 Edge 5:(7 6) cost:1 Edge 6:(7 5) cost:6 Minimum cost=16 RESULT Thus the C program to implement prims algorithm to find the minimum spanning tree is written, executed and verified.

12.
AIM

B. IMPLEMENTATION OF KRUSKALS ALGORITHM

Write a C program to implement kruskals algorithm. ALGORITHM 1. Get the no. of vertices (V), edges (E) and costs (C ) 2. Sort the edges in increasing order of costs 3. Build a minimum spanning tree edge by edge 3.1 Include an edge in minimum spanning tree 3.1.1 If its inclusion does not form a cycle with the edges already in T. 3.1.2 Else reject the edge 3.2 Repeat the above step for V-1 vertices SOURCE CODE #include<stdio.h> #include<conio.h> #include<stdlib.h> int i,j,k,a,b,u,v,n,ne=1; int min,mincost=0,cost[9][9],parent[9]; int find(int); int uni(int,int); void main() { clrscr(); printf("\nEnter the no. of vertices\n"); scanf("%d",&n); printf("\nEnter the cost adjacency matrix\n"); for(i=1;i<=n;i++) { for(j=1;j<=n;j++) { scanf("%d",&cost[i][j]); if(cost[i][j]==0) cost[i][j]=999; } } printf("\nThe edges of the minimum spanning tree are\n\n"); while(ne<n) {

for(i=1,min=999;i<=n;i++) { for(j=1;j<=n;j++) { if(cost[i][j]<min) { min=cost[i][j]; a=u=i; b=v=j; } } } u=find(u); v=find(v); if(uni(u,v)) { printf("\nedge %d (%d,%d) =%d\n",ne++,a,b,min); mincost +=min; } OUTPUT Enter the number of vertices: 7 Enter the cost adjacency matrix: 0241000 2003700 4002050 1320784 0 10 0 7 0 0 6 0058001 0004610 The edges of the minimum spanning tree are edge 1 (1,4) =1 edge 2 (6,7) =1 edge 3 (1,2) =2 edge 4 (3,4) =2 edge 5 (4,7) =4 edge 6 (5,7) =6 Minimum cost = 16

RESULT Thus the C program to implement kruskals algorithm to find the minimum spanning tree is written, executed and verified.

13.

IMPLEMENTATION OF BACKTRACKING ALGORITHM FOR KNAPSACK PROBLEM

AIM Write a C program to implement backtracking algorithm for knapsack problem. ALGORITHM 1. To solve the knapsack problem: given n rods, use a bit array A[1..n]. Set A[i] to 1 if rod i is to be used. Exhaustively search through all binary strings A[1..n] testing for a fit. 2. Use the binary string algorithm. Pruning: let be length remaining, A[m] = 0 is always legal A[m] = 1 is illegal if sm > ; prune here

3. Prints all solutions to knapsack problem with n rods of length s1. . .sn, and knapsack of length L. 4. Comment solve knapsack problem with m rods, knapsack size 5. If m = 0 then If = 0 then print (A) 6. else . A[m]:= 0; knapsack (m 1, ) 7. f sm then A[m]:= 1; knapsack (m 1, sm) SOURCE CODE #include<stdio.h> #include<conio.h> int c,c1,n,i,j,k; int q[10],x[10][10],w[10],p[10],max; void get(); void knapsack(); void display(); void get() { printf("\n Enter the number of objects: "); scanf("%d",&n); printf("\n Enter the size of the knapsack: "); scanf("%d",&c); printf("\n Enter the weight and profit of the objects "); for(i=1; i<=n; i++) {

printf("\n Enter the weight %d: ",i); scanf("%d",&w[i]); printf("\n Enter the profit of weight %d: ",i); scanf("%d",&p[i]); } }

void knapsack() { for(j=1; j<=n; j++) { for(i=1; i<=n; i++) { x[i][j]=0; q[j]=0; } c1=c; for(i=j; i<=n && w[i]<=c1; i++) { x[j][i]=1; c1=c1-w[i]; q[j]=q[j]+x[j][i]*p[i]; } } max=q[1]; for(i=1; i<=n; i++) { if(q[i]>max) { max=q[i]; k=i; } } } void display() { printf("\n The suboptimal solutions \t profit"); for(i=1; i<=n; i++) { printf("\n"); for(j=1; j<=n; j++) { printf("%d\t",x[i][j]); } printf("%d\t",q[i]); } printf("\n Maximum profit is %d",max); }

OUTPUT Enter the number of objects: 5 Enter the size of the knapsack: 12 Enter the weight and profit of the objects Enter the weight 1: 3 Enter the profit of weight 1: 5 Enter the weight 2: 4 Enter the profit of weight 2: 4 Enter the weight 3: 2 Enter the profit of weight 3: 4 Enter the weight 4: 4 Enter the profit of weight 4: 3 Enter the weight 5: 5 Enter the profit of weight 5: 1 1 0 0 0 0 The suboptimal solutions 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 profit 13 11 8 4 1

Maximum profit is 13 RESULT Thus the C program to implement backtracking algorithm for knapsack problem is written, executed and verified.

You might also like