Sei sulla pagina 1di 45

DATA STRUCTURES AND ALGORITHMS II IT-III SEM

Prepared By Mr.J.Gokulraj,Asst Professor IT Dept

IT 2205 DATA STRUCTURES AND ALGORITHMS LAB 0 0 3 2 Aim:

To develop programming skills in design and implementation of data structures and their applications.

1. Implement singly and doubly linked lists. 2. Represent a polynomial as a linked list and write functions for polynomial addition. 3. Implement stack and use it to convert infix to postfix expression 4. Implement array-based circular queue and use it to simulate a producer consumer problem. 5. Implement an expression tree. Produce its pre-order, in-order, and post-order traversals. 6. Implement binary search tree. 7. Implement priority queue using heaps 8. Implement hashing techniques. 9. Implement Dijkstra's algorithm using priority queues 10. Implement a backtracking algorithm for Knapsack problem
List of Equipments and components for A Batch of 30 students (1 per batch)

1. SOFTWARE REQUIRED TURBOC version 3 or GCC version 3.3.4. 2. OPERATING SYSTEM WINDOWS 2000 / XP / NT OR LINUX 3. COMPUTERS REQUIRED 30 Nos. (Minimum Requirement : Pentium III or Pentium IV with 256 RAM and 40 GB hard disk)

INDEX S.no 1 2 3 4 5 6 7 8 9 10 11 Ex.no 1.A 1.B 2 3 4 5 6 7 8 9 10 Date Title To write a C program to create a singly linked list implementation. To write a C program to create a singly linked list implementation. To write a C program to represent a polynomial as a linked list and write functions for polynomial addition To write a C program to implement stack and use it to convert infix to postfix expression. To Implement array-based circular queue and use it to simulate a producer consumer problem. To write a C program to implement an expression tree. Produce its pre-order, in-order, and post-order traversals. To write a C program to implement binary search tree. To implement priority queue using heaps. To implement the hashing techniques To implement Dijkstra's algorithm using priority queues. To Implement a backtracking algorithm for Knapsack problem Page .no 4 9 14 19 24 27 31 38 44 48 52 Mark

Ex. No: 1(a)

IMPLEMENTATION OF A LINKED LIST SINGLY LINKED 3

LIST Date: AIM:To write a C program to create a singly linked list implementation. ALGORITHM:1. Start the program. 2. Get the choice from the user. 3. If the choice is to add records, get the data from the user and add them to the list. 4. If the choice is to delete records, get the data to be deleted and delete it from the list. 5. If the choice is to display number of records, count the items in the list and display. 6. If the choice is to search for an item, get the item to be searched and respond yes if the item is found, otherwise no. 7. Terminate the program PROGRAM

#include<stdio.h> #include<conio.h> #include<stdlib.h> #define NULL 0 typedef struct list { int no; struct list *next; }LIST; LIST *p,*t,*h,*y,*ptr,*pt; void create( void ); void insert( void ); void delet( void ); void display ( void ); int j,pos,k=1,count; void main() { int n,i = 1,opt; clrscr(); p = NULL; printf("%d",sizeof(LIST)); printf( "Enter the no of nodes :\n " ); scanf( "%d",&n ); count = n; while( i <= n) { create(); i++; } printf("\nEnter your option:\n"); printf("1.Insert \t 2.Delete \t 3.Display \t 4.Exit\n"); do
4

{ scanf("%d",&opt); switch( opt ) { case 1: insert(); count++; break; case 2: delet(); count--; if ( count == 0 ) { printf("\n List is empty\n"); } break; case 3: printf("List elements are:\n"); display(); break; } printf("\nEnter your option \n"); }while( opt != 4 ); getch(); } void create ( ) { if( p == NULL ) { p = ( LIST * ) malloc ( sizeof ( LIST ) ); printf( "Enter the element:\n" ); scanf( "%d",&p->no ); p->next = NULL; h = p; } else { t = ( LIST * ) malloc (sizeof( LIST )); printf( "\nEnter the element" ); scanf( "%d",&t->no ); t->next = NULL; p->next = t; p = t; } } void insert() { t=h; p = ( LIST * ) malloc ( sizeof(LIST) ); printf("Enter the element to be insrted:\n"); scanf("%d",&p->no); printf("Enter the position to insert:\n"); scanf( "%d",&pos );
5

if( pos == 1 ) { h = p; h->next = t; } else { for(j=1;j<(pos-1);j++) t = t->next; p->next = t->next; t->next = p; t=p; } } void delet() { //t=h; printf("Enter the position to delete:\n"); scanf( "%d",&pos ); if( pos == 1 ) { h = h->next ; } else { t = h; for(j=1;j<(pos-1);j++) t = t->next; pt=t->next->next; free(t->next); t->next= pt; } } void display() { t = h; while( t->next != NULL ) { printf("\t%d",t->no); t = t->next; } printf( "\t %d\t",t->no ); }

OUTPUT Enter the no of nodes : 3 Enter the element:1

Enter the element 2 Enter the element 3 Enter your option: 1.Insert 2.Delete 3.Display 3 List elements are: 1 2 3 Enter your option 1 Enter the element to be insrted: 12 Enter the position to insert: 1 Enter your option 3 List elements are: 12 1 2 3 Enter your option 1 Enter the element to be insrted: 13 Enter the position to insert: 3 Enter your option 1 Enter the element to be insrted: 14 Enter the position to insert:6 Enter your option 3 List elements are: 12 1 13 2 3 14 Enter your option 2 Enter the position to delete:1 Enter your option 3 List elements are: 1 13 2 3 14 Enter your option 2 Enter the position to delete:3 Enter your option 3 List elements are: 1 13 3 14 Enter your option 2 Enter the position to delete:4 Enter your option 3 List elements are: 1 13 3 Enter your option viva How to allocate memory dynamically? How to implement linked list using structures? Result: Thus, the singly linked list program was implemented, and executed successfully. 4.Exit

Ex. No : 1(b) Date:

IMPLEMENTATION OF DOUBLY LINKED LIST

AIM:To write a C program to create a Double linked list implementation. ALGORITHM:1Start the program. 2Get the choice from the user. 3.If the choice is to add records, get the data from the user and add them to the list. 4If the choice is to delete records, get the data to be deleted and delete it from the list. 5.If the choice is to display number of records, count the items in the list and display. 6.If the choice is to search for an item, get the item to be searched and respond yes if the item is found, otherwise no. 7.Terminate the program PROGRAM #include<stdio.h> #include<conio.h> #include<stdlib.h> #define NULL 0 typedef struct list { int no; struct list *next; struct list *pre; }LIST; LIST *p,*t,*h; void create( void ); void insert( void ); void delet( void ); void display ( void ); int j,pos,k=1,count; void main() { int n,i = 1,opt; clrscr(); p = NULL; printf( "Enter the no of nodes :\n " ); scanf( "%d",&n ); count = n; while( i <= n) { create(); i++; } printf("\nEnter your option:\n"); printf("1.Insert \t 2.Delete \t 3.Display \t 4.Exit\n"); do { scanf("%d",&opt); switch( opt ) { case 1: insert(); count++; break; case 2: delet(); count--;

if ( count == 0 ) { printf("\n List is empty\n"); } break; case 3: printf("List elements are:\n"); display(); break; } printf("\nEnter your option \n"); }while( opt != 4 ); getch(); } void create ( ) { if( p == NULL ) { p = ( LIST * ) malloc ( sizeof ( LIST ) ); printf( "Enter the element:\n" ); scanf( "%d",&p->no ); p->next = NULL; p->pre = NULL; h = p; } else { t = ( LIST * ) malloc (sizeof( LIST )); printf( "\nEnter the element" ); scanf( "%d",&t->no ); t->next = NULL; p->next = t; t->pre = p; p = t; } } void insert() { t=h; p = ( LIST * ) malloc ( sizeof(LIST) ); printf("Enter the element to be insrted:\n"); scanf("%d",&p->no); printf("Enter the position to insert:\n"); scanf( "%d",&pos ); if( pos == 1 ) { h = p; h->next = t; t->pre = h; h->pre = NULL; } else { for(j=1;j<(pos-1);j++) t = t->next; p->next = t->next; t->next = p; p->pre = t; } } void delet() {

printf("Enter the position to delete:\n"); scanf( "%d",&pos ); if( pos == 1 ) { h = h->next ; h->pre = NULL; } else { t = h; for(j=1;j<(pos-1);j++) t = t->next; t->next = t->next->next; t->next->pre = t; free( t->next ); } } void display() { t = h; while( t->next != NULL ) {printf("%d\n",t->no); t = t->next; } printf( "%d",t->no ); } OUTPUT Enter the no of nodes :3 Enter the element3 Enter your option: 1.Insert 2.Delete 3.Display 3 List elements are: 1 2 3 Enter your option 1 Enter the element to be insrted:22 Enter the position to insert:1 Enter your option 3 List elements are: 22 1 2 3 Enter your option 1 Enter the element to be insrted: 11 Enter the position to insert:5 Enter your option 3 List elements are: 22 1 2 3 11 Enter your option 2 Enter the position to delete: 1 Enter your option 3 List elements are: 1 2 3 11 Enter your option 2 Enter your option 4

4.Exit

10

Viva Questions: A Linked list can grow and shrink in size dynamically at _______. Write an algorithm to detect loop in a linked list. Reverse a linked list. Delete an element from a doubly linked list. Implement an algorithm to reverse a singly linked list. (with and without recursion) Implement an algorithm to reverse a doubly linked list How would you find a cycle in a linked list? Try to do it in O(n) time. Try it using a constant amount of memory.

Result: Thus, the doubly linked list program was implemented, and executed successfully.

Ex.No:2.

POLYNOMIAL ADDITION

11

Date: AIM:To write a C program to represent a polynomial as a linked list and write functions for polynomial addition ALGORITHM:1. Start the program 2. Get the coefficients and powers for the two polynomials to be added. 3. Add the coefficients of the respective powers. 4. Display the added polynomial. 5. Terminate the program. PROGRAM # include <stdio.h> # include <malloc.h> struct node { float coef; int expo; struct node *link; }; struct node *poly_add(struct node *,struct node *); struct node *enter(struct node *); struct node *insert(struct node *,float,int); main( ) { struct node *p1_start,*p2_start,*p3_start; p1_start=NULL; p2_start=NULL; p3_start=NULL; printf("Polynomial 1 :\n"); p1_start=enter(p1_start); printf("Polynomial 2 :\n"); p2_start=enter(p2_start); p3_start=poly_add(p1_start,p2_start); printf("Polynomial 1 is : "); display(p1_start); printf("Polynomial 2 is : "); display(p2_start); printf("Added polynomial is : "); display(p3_start); }/*End of main()*/ struct node *enter(struct node *start) { int i,n,ex; float co; printf("How many terms u want to enter : "); scanf("%d",&n); for(i=1;i<=n;i++) { printf("Enter coeficient for term %d : ",i); scanf("%f",&co); printf("Enter exponent for term %d : ",i); scanf("%d",&ex); start=insert(start,co,ex);

12

} return start; }/*End of enter()*/ struct node *insert(struct node *start,float co,int ex) { struct node *ptr,*tmp; tmp= malloc(sizeof(struct node)); tmp->coef=co; tmp->expo=ex; /*list empty or exp greater than first one */ if(start==NULL || ex>start->expo) { tmp->link=start; start=tmp; } else { ptr=start; while(ptr->link!=NULL && ptr->link->expo>ex) ptr=ptr->link; tmp->link=ptr->link; ptr->link=tmp; if(ptr->link==NULL) /*item to be added in the end */ tmp->link=NULL; } return start; }/*End of insert()*/ struct node *poly_add(struct node *p1,struct node *p2) { struct node *p3_start,*p3,*tmp; p3_start=NULL; if(p1==NULL && p2==NULL) return p3_start; while(p1!=NULL && p2!=NULL ) { tmp=malloc(sizeof(struct node)); if(p3_start==NULL) { p3_start=tmp; p3=p3_start; } else { p3->link=tmp; p3=p3->link; } if(p1->expo > p2->expo) { tmp->coef=p1->coef; tmp->expo=p1->expo; p1=p1->link; } else if(p2->expo > p1->expo) { tmp->coef=p2->coef; tmp->expo=p2->expo; p2=p2->link;

13

} else if(p1->expo == p2->expo) { tmp->coef=p1->coef + p2->coef; tmp->expo=p1->expo; p1=p1->link; p2=p2->link; } }/*End of while*/ while(p1!=NULL) { tmp=malloc(sizeof(struct node)); tmp->coef=p1->coef; tmp->expo=p1->expo; if (p3_start==NULL) /*poly 2 is empty*/ { p3_start=tmp; p3=p3_start; } else { p3->link=tmp; p3=p3->link; } p1=p1->link; }/*End of while */ while(p2!=NULL) { tmp=malloc(sizeof(struct node)); tmp->coef=p2->coef; tmp->expo=p2->expo; if (p3_start==NULL) /*poly 1 is empty*/ { p3_start=tmp; p3=p3_start; } else { p3->link=tmp; p3=p3->link; } p2=p2->link; }/*End of while*/ p3->link=NULL; return p3_start; }/*End of poly_add() */ display(struct node *ptr) { if(ptr==NULL) { printf("Empty\n"); return; } while(ptr!=NULL) { printf("(%.1fx^%d) + ", ptr->coef,ptr->expo); ptr=ptr->link; } printf("\b\b \n"); /* \b\b to erase the last + sign */ }/*End of display()*/

14

OUTPUT Polynomial 1 : How many terms u want to enter : 3 Enter coeficient for term 1 : 5 Enter exponent for term 1 : 2 Enter coeficient for term 2 : 3 Enter exponent for term 2 : 1 Enter coeficient for term 3 : 1 Enter exponent for term 3 : 0 Polynomial 2 : How many terms u want to enter : 3 Enter coeficient for term 1 : 3 Enter exponent for term 1 : 3 Enter coeficient for term 2 : 4 Enter exponent for term 2 : 2 Enter coeficient for term 3 : 4 Enter exponent for term 3 : 1 Polynomial 1 is : (5.0x^2) + (3.0x^1) + (1.0x^0) Polynomial 2 is : (3.0x^3) + (4.0x^2) + (4.0x^1) Added polynomial is : (3.0x^3) + (9.0x^2) + (7.0x^1) + (1.0x^0)

Result: Thus, the Polynomial program was implemented, executed and verified successfully.

Ex.No:3. Date:

CONVERT INFIX TO POSTFIX EXPRESSION

15

AIM:To write a C program to implement stack and use it to convert infix to postfix expression. ALGORITHM:1. Start the program 2. Scan the Infix string from left to right. 3. Initialise an empty stack. 4. If the scannned character is an operand, add it to the Postfix string. If the scanned character is an operator and if the stack is empty Push the character to stack. If the scanned character is an Operand and the stack is not empty,

compare the precedence of the character with the element on top of the stack (topStack). If topStack has higher precedence over the scanned character Pop the stack else Push the scanned character to stack. Repeat this step as long as stack is not empty and topStack has precedence over the character. Repeat this step till all the characters are scanned. 5. (After all characters are scanned, we have to add any character that the stack may have to the Postfix string.) If stack is not empty add topStack to Postfix string and Pop the stack. Repeat this step as long as stack is not empty. 6. Return the Postfix string. PROGRAM #include<stdio.h> #include<string.h> #include<math.h> #define Blank ' ' #define Tab '\t' #define MAX 50 long int pop (); long int eval_post(); char infix[MAX], postfix[MAX]; long int stack[MAX]; int top; main() { long int value; char choice='y'; while(choice == 'y') { top = 0; printf("Enter infix : "); fflush(stdin); gets(infix); infix_to_postfix(); printf("Postfix : %s\n",postfix); value=eval_post();

16

printf("Value of expression : %ld\n",value); printf("Want to continue(y/n) : "); scanf("%c",&choice); } }/*End of main()*/ infix_to_postfix() { int i,p=0,type,precedence,len; char next ; stack[top]='#'; len=strlen(infix); infix[len]='#'; for(i=0; infix[i]!='#';i++) { if( !white_space(infix[i])) { switch(infix[i]) { case '(': push(infix[i]); break; case ')': while((next = pop()) != '(') postfix[p++] = next; break; case '+': case '-': case '*': case '/': case '%': case '^': precedence = prec(infix[i]); while(stack[top]!='#' && precedence<= prec(stack[top])) postfix[p++] = pop(); push(infix[i]); break; default: /*if an operand comes */ postfix[p++] = infix[i]; }/*End of switch */ }/*End of if */ } while(stack[top]!='#') postfix[p++] = pop(); postfix[p] = '\0' ; /*End postfix with'\0' to make it a string*/ }/*End of infix_to_postfix()*/ /* This function returns the precedence of the operator */ prec(char symbol ) { switch(symbol) { case '(': return 0; case '+': case '-': return 1; case '*': case '/': case '%': return 2; case '^':

17

return 3; }/*End of switch*/ }/*End of prec()*/ push(long int symbol) { if(top > MAX) { printf("Stack overflow\n"); exit(1); } else { top=top+1; stack[top] = symbol; } }/*End of push()*/ long int pop() { if (top == -1 ) { printf("Stack underflow \n"); exit(2); } else return (stack[top--]); }/*End of pop()*/ white_space(char symbol) { if( symbol == Blank || symbol == Tab || symbol == '\0') return 1; else return 0; }/*End of white_space()*/ long int eval_post() { long int a,b,temp,result,len; int i; len=strlen(postfix); postfix[len]='#'; for(i=0;postfix[i]!='#';i++) { if(postfix[i]<='9' && postfix[i]>='0') push( postfix[i]-48 ); else { a=pop(); b=pop(); switch(postfix[i]) { case '+': temp=b+a; break; case '-': temp=b-a;break; case '*': temp=b*a;break; case '/': temp=b/a;break; case '%': temp=b%a;break;

18

case '^': temp=pow(b,a); }/*End of switch */ push(temp); }/*End of else*/ }/*End of for */ result=pop(); return result; }/*End of eval_post */

OUTPUT Enter infix : (a+b) Postfix : ab+ Enter infix : (a+b)*c/d+f Postfix : ab+c*d/f+ 7. .

VIVA Given an expression tree with no parentheses in it, write the program to give equivalent infix expression with parentheses inserted where necessary. How would you implement a queue from a stack? What is stack? List the difference between queue and stack. How would you implement a queue from a stack?

Result: Thus, the implementation of stack by using convert infix to postfix expression was executed successfully and verified.

19

Ex.No: 4 Date: AIM:-

IMPLEMENT ARRAY BASED CIRCULAR QUEUE

To write a C program to implement array based circular queue and use it to simulate a producer-consumer problem ALGORITHM:1. Start the program 2. To insert an element, Step-i: If "rear" of the queue is pointing to the last position then go to step-ii or else step-iii Step-ii: make the "rear" value as 0 Step-iii: increment the "rear" value by one Step-iv: a. if the "front" points where "rear" is pointing and the queue holds a not NULL value for it, then its a "queue overflow" state, so quit; else go to step-b b. insert the new value for the queue position pointed by the "rear" 3. To delete the particular item from circular queue Step-i: If the queue is empty then say "empty queue" and quit; else continue Step-ii: Delete the "front" element Step-iii: If the "front" is pointing to the last position of the queue then step-iv else step-v Step-iv: Make the "front" point to the first position in the queue and quit Step-v: Increment the "front" position by one 4. Terminate the program. Program: #include<stdio.h> #include<conio.h> #define MS 5 int r=-1,f=-1,q[MS]; void enqueue(int); void dequeue(); void display(); void main() { int ch,x,y; clrscr(); printf("\n main menu"); do { printf("\n enter your choice"); scanf("%d",&ch); switch(ch) { case 1: printf("\n enter the element"); scanf("%d",&x); enqueue(x); break; 20

case 2: dequeue(); //printf("the deleted element is: %d",y); break; case 3: display(); break; default: exit(0); } }while(ch<4); getch(); } void enqueue(int e) { if(f==(r+1)%MS) printf("queue is overflow"); else { if(f==-1) f=r=0; else r=(r+1)%MS; q[r]=e; } } void dequeue() { int c; if(f==-1) printf("queue is underflow"); else { c=q[f]; printf("element is %d",c); if(f==r) f=r=-1; else f=(f+1)%MS; } //return(c); } void display() { int i; if(f==-1) printf("queue underflow\n"); else { for(i=f;i<=r;i++) printf("%d\n",q[i]); } } OUTPUT: main menu enter your choice 1 enter the element 23

21

enter your choice 1 enter the element 34 enter your choice 1 enter the element 12 enter your choice2 element is 23 enter your choice3 34 12

RESULT:Thus, the implementation of array based circular queue by using a producer-consumer problem was executed and verified successfully.

22

Ex.No:5 Date: AIM:-

IMPLEMENTATION OF TREE TRAVERSALS

To write a C program to implement an expression tree. Produce its pre-order, inorder, and post-order traversals. ALGORITHM:Step 1: Start the process. Step 2: Initialize and declare variables. Step 3: Enter the choice. Inorder / Preorder / Postorder. Step 4: If choice is Inorder then o Traverse the left subtree in inorder. o Process the root node. o Traverse the right subtree in inorder. Step 5: If choice is Preorder then o Process the root node. o Traverse the left subtree in preorder. o Traverse the right subtree in preorder. Step 6: If choice is postorder then o Traverse the left subtree in postorder. o Traverse the right subtree in postorder. o Process the root node. Step7: Print the Inorder / Preorder / Postorder traversal. Step 8: Stop the process. PROGRAM: #include<stdio.h> #include<conio.h> #include<ctype.h> #include<alloc.h> #define size 20 typedef struct node { char data; struct node *left; struct node *right; } btree; /*stack stores the operand nodes of the tree*/ btree *stack[size]; int top; void main() { btree *root; char exp[80];/*exp stores postfix expression*/ btree *create(char exp[80]); void inorder(btree *root); void preorder(btree *root); void postorder(btree *root); clrscr(); printf("\n enter the postfix expression:\n");

23

scanf("%s",exp); top=-1;/*Initialize the stack*/ root=create(exp); printf("\n The tree is created.....\n"); printf("\n Inorder traversal: \n\n"); inorder(root); printf("\n Preorder traversal: \n\n"); preorder(root); printf("\n Postorder traversal: \n\n"); postorder(root); getch(); } btree *create(char exp[]) { btree *temp; int pos; char ch; void push(btree*); btree *pop(); pos=0; ch=exp[pos]; while(ch!='\0') { /*create new node*/ temp=((btree*)malloc(sizeof(btree))); temp->left=temp->right=NULL; temp->data=ch; if(isalpha(ch)) push(temp); else if(ch=='+' ||ch=='-' || ch=='*' || ch=='/') { temp->right=pop(); temp->left=pop(); push(temp); } else printf("\n Invalid char Expression\n"); pos++; ch=exp[pos]; } temp=pop(); return(temp); } void push(btree *Node) { if(top+1 >=size) printf("Error:Stack is full\n"); top++; stack[top]=Node; } btree* pop() { btree *Node; if(top==-1) printf("\nerror: stack is empty..\n"); Node =stack[top]; top--; return(Node); } void inorder(btree *root) { btree *temp;

24

temp=root; if(temp!=NULL) { inorder(temp->left); printf("%c",temp->data); inorder(temp->right); } } void preorder(btree *root) { btree *temp; temp=root; if(temp!=NULL) { printf("%c",temp->data); preorder(temp->left); preorder(temp->right); } } void postorder(btree *root) { btree *temp; temp=root; if(temp!=NULL) { postorder(temp->left); postorder(temp->right); printf("%c",temp->data); } } OUTPUT Enter the postfix expression: ab+cd-* The tree is created..... Inorder traversal: a+b*c-d Preorder traversal: *+ab-cd Postorder traversal: ab+cd-*

Result: Thus, the implementation of tree traversals program was executed, tested and verified successfully. Ex.No:6 Date: IMPLEMENT BINARY SEARCH TREE

25

AIM:To write a C program to implement binary search tree. ALGORITHM:Step 1: Start the process. Step 2: Initialize and declare variables. Step 3: Construct the Tree Step 4: Data values are given which we call a key and a binary search tree
Step 5: To

search for the key in the given binary search tree, start with the root node and Compare the key with the data value of the root node. If they match, return the root pointer. the key is less than the data value of the root node, repeat the process by using the left subtree.

Step 6: If

Step 7: Otherwise, repeat the same process with the right subtree until either a match is found or the subtree under consideration becomes an empty tree. Step 8: Terminate PROGRAM #include<stdio.h> #include<conio.h> #include<process.h> #include<alloc.h> struct tree { int data; struct tree *lchild; struct tree *rchild; }*t,*temp; int element; void inorder(struct tree *); void preorder(struct tree *); void postorder(struct tree *); struct tree * create(struct tree *, int); struct tree * find(struct tree *, int); struct tree * insert(struct tree *, int); struct tree * del(struct tree *, int); struct tree * findmin(struct tree *); struct tree * findmax(struct tree *); void main() { int ch; do { printf("\n\t\t\tBINARY SEARCH TREE"); printf("\n\t\t\t****** ****** ****"); printf("\nMain Menu\n"); printf("\n1.Create\n2.Insert\n3.Delete\n4.Find\n5.FindMin\n6.FindMax");

26

printf("\n7.Inorder\n8.Preorder\n9.Postorder\n10.Exit\n"); printf("\nEnter ur choice :"); scanf("%d",&ch); switch(ch) { case 1: printf("\nEnter the data:"); scanf("%d",&element); t=create(t,element); inorder(t); break; case 2: printf("\nEnter the data:"); scanf("%d",&element); t=insert(t,element); inorder(t); break; case 3: printf("\nEnter the data:"); scanf("%d",&element); t=del(t,element); inorder(t); break; case 4: printf("\nEnter the data:"); scanf("%d",&element); temp=find(t,element); if(temp->data==element) printf("\nElement %d is at %d",element,temp); else printf("\nElement is not found"); break; case 5: temp=findmin(t); printf("\nMax element=%d",temp->data); break; case 6: temp=findmax(t); printf("\nMax element=%d",temp->data); break; case 7: inorder(t); break; case 8: preorder(t); break; case 9: postorder(t); break; case 10: exit(0); } }while(ch<=10); } struct tree * create(struct tree *t, int element) { t=(struct tree *)malloc(sizeof(struct tree)); t->data=element; t->lchild=NULL; t->rchild=NULL; return t;

27

} struct tree * find(struct tree *t, int element) { if(t==NULL) return NULL; if(element<t->data) return(find(t->lchild,element)); else if(element>t->data) return(find(t->rchild,element)); else return t; } struct tree *findmin(struct tree *t) { if(t==NULL) return NULL; else if(t->lchild==NULL) return t; else return(findmin(t->lchild)); } struct tree *findmax(struct tree *t) { if(t!=NULL) { while(t->rchild!=NULL) t=t->rchild; } return t; } struct tree *insert(struct tree *t,int element) { if(t==NULL) { t=(struct tree *)malloc(sizeof(struct tree)); t->data=element; t->lchild=NULL; t->rchild=NULL; return t; } else { if(element<t->data) { t->lchild=insert(t->lchild,element); } else if(element>t->data) { t->rchild=insert(t->rchild,element); } else if(element==t->data) { printf("element already present\n"); }

28

return t; } } struct tree * del(struct tree *t, int element) { if(t==NULL) printf("element not found\n"); else if(element<t->data) t->lchild=del(t->lchild,element); else if(element>t->data) t->rchild=del(t->rchild,element); else if(t->lchild&&t->rchild) { temp=findmin(t->rchild); t->data=temp->data; t->rchild=del(t->rchild,t->data); } else { temp=t; if(t->lchild==NULL) t=t->rchild; else if(t->rchild==NULL) t=t->lchild; free(temp); } return t; } void inorder(struct tree *t) { if(t==NULL) return; else { inorder(t->lchild); printf("\t%d",t->data); inorder(t->rchild); } } void preorder(struct tree *t) { if(t==NULL) return; else { printf("\t%d",t->data); preorder(t->lchild); preorder(t->rchild); } } void postorder(struct tree *t) { if(t==NULL) return;

29

else { postorder(t->lchild); postorder(t->rchild); printf("\t%d",t->data); } } OUTPUT: BINARY SEARCH TREE ****** ****** **** Main Menu 1.Create 2.Insert 3.Delete 4.Find 5.FindMin 6.FindMax 7.Inorder 8.Preorder 9.Postorder 10.Exit Enter ur choice :1 Enter the data:2 2 BINARY SEARCH TREE ****** ****** **** Main Menu 1.Create 2.Insert 3.Delete 4.Find 5.FindMin 6.FindMax 7.Inorder 8.Preorder 9.Postorder 10.Exit Enter ur choice :2 Enter the data:3 2 3 BINARY SEARCH TREE ****** ****** **** Main Menu 1.Create 2.Insert 3.Delete 4.Find 5.FindMin 6.FindMax 7.Inorder 8.Preorder

30

9.Postorder 10.Exit Enter ur choice :2 Enter the data: 5 2 3 5 BINARY SEARCH TREE ****** ****** **** Main Menu 1.Create 2.Insert 3.Delete 4.Find 5.FindMin 6.FindMax 7.Inorder 8.Preorder 9.Postorder 10.Exit Enter ur choice :2 Enter the data:7 2 3 5 7 BINARY SEARCH TREE ****** ****** **** Main Menu 1.Create 2.Insert 3.Delete 4.Find 5.FindMin 6.FindMax 7.Inorder 8.Preorder 9.Postorder 10.Exit Enter ur choice :5 Min element=3 BINARY SEARCH TREE ****** ****** **** Main Menu 1.Create 2.Insert 3.Delete 4.Find 5.FindMin 6.FindMax 7.Inorder 8.Preorder 9.Postorder 10.Exit

31

Enter ur choice :6 Max element=7 BINARY SEARCH TREE ****** ****** **** Main Menu 1.Create 2.Insert 3.Delete 4.Find 5.FindMin 6.FindMax 7.Inorder 8.Preorder 9.Postorder 10.Exit Enter ur choice :3 Enter the data: 3 2 5 7 BINARY SEARCH TREE ****** ****** **** Main Menu 1.Create 2.Insert 3.Delete 4.Find 5.FindMin 6.FindMax 7.Inorder 8.Preorder 9.Postorder 10.Exit Enter ur choice : 10

Result: Thus, the implement of binary search tree program was executed, tested and verified successfully.

Ex.No:7

IMPLEMENTATION OF PRIORITY QUEUE USING HEAPS

32

Date: AIM:To implement priority queue using heaps. ALGORITHM:Step 1: Start the Program Step 2: heap is a binary tree with two important properties: For any node n other than the root, n.key >= n.parent.key. In other words, the parent always has more priority than its children. If the heap has height h, the first h1 levels are full, and on the last level the nodes are all packed to the left. Step 4: implement the queue as a linked list, the element with most priority will be the first element of the list, so retrieving the content as well as removing this element are both O(1) operations. However, inserting a new object in its right position requires traversing the list element by element, which is an O(n) operation. Step 3: Insert Element in Queue void insert (Object o, int priority) - inserts in the queue the specified object with the specified priority Algorithm insert (Object o, int priority) Input: An object and the corresponding priority Output: The object is inserted in the heap with the corresponding priority lastNode getLast() //get the position at which to insert lastNode.setKey(priority) lastnode.setContent(o) n lastNode while n.getParent()! = null and n.getParent().getKey() > priority swap(n,n.getParent()) Step 4: Object DeleteMin() - removes from the queue the object with most priority Algorithm removeMin() lastNode <- getLast() value lastNode.getContent() swap(lastNode, root) update lastNode return value PROGRAM:#include<iostream.h> #include<conio.h> #include<stdio.h> #include<stdlib.h> #include<process.h> struct heapnode { int capacity; int size; int *elements; }; int isFull(struct heapnode *h) { if(h->capacity==h->size) return 1; else return 0; 33

} int isEmpty(struct heapnode *h) { if(h->size==0) return 1; else return 0; } void display(struct heapnode *h) { printf("\nPriority Queue Display :"); if(isEmpty(h)) { printf("\nPriority queue is empty"); return; } else for(int i=1;i<=h->size;i++) printf("%d\t",h->elements[i]); } struct heapnode * initialize() { struct heapnode *t; int maxelements; printf("\nEnter the Size of the Priority queue :"); scanf("%d",&maxelements); if(maxelements<5) { printf("Priority queue size is to small"); getch(); exit(0); } t=(struct heapnode *)malloc(sizeof(struct heapnode *)); if(t==NULL) { printf("out of space!"); getch(); exit(0); } t->elements=(int *)malloc((maxelements+1)*sizeof(int)); if(t->elements==NULL) { printf("Out of space"); getch(); exit(0); } t->capacity=maxelements; t->size=0; t->elements=0; return t; } void insert(int x,struct heapnode *h) { int i;

34

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 deleteMin(struct heapnode *h) { int i,child; int MinElement,LastElement; if(isEmpty(h)) { printf("Priority queue is empty"); return 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]; else break; } h->elements[i]=LastElement; return MinElement; } void main() { int ch,ins,del; struct heapnode *h; clrscr(); printf("\nPriority Queue using Heap"); h=initialize(); while(1) { printf("\n1. Insert\n2. DeleteMin\n3. Display\n4. Exit"); printf("\nEnter u r choice :"); scanf("%d",&ch); switch(ch) { case 1: printf("\nEnter the element:"); scanf("%d",&ins); insert(ins,h); break; case 2: del=deleteMin(h); printf("\nDeleted element is %d",del); getch();

35

break; case 3: display(h); getch(); break; case 4: exit(0); } } } OUTPUT: Priority Queue using Heap Enter the Size of the Priority queue :14 1. Insert 2. DeleteMin 3. Display 4. Exit Enter u r choice :1 Enter the element:10 1. Insert 2. DeleteMin 3. Display 4. Exit Enter u r choice :1 Enter the element:34 1. Insert 2. DeleteMin 3. Display 4. Exit Enter u r choice :1 Enter the element:24 1. Insert 2. DeleteMin 3. Display 4. Exit Enter u r choice :1 Enter the element:67 1. Insert 2. DeleteMin 3. Display 4. Exit Enter u r choice :3 Priority Queue Display :10 1. Insert 2. DeleteMin 3. Display 4. Exit Enter u r choice :2 Deleted element is 10 1. Insert 2. DeleteMin 34 24 67

36

3. Display 4. Exit Enter u r choice :2 Deleted element is 24 1. Insert 2. DeleteMin 3. Display 4. Exit Enter u r choice :3 Priority Queue Display :34 1. Insert 2. DeleteMin 3. Display 4. Exit Enter u r choice :4

67

Result: Thus, the implement of priority queue program by using heaps was executed, tested and verified successfully.

Ex.No:8 Date:

IMPLEMENT HASHING TECHNIQUES

37

AIM:To implement the hashing techniques using C language. ALGORITHM:1. Start the program 2. Get the array size. 3. Get the elements of the array. 4. Get the key value of the element to be searched. 5. Find the position of the element by taking the remainder of the division of the array size by the key. 6. Print the element in that position. 7. Terminate the program. PROGRAM #include<stdio.h> #include<conio.h> #include<stdlib.h> #define MAX 10 void main() { int a[MAX],num,key,i; char ans; int create(int); void linear_prob(int [],int,int),display(int []); clrscr(); printf("\n Collision Handling By Linaer Probling"); for(i=0;i<MAX;i++) a[i]=-1; do { printf("\n Enter the Number "); scanf("%d",&num); key=create(num); linear_prob(a,key,num); printf("\n Do U Wish to Contiue?(Y/N"); ans=getch(); } while(ans=='y'); display(a); getch(); } int create(int num) { int key; key=num%10; return key; } void linear_prob(int a[MAX],int key,int num) { int flag,i,count=0; void display(int a[]); flag=0;

38

if(a[key]==-1) a[key]=num; else { i=0; while(i<MAX) { if(a[i]!=-1) count++; i++; } if(count==MAX) { printf("\n\n Hash Table is Fu;;"); display(a); getch(); exit(1); } 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; } } } void display(int a[MAX]) { int i; printf("\n\n The HAsh Table is....\n"); for(i=0;i<MAX;i++) printf("\n %d %d",i,a[i]); } OUTPUT Collision Handling By Linaer Probling Enter the Number 131 Do U Wish to Contiue?(Y/N Enter the Number 21 Do U Wish to Contiue?(Y/N Enter the Number 3 Do U Wish to Contiue?(Y/N Enter the Number 4 Do U Wish to Contiue?(Y/N Enter the Number 5

39

Do U Wish to Contiue?(Y/N Enter the Number 8 Do U Wish to Contiue?(Y/N Enter the Number 9 Do U Wish to Contiue?(Y/N Enter the Number 18 Do U Wish to Contiue?(Y/N The HAsh Table is.... 0 1 2 3 4 5 6 7 8 9 18 131 21 3 4 5 -1 -1 8 9

Viva questions: Define hashing. List the hashing techniques. How can a data be inserted in to the hash table? What is hash table? What are the applications of hashing techniques?

Result: Thus, the implement of hashing techniques program was implemented, executed, tested and verified successfully. Ex.No:9 IMPLEMENTATION OF DIJKSTRA'S ALGORITHM USING PRIORITY QUEUES 40

Date: AIM:To implement Dijkstra's algorithm using priority queues. ALGORITHM:1. Assign to every node a distance value. Set it to zero for our initial node and to infinity for all other nodes. 2. Mark all nodes as unvisited. Set initial node as current. 3. For current node, consider all its unvisited neighbors and calculate their distance (from the initial node). For example, if current node (A) has distance of 6, and an edge connecting it with another node (B) is 2, the distance to B through A will be 6+2=8. If this distance is less than the previously recorded distance (infinity in the beginning, zero for the initial node), overwrite the distance. 4. When we are done considering all neighbors of the current node, mark it as visited. A visited node will not be checked ever again; its distance recorded now is final and minimal. 5. Set the unvisited node with the smallest distance (from the initial node) as the next "current node" and continue from step 3 . PROGRAM:#include<stdio.h> #include<stdlib.h> void main() { int graph[15][15],s[15],pathestimate[15],mark[15]; int num_of_vertices,source,i,j,u,predecessor[15]; int count=0; int minimum(int a[],int m[],int k); void printpath(int,int,int[]); printf("\nenter the no.of vertices\n"); scanf("%d",&num_of_vertices); if(num_of_vertices<=0) { printf("\nthis is meaningless\n"); exit(1); } printf("\nenter the adjacent matrix\n"); for(i=1;i<=num_of_vertices;i++) { printf("\nenter the elements of row %d\n",i); for(j=1;j<=num_of_vertices;j++) { scanf("%d",&graph[i][j]); } } printf("\nenter the source vertex\n"); scanf("%d",&source); for(j=1;j<=num_of_vertices;j++) { mark[j]=0; pathestimate[j]=999; predecessor[j]=0; } pathestimate[source]=0; while(count<num_of_vertices) 41

{ u=minimum(pathestimate,mark,num_of_vertices); s[++count]=u; mark[u]=1;

for(i=1;i<=num_of_vertices;i++) { if(graph[u][i]>0) { if(mark[i]!=1) { if(pathestimate[i]>pathestimate[u]+graph[u][i]) { pathestimate[i]=pathestimate[u]+graph[u][i]; predecessor[i]=u; } } } } } for(i=1;i<=num_of_vertices;i++) { printpath(source,i,predecessor); if(pathestimate[i]!=999) printf("->(%d)\n",pathestimate[i]); } } int minimum(int a[],int m[],int k) { int mi=999; int i,t; for(i=1;i<=k;i++) { if(m[i]!=1) { if(mi>=a[i]) { mi=a[i]; t=i; } } } return t; } void printpath(int x,int i,int p[]) { printf("\n"); if(i==x) { printf("%d",x); } else if(p[i]==0) printf("no path from %d to %d",x,i); else { printpath(x,p[i],p); printf("..%d",i);

42

} } OUTPUT: enter the no.of vertices 3 enter the adjacent matrix enter the elements of row 1 1 2 3 enter the elements of row 2 4 5 6 enter the elements of row 3 7 8 9 enter the source vertex 1 1->(0) 1..2->(2) 1..3->(3)

Result: Thus, the implement of Dijkstra's algorithm using priority queues was executed and verified successfully.

43

Ex.NO:10. IMPLEMENTATION OF BACKTRACKING ALGORITHM FOR KNAPSACK PROBLEM Date:

Aim:
To implement the knapsnack problem to find the maximum profit for corresponding weight.

Algorithm:
1. Include the header files for the program. 2. Declare the global varaiable v,c,w; 3. Declare the function simple.fill. 4. Using for loop get the values. 5. Using while perform the necessary operations 6. Check the weight of the elements. 7. Initialize max i=1. 8. Deliver the outputs by the values v[max i] , c[max i] , cur_w. 9. In the main function , call the simple fill application. 10. Stop the program.

Program:
#include<iostream.h> #include<conio.h> int n=5; int c[10]={12,1,2,1,4}; int v[10]={4,2,2,1,10}; int w=15; void simple_fill() { int cur_w; float tot_v; int i,maxi; int used[10]; /*for(i=0;i<n;++i) { cout<<"enter the weight for the items..."; cin>>c[i]; cout<<"enter the profit of each item ..."; cin>>v[i]; } */ for(i=0;i<n;i++) used[i]=0; cur_w=w; while(cur_w>0) { maxi=-1; for(i=0;i<n;++i) if((used[i]==0)&&((maxi==-1)||((float)v[i]/c[i]>(float)v[maxi]/c[maxi]))) maxi=i; used[maxi]=1; cur_w-=c[maxi]; tot_v+=v[maxi]; if(cur_w>=0) cout<<"\nadded object"<<maxi+1<<"\t"<<v[maxi]<<"\t"<<c[maxi]<<"completely with bag space left:"<<cur_w; else {

44

cout<<"\nadded object "<<(int)((1+ (float)cur_w/c[maxi])*1)<<"\t"<<v[maxi]<<"\t"<<c[maxi]<<"\tkg of object"<<maxi+1<<"in the bag"; tot_v-=v[maxi]; tot_v+=(1+(float)cur_w/c[maxi])*v[maxi]; } cout<<"\nfilled the bag with objects worth \n"<<tot_v<<"\n\t"; } } void main() { clrscr(); simple_fill(); getch(); } output: added object5 10 4 completely with bag space left:11 filled the bag with objects worth 10 added object2 2 1 completely with bag space left:10 filled the bag with objects worth12 added object3 2 2 completely with bag space left:8 filled the bag with objects worth 14 added object4 1 1 completely with bag space left:7 filled the bag with objects worth15 added object 0 4 12 kg of object1in the bag filled the bag with objects worth 17.333334

. Viva questions: Describe knapsack problem. What is the significance of backtracking algorithm?

RESULT: Thus, the implementation of backtracking algorithm for knapsack problem was Successfully created and verified

45

Potrebbero piacerti anche