III SEM EEE EE2209-Data Structures and Algorithms 2 EE2209 – DATA STRUCTURES AND ALGORITHMS LTP 0...

66
III SEM EEE EE2209-Data Structures and Algorithms 2 EE2209 – DATA STRUCTURES AND ALGORITHMS LTP 003 LIST OF EXPERIMENTS: 1. a Singly Linked List b Doubly Linked List 2. Polynomial Addition 3. Infix to Postfix Expression 4. Binary Tree Traversal 5. Circular Queue - Producer Consumer problem 6. Binary Search Tree 7. AVL Tree 8. Queue using binary heaping 9. Hashing Techniques 10. Topological Sorting 11. Dijkstra’s Algorithm 12. Prim’s Algorithm 13. Backtracking Algorithm – Knapsack Problem 14. Branch and Bound Algorithm- Travelling Salesman Problem 15. Randomized Algorithm www.rejinpaul.com

Transcript of III SEM EEE EE2209-Data Structures and Algorithms 2 EE2209 – DATA STRUCTURES AND ALGORITHMS LTP 0...

III SEM EEE EE2209-Data Structures and Algorithms

2

EE2209 – DATA STRUCTURES AND ALGORITHMS

LTP

0 0 3

LIST OF EXPERIMENTS:

1. a Singly Linked List

b Doubly Linked List

2. Polynomial Addition

3. Infix to Postfix Expression

4. Binary Tree Traversal

5. Circular Queue - Producer Consumer problem

6. Binary Search Tree

7. AVL Tree

8. Queue using binary heaping

9. Hashing Techniques

10. Topological Sorting

11. Dijkstra’s Algorithm

12. Prim’s Algorithm

13. Backtracking Algorithm – Knapsack Problem

14. Branch and Bound Algorithm- Travelling Salesman Problem

15. Randomized Algorithm

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

3

M.A.M COLLEGE OF ENGINEERING

EE2209 DATA STRUCTURES AND ALGORITHMS LAB

DEGREE / BRANCH: B.E/EEE YEAR / SEM: II/III

TABLE OF CONTENTS

Ex. No TITLE Page No

1.a Singly Linked List 04

1.b Doubly Linked List 09

2. Polynomial Addition 14

3. Infix to Postfix Expression 18

4. Binary Tree Traversal 21

5. Circular Queue - Producer Consumer problem 26

6. Binary Search Tree 29

7. AVL Tree 36

8. Queue using binary heaping 42

9. Hashing Techniques 46

10. Topological Sorting 48

11 Dijkstra’s Algorithm 52

12. Prim’s Algorithm 56

13. Backtracking Algorithm – Knapsack Problem 60

14. Branch and Bound Algorithm- Travelling Salesman Problem 63

15. Randomized Algorithm 66

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

4

EX NO: 1 (a) SINGLY LINKED LIST

AIM: To write a Program to implement a single linked list

ALGORITHM: Step 1: Start Step 2: Read the value of ch Step 3: If ch=1 call create list functions Step 4: If ch=2 call insert list functions Step 5: If ch=3 call delete list functions Step 6: If ch=4 call view list functions Step 7: Repeat while (ch! =5) Step 8: StopALGORITHM FOR CREATE LIST Step 1: Read value of item Step 2: Allocate the memory far new node Step 3: Assign values to new node data part Step 4: Assign new node address part as null ALGORITHM FOR INSERT LIST Step 1: Read the value of item Step 2: Allocate the memory far new node Step 3: Assign values of data field as null else make link fields of all new nodes to point Step 4: starting node to new node Step 5: Set the external pointer from the starting node to new node ALGORITHM FOR DELETE LIST Step 1: If the link is empty then return else check whether the list contains more than one element Step 2: Move the start pointer to the next node Step 3: Free the first node ALGORITHM FOR VIEW LIST Step 1: Using the for loop i Step 2: Print the linked listStep 3: Stop

PROGRAM:#include<stdio.h> #include<conio.h>#include<alloc.h> struct node { int item; struct node *link; }; typedef struct node NODE; NODE *head; NODE *getnode(); void readnode(NODE *newnode); void createlist(); void insertfirst();

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

5

void deletefirst(); void viewlist(); void main() { int ch; clrscr(); printf("\n\n\t\t SINGLY LINKEDLIST\n"); printf("\t\t *****************\n"); do { printf("\n 1.CREATE LIST"); printf("\n 2.INSERT FIRST"); printf("\n 3.DELETE FIRST"); printf("\n 4.VIEW LIST"); printf("\n 5.EXIT"); printf("\n\nEnter Your Choice:"); scanf("%d",&ch); switch(ch) { case 1: createlist();break; case 2: insertfirst(); break; case 3: deletefirst(); break; case 4: viewlist(); break; case 5: exit(0); } } while(ch<=5); } NODE *getnode() { NODE *newnode; newnode=(NODE*)malloc(sizeof (NODE)); return(newnode); } void readnode(NODE *newnode) { printf("\nEnter the item:"); scanf("%d",&newnode->item); fflush(stdin); newnode->link=NULL; }

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

6

void createlist() { NODE *prev,*newnode; char ch; head = NULL; do { newnode=getnode(); readnode(newnode);if(head==NULL) { head=newnode; prev=head; } else { prev->link =newnode; prev=newnode; } printf("\nDo You Want To Continue:"); scanf("%c",&ch); } while(ch=='y'); } void insertfirst() { NODE *newnode; newnode=getnode(); readnode(newnode); if(head==NULL) { head=newnode; } else { newnode->link=head; head=newnode; } } void deletefirst() { NODE *prev; if(head==NULL) return; else {prev=head; head=head->link; free(prev);

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

7

} } void viewlist() { NODE *loc; printf("\nELEMENTS\n"); loc=head; do { printf("\t%d->",loc->item); loc=loc->link; } while(loc!=NULL); printf("NULL"); }

OUTPUT:1.CREATE LIST 2.INSERT FIRST 3.DELETE FIRST 4.VIEW LIST 5.EXIT Enter Your Choice:1 Enter the item:2 Do You Want To Continue:y Enter the item:3 Do You Want To Continue:n 1.CREATE LIST 2.INSERT FIRST 3.DELETE FIRST 4.VIEW LIST 5.EXIT Enter Your Choice:4 ELEMENTS 2-> 3->NULL 1.CREATE LIST 2.INSERT FIRST3.DELETE FIRST 4.VIEW LIST 5.EXIT Enter Your Choice:2 Enter the item:1 1.CREATE LIST 2.INSERT FIRST 3.DELETE FIRST 4.VIEW LIST 5.EXIT Enter Your Choice:4 ELEMENTS 1-> 2-> 3->NULL 1.CREATE LIST 2.INSERT FIRST

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

8

3.DELETE FIRST 4.VIEW LIST 5.EXIT Enter Your Choice:3 1.CREATE LIST 2.INSERT FIRST 3.DELETE FIRST 4.VIEW LIST 5.EXIT Enter Your Choice:4 ELEMENTS 2-> 3->NULL 1.CREATE LIST 2.INSERT FIRST 3.DELETE FIRST 4.VIEW LIST 5.EXIT Enter Your Choice:5

RESULT:

Thus the singly linked list program has been executed successfully and the output has been verified.

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

9

EX NO: 1 (b) DOUBLE LINKED LIST

AIM: To write a program to implement a Double linked list.

ALGORITHM: Step 1: StartStep 2: Read the value of ch Step 3: If ch=1 call create list functions Step 4: If ch=2 call insert list functions Step 5: If ch=3 call delete list functions Step 6: If ch=4 call view list functions Step 7: If ch=5 call the exit functions Step 8: Repeat while (ch! =5) Step 9: StopALGORITHM FOR CREATE LIST Step 1: Read the value of item Step 2: Allocate the memory far newly assigned nodes Step 3: Assign the data to the data field Step 4: Assign forward and backward link as Null ALGORITHM FOR INSERT LIST Step 1: Read the value of item Step 2: Allocate a new node and assign the item to the data part Step 3: If head is NULL return Step 4: Assign link of new node to head and blink of new node to NULL link of head node Step 5: To new node change head ptr to print the new node ALGORITHM FOR DELETE LIST Step 1: Check the head node as null return empty Step 2: Else change the head pointer to the head pointer link Step 3: Change the new head ptr blink as null ALGORITHM FOR VIEW LIST Step 1: Using the for loop Step 2: Print the required list Step 3: Stop

PROGRAM:#include<stdio.h> #include<conio.h> #include<alloc.h> struct node { int item; struct node *plink,*nlink; }; typedef struct node NODE; NODE *head; NODE *getnode(); void readnode(NODE *newnode); void createlist();

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

10

void insertfirst(); void deletefirst(); void viewlist(); void main() { int ch; clrscr(); printf("\n\n\t DOUBLY LINKEDLIST\n"); printf("\t *****************\n"); do { printf("\n 1.CREATE LIST"); printf("\n 2.INSERT FIRST"); printf("\n 3.DELETE FIRST"); printf("\n 4.VIEW LIST"); printf("\n 5.EXIT"); printf("\nEnter your choice:"); scanf("%d",&ch); switch(ch) { case 1: createlist(); break;case 2: insertfirst(); break; case 3: deletefirst(); break; case 4: viewlist(); break; case 5: exit(0); } }while(ch<=5); } NODE *getnode() { NODE *newnode; newnode=(NODE*)malloc(sizeof(NODE)); return(newnode); } void readnode(NODE *newnode) { printf("\nEnter the item:"); scanf("%d",&newnode->item); fflush(stdin); newnode->plink=NULL; newnode->nlink=NULL;

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

11

} void createlist() { NODE *prev,*newnode; char ch; head=NULL; do { newnode=getnode(); readnode(newnode); if(head==NULL){ head=newnode; prev=head; } else { prev->nlink=newnode; newnode->plink=prev; prev=newnode; } printf("\nDo you want to continue:"); scanf("%c",&ch); } while(ch=='y'); } void insertfirst() { NODE *newnode; newnode=getnode(); readnode(newnode); if(head==NULL) { head=newnode; } else { newnode->nlink=head; head->plink=newnode; head=newnode; } } void deletefirst() { NODE *prev; if(head==NULL) return; else {

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

12

prev=head; head=head->nlink; head->plink=NULL; free(prev); } } void viewlist() { NODE *loc; printf("\nELEMENTS\n"); loc=head; do { printf("%2d<->",loc->item); loc=loc->nlink; } while(loc!=NULL); printf("NULL"); }

OUTPUT1.CREATE LIST 2.INSERT FIRST 3.DELETE FIRST 4.VIEW LIST 5.EXIT Enter Your Choice:1 Enter the item:2 Do You Want To Continue:y Enter the item:3 Do You Want To Continue:n 1.CREATE LIST 2.INSERT FIRST 3.DELETE FIRST 4.VIEW LIST 5.EXIT Enter Your Choice:4 ELEMENTS2<-> 3<->NULL 1.CREATE LIST 2.INSERT FIRST 3.DELETE FIRST 4.VIEW LIST 5.EXIT Enter Your Choice:2 Enter the item:1 1.CREATE LIST 2.INSERT FIRST 3.DELETE FIRST 4.VIEW LIST 5.EXIT

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

13

Enter Your Choice:4 ELEMENTS 1<-> 2<-> 3<->NULL 1.CREATE LIST 2.INSERT FIRST 3.DELETE FIRST 4.VIEW LIST 5.EXIT Enter Your Choice:3 1.CREATE LIST 2.INSERT FIRST 3.DELETE FIRST 4.VIEW LIST 5.EXIT Enter Your Choice:4 ELEMENTS 2<-> 3<->NULL 1.CREATE LIST 2.INSERT FIRST 3.DELETE FIRST 4.VIEW LIST 5.EXIT Enter Your Choice:5

RESULT:

Thus the doubly linked list program has been executed successfully and the output has been verified.

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

14

EX NO: 2 POLYNOMIAL ADDITIONS

AIM: Represent a polynomial as a linked list and write functions for polynomial addition.

ALGORITHM: Step 1: While p and q are not null repeat step 2 Step 2:if power of the two term are equal then if the term do not cancel then insert num of terms into the sum polynomial advance p ,advance q, else if the power first polynomial-> power of the second then insert the term from second polynomial in to sum polynomial advance q Step 3: copy remaining terms from the non empty polynomial in to the sum polynomial

PROGRAM:#include<stdio.h> #include<malloc.h> #include<conio.h> struct link { int coeff; int pow; struct link *next; }; struct link *poly1=NULL,*poly2=NULL,*poly=NULL; void create(struct link *node) { char ch; do { printf("\n enter coeff:"); scanf("%d",&node->coeff); printf("\n enter power:"); scanf("%d",&node->pow); node->next=(struct link*)malloc(sizeof(struct link)); node=node->next; node->next=NULL; printf("\n continue(y/n):"); ch=getch(); } while(ch=='y' || ch=='Y'); } void show(struct link *node) { while(node->next!=NULL) {printf("%dx^%d",node->coeff,node->pow); node=node->next; if(node->next!=NULL) printf("+"); } }

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

15

void polyadd(struct link *poly1,struct link *poly2,struct link *poly) { while(poly1->next && poly2->next) { if(poly1->pow>poly2->pow) { poly->pow=poly1->pow; poly->coeff=poly1->coeff; poly1=poly1->next; } else if(poly1->pow<poly2->pow) { poly->pow=poly2->pow; poly->coeff=poly2->coeff; poly2=poly2->next; } else { poly->pow=poly1->pow; poly->coeff=poly1->coeff+poly2->coeff; poly1=poly1->next; poly2=poly2->next; } poly->next=(struct link *)malloc(sizeof(struct link)); poly=poly->next; poly->next=NULL; } while(poly1->next || poly2->next) { if(poly1->next) {poly->pow=poly1->pow; poly->coeff=poly1->coeff; poly1=poly1->next; } if(poly2->next) { poly->pow=poly2->pow; poly->coeff=poly2->coeff; poly2=poly2->next; } poly->next=(struct link *)malloc(sizeof(struct link)); poly=poly->next; poly->next=NULL; } } main() { char ch; do

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

16

{ poly1=(struct link *)malloc(sizeof(struct link)); poly2=(struct link *)malloc(sizeof(struct link)); poly=(struct link *)malloc(sizeof(struct link)); printf("\nenter 1st number:"); create(poly1); printf("\nenter 2nd number:"); create(poly2); printf("\n1st Number:"); show(poly1); printf("\n2nd Number:"); show(poly2); polyadd(poly1,poly2,poly); printf("\nAdded polynomial:"); show(poly); printf("\n add two more numbers:"); ch=getch(); } while(ch=='y' || ch=='Y');return(0); }

OUTPUT:enter 1st number: enter coeff:3 enter power:4 continue(y/n): enter coeff:6 enter power:2 continue(y/n): enter coeff:4 enter power:1 continue(y/n): enter coeff:5 enter power:0 continue(y/n): enter 2nd number: enter coeff:2 enter power:3 continue(y/n): enter coeff:3 enter power:1 continue(y/n): enter coeff:7 enter power:0 continue(y/n): 1st Number:3x^4+6x^2+4x^1+5x^0 2nd Number:2x^3+3x^1+7x^0 Added polynomial:3x^4+2x^3+6x^2+7x^1+12x^0 Add two more numbers:

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

17

RESULT:

`Thus the program for implementing polynomial addition is executed.

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

18

EX NO: 3 CONVERSION OF INFIX TO POSTFIX EXPRESSION

AIM: To convert the infix to post fix expression using the concept of linked list

ALGORITHM: Step 1: Include the header files Step 2: Allocate the memory for linked list Step 3: Delete the structure for the node Step 4: Read the infix expression and find the length of the expression Step 5: If the current character is open parenthesis ‘(‘then push it into the stack Step 6: When the current character is an operand then adds it to the result Step 7: When the current character is operator check the priority of scanned operator with top of the stack. If the priority of the scanned character is greater than top of the stack Step 8: If the element of the current operator is less than or equal to the top of the stack then i) Pop the top character from the stack ii) Push the scanned operator into the stack Step 9: When the current character is closing parenthesis then pop all the characters above opening parenthesis if any from the stack Step10: Return the result Step 11: End

PROGRAM:#include<stdio.h> #include<conio.h> #include<string.h> #include<math.h> #include<ctype.h> char pop(void); void push(char); int priority(char); int top; char s[80],result[80]; void main() { int len,i,j; char a[80]; clrscr(); printf("Enter the expression"); scanf("%s",a); len=strlen(a); a[len]=')'; a[len+1]='\0'; push('('); i=0;j=0; while(a[i]) { if(isalpha(a[i]))result[j++]=a[i]; else

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

19

{ if(a[i]=='(') push('('); else { if(a[i]=='+'||a[i]=='-'||a[i]=='*'||a[i]=='/') { if(priority(a[i])>priority(s[top])) push(a[i]); else { while(priority(a[i])<priority(s[top])) result[j++]=pop(); if (priority(a[i])==priority(s[top])) result[j++]=pop(); push(a[i]); } } else { if (a[i]==')') { while(priority(a[i])<priority(s[top])) result[j++]=pop(); pop(); }}}} i++; } result[j]='\0'; printf("Postfix expression is %s",result); getch(); } char pop() { return(s[top--]);} void push(char ele) { s[++top]=ele; } int priority(char ch) { switch(ch) { case '+':return(4); case '-':return(4); case '*':return(5); case '/':return(5); case '(':return(0); case ')':return(0);

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

20

} }

OUTPUT

enter the infix expression is: a+b*c-d/e postfix expression is: abc*+de/-

RESULT:

Thus the infix expression is converted into postfix using linked list.

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

21

EX: NO 4 BINARY TREE TRAVERSALSAIM: To write a program to implement a binary tree traversal

ALGORITHM: Step 1: Start Step 2: Read the value of ch Step 3: If ch=1 read the values as numbers Step 4: While (num!=0) call insert (tree, num) Step 5: If ch=2 call the inorder to prefer inorder traversal Step 6: If ch=3 call the post order to prefer post order traversal Step 7: If ch=4 call the pre order to prefer pre order traversal Step 8: If ch=5 exit the operations Step 9: Repeat while ch!=5) Step10: EndALGORITHM FOR INSERT Step 1: StartStep 2: If (tree –null) allocate memory space to tree Step 3: assign num to true ->item Step 4: Set null to tree ->child and tree->rchild Step 5: If (num < tree -> item) insert the num on the left side of node by replacing the stepStep 6: Else (num > tree -> item) insert the num on the right side of node and repeat the Step 5 Step 7: Else write duplicate value Step 8: Return (tree) Step 9: StopALGORITHM FOR IN ORDER Step 1: StartStep 2: If (tree! = null) Step 3: Visit the left child Step 4: Write tree ->item Step 5: Visit the right child Step 6: StopALGORITHM FOR PRE - ORDER Step 1: Start Step 2: If true! =null Step 3: Write tree ->item Step 4: Visit the left child Step 5: Visit the right child Step 6: StopALGORITHM FOR POST ORDER Step 1: StartStep 2: If (true! =null) Step 3Visit the left child Step 4: Visit the right child Step 5: Write tree -> item Step 6: Stop

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

22

PROGRAM:#include<stdio.h> #include<conio.h> #include<alloc.h> struct node { int val;struct node *lptr,*rptr; }; struct node*str; int ch; void main() { void create(void); void display(void); str=NULL; clrscr(); do { printf("\n\t BINARY TREE TRAVERSAL\n"); printf("\t *********************\n"); printf("\n 1.CREATE \n"); printf("\n 2.DISPLAY\n"); printf("\n Enter ur choice:"); scanf("%d",&ch); switch(ch) { case 1: create(); break; case 2: display(); break; } } while(ch!=2); } void create() { struct node *temp,*prev; int c,n; printf("\n Enter the number of elements:"); scanf("%d",&n); printf("\n Enter the node elements:\n");do { scanf("%d",&c); temp=str; if(temp==NULL)

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

23

{ str=(struct node*)malloc(sizeof(struct node)); temp=str; } else { while(temp!=NULL) { prev=temp; if(c<temp->val) temp=temp->lptr; else temp=temp->rptr; } temp=(struct node*)malloc(sizeof(struct node)); if(c<prev->val) prev->lptr=temp; else prev->rptr=temp; } temp->val=c; temp->lptr=NULL; temp->rptr=NULL; n--; }while(n>0); } void in(struct node *str) { if(str!=NULL) {in(str->lptr); printf("\t%d",str->val); in(str->rptr); } } void pre(struct node *str) { if(str!=NULL) { printf("\t%d",str->val); pre(str->lptr); pre(str->rptr); } } void post(struct node *str) { if(str!=NULL) { post(str->lptr); post(str->rptr);

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

24

printf("\t%d",str->val); } } void display() { void in(struct node *p); void pre(struct node *p); void post(struct node *p); do { printf("\n\n 1.INORDER \n"); printf("\n 2.PREORDER\n"); printf("\n 3.POSTORDER\n"); printf("\n 4.EXIT\n");printf("\n Enter ur choice:"); scanf("%d",&ch); switch(ch){ case 1: in(str); break; case 2: pre(str); break; case 3: post(str); break; case 4: exit(0); } }while(ch!=4); }

OUTPUT

1.CREATE 2.DISPLAY Enter ur choice:1 Enter the number of elements:5 Enter the node elements: 10 5 3 9 23 BINARY TREE TRAVERSAL ********************* 1.CREATE 2.DISPLAY Enter ur choice:2 1.INORDER

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

25

2.PREORDER 3.POSTORDER 4.EXIT Enter ur choice:1 3 5 9 10 23 1.INORDER2.PREORDER 3.POSTORDER 4.EXIT Enter ur choice:2 10 5 3 9 23 1.INORDER 2.PREORDER 3.POSTORDER 4.EXIT Enter ur choice:3 3 9 5 23 10 1.INORDER 2.PREORDER 3.POSTORDER 4.EXIT Enter ur choice:4

RESULT:

Thus the binary tree traversal program has been executed successfully and the output has been verified.

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

26

EX NO: 5 CIRCULAR QUEUE TO SIMULATE A PRODUCER-CONSUMER PROBLEM

AIM: To write a program to implement array based circular queue to simulate producer-consumer problem.

ALGORITHM:

ALGORITHM FOR INSERTION:Step 1: If "rear" of the queue is pointing to the last position then go to step-ii or else step-iiiStep 2: make the "rear" value as 0Step 3: increment the "rear" value by oneStep 4: a. if the "front" points where "rear" is pointing and the queue holds a not NULL value for it, then it’s a "queue overflow" state, so quit; else go to step-b b. insert the new value for the queue position pointed by the "rear".

ALGORITHM FOR DELETION:Step 1: If the queue is empty then say "empty queue" and quit; else continueStep 2: Delete the "front" elementStep 3: If the "front" is pointing to the last position of the queue then step-iv else step-vStep 4: Make the "front" point to the first position in the queue and quitStep 5: Increment the "front" position by one4. Terminate the program.

PROGRAM:

#include<stdio.h>#include<conio.h>#include<ctype.h>int frnt=-1,rear=-1,buffer[5];void consume(){if(frnt==-1)printf("\n Cannot consume till producer produces it:");else{printf("The consumed item is:%d",buffer[frnt]);if(frnt==rear)frnt=rear=-1;elsefrnt=((frnt+1)%5);}getch();}void producer(int x){if(frnt==(rear+1)%5){printf("\n Cannot produce till consumer haves it");}else{

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

27

if(frnt==-1)frnt=rear=0;elserear=((rear+1)%5);buffer[rear]=x;printf("\n The produced element is:%d",buffer[rear]);}getch();}void disp(){int i;printf("\n The buffer contains:");if(rear>=frnt){for(i=frnt;i<=rear;++i)printf("%d\t",buffer[i]);}else{

for(i=frnt;i<5;++i)printf("%d\t",buffer[i]);for(i=0;i<=rear;++i);printf("%d\t",buffer[i]);}getch();}void main(){int ch,z;do{clrscr();printf("\n Producer and Consumer");printf("\n1.Produce an item");printf("\n2.Consume an item");printf("\n3.Display the items");printf("\n4.Exit");printf("\n Enter the choice:");scanf("\t%d",&ch);switch(ch){case 1:printf("\n Enter the item to be inserted in buffer");scanf("%d",&z);producer(z);break;case 2:consume();

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

28

break;case 3:disp();break;case 4:exit(0);break;}} while(ch<=4);}

OUTPUT

Producer and Consumer1.Produce an item2.Consume an item3.Display the items4.ExitEnter the choice:1Enter the item to be inserted in buffer 25The produced element is:25Enter the choice:3

The buffer contains:25Enter the choice:2The consumed item is:25Enter the choice:3The buffer contains:0Enter the choice:4

RESULT:

Thus the program for producer consumer problem using circular queue is successfully executed.

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

29

EX NO: 6 BINARY SEARCH TREE

AIM: To write a program to implement a binary search tree

ALGORITHM: Step 1: Start Step 2: Read the value of ch Step 3: If ch=1 insert function should be called Step 4: If ch=2 delete functions should be called Step 5: If ch=3 view functions should be called Step 6: If ch=4 exit insert function should be called Step 7; Return while ch! 4Step 8: Stop ALGORITHM FOR INSERT:Step 1: If (tree =null), empty allocate memory space to tree Step 2: Assign num into tree -> Lchild item Step 3: Set null to tree ->Lchild item and free -> rchild Step 4: If (num < tree -> item) insert num on the Lchild of the node by repeating the step 4. Step 5: Else (num > tree -> item ) insert the num on rchild of the node by repeating step 5 else Step 6: Return tree ALGORITHM FOR DELETE:Step 1: Start Step 2: Assign p=tree and v=null Step 3: Search for the element to be deleted Step 4: Check if P-> Lchild=NULL, P->rchild inplacing node Step 5: Check if P=NULL, condition tree print key don’t existStep 6: Else check if p->rchild=null tree->lchild is replaced node Step 7: Check if (f1=P) assign rp->rchild to f->Lchild and p->rchild to rp->rchild Step 8: Assign p->lchild to rp->lchild Step 9: Check q =null and assign replacing node is root node Step 10: Else if p=q ->lchild attaches the rp node as the last if q, otherwise attach rp nodes on right of q ALGORITHM FOR SEARCH:Step 1: start Step 2: Check if (true! =NULL) Step 3: Execute visit left child Step 4: Print tree -> item Step 5: Stop

PROGRAM:#include<stdio.h> #include<stdlib.h> #include<conio.h> #include<alloc.h> typedef struct node { int data; struct node *left,*right; }tree;

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

30

void displaymenu(); void readnode(tree *); void releasenode(tree *head); tree *getnode(); tree *createbtree(); tree *insertnode(tree *btree,tree *temp); tree *deletenode(int digit,tree *btree); tree *searchnode(tree *btree,int key); void view(tree *btree,int level); void main() {int choice,key; tree *btree=NULL,*temp; clrscr(); printf("\n\n\t\tIMPLEMENTATION OF BINARY SEARCH TREE\n"); printf("\t\t************************************\n"); displaymenu(); while(1) { printf("\n Enter ur choice:"); scanf("%d",&choice); switch(choice) { case 0: displaymenu(); break; case 1: btree=NULL; printf("\n CREATE A NEW BINARY TREE\n"); btree=createbtree(); break; case 2: printf("\n INSERT THE NODE IN THE TREE\n"); temp=getnode(); readnode(temp); btree=insertnode(btree,temp); break; case 3: if(btree==NULL) printf("\n BINARY TREE IS EMPTY\n"); else { printf("\n DELETE THE NODE FROM THE TREE\n"); printf("\n ENTER THE NODE FOR DELETING :"); scanf("%d",&key); btree=deletenode(key,btree); } break;case 4:

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

31

if(btree==NULL) printf("\n BINARY TREE IS EMPTY\n"); else { printf("\n SEARCH THE NODE IN THE TREE\n\n"); printf("\n ENTER THE SEARCHING ELEMENT:"); scanf("%d",&key); temp=searchnode(btree,key); if(temp==NULL) printf("\n SEARCH ELEMENT %d IS NOT FOUND",key); else printf("\n SEARCH ELEMENT %d IS FOUND ",temp->data); } break; case 5: if(btree!=NULL) { printf("\n BINARY SEARCH TREE IS\n"); view(btree,1); } else printf("\n BINARY TREE IS EMPTY\n"); break; default: printf("\n END OF THE RUN OF UR PROGRAM\n"); releasenode (btree); exit(0); } } } tree *getnode() { int size; tree *newnode; size=sizeof(tree); newnode=(tree *)malloc(size);return(newnode); } void readnode(tree *newnode) { printf("\n ENTER THE DATA:"); scanf("%d",&newnode->data); newnode->left=NULL; newnode->right=NULL; } void releasenode(tree *head) { free(head); } tree *createbtree()

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

32

{ char ch; tree *btree=NULL,*temp; do { temp=getnode() readnode(temp); btree=insertnode(btree,temp); fflush(stdin); printf("\n DO U WISH TO ADD DATA IN THE TREE(Y/N)?"); scanf("%c",&ch); } while(ch=='y'); return btree; } tree *insertnode(tree *btree,tree *temp) { if(btree==NULL) return temp; else if(temp->data<btree->data) btree->left=insertnode(btree->left,temp); else if(temp->data>btree->data)btree->right=insertnode(btree->right,temp); else if (temp->data==btree->data) { printf("\n DATA IS ALREADY EXISTING...."); return btree; } return btree; } tree *deletenode(int key,tree *btree) { tree *p,*fop,*suc,*fosuc; p=btree; fop=NULL; while(p!=NULL&&p->data!=key) { fop=p; p=(key<p->data)?p->left:p->right; } if(p==NULL) { printf("\n ELEMENT IS NOT FOUND .."); return btree; } if(p->left!=NULL&&p->right!=NULL) { for(fosuc=p,suc=p->right;suc->left!=NULL;suc=suc->left) fosuc=suc; if(suc->right==NULL)

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

33

{ if(fosuc->right==suc) fosuc->right=NULL; else if(fosuc->left==suc) fosuc->left=NULL; } else if(suc->right!=NULL) { if(fosuc->right==suc) fosuc->right=suc->right;else if (fosuc->left==suc) fosuc->left=suc->right; } suc->left=p->left; suc->right=p->right; if(fop==NULL) return suc; if(fop->left==p) fop->left=suc; if(fop->left==p) fop->left=suc; else if(fop->right==p) fop->right=suc; return btree; } else if(p->left==NULL&&p->right==NULL) { if(fop==NULL) return NULL; else if(fop->right==p) fop->right=NULL; else if (fop->left==p) fop->left=NULL; } else if((p->left!=NULL&&p->right==NULL)||(p->left==NULL&&p->right!=NULL)) { if(fop==NULL) return((p->right!=NULL)?p->right:p->left); else if(fop->right==p) fop->right=((p->right!=NULL)?p->right:p->left); else if(fop->left==p) fop->left=((p->left!=NULL)?p->right:p->left); } releasenode(p); return btree; } tree *searchnode(tree *btree,int key){ if(btree==NULL)

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

34

return NULL; else if (key<btree->data) return searchnode(btree->left,key); else if (key>btree->data) return searchnode(btree->right,key); else if(key==btree->data) return btree; } void view(tree *btree,int level) { int k; if(btree==NULL) return; view(btree->right,level+1); printf("\n"); for(k=0;k<level;k++) printf(" "); printf("%d",btree->data); view(btree->left,level+1); } void displaymenu() { printf("\n BASIC OPERATIONS IN A BINARY SEARCH TREE\n"); printf("\n 0.SHOW MENU"); printf("\n 1.CREATE BINARY TRE"); printf("\n 2.INSERT A NODE"); printf("\n 3.DELETE A NODE"); printf("\n 4.SEARCH A NODE"); printf("\n 5.VIEW THE BINARY TREE"); printf("\n 6.EXIT\n"); }

OUTPUT

BASIC OPERATIONS IN A BINARY SEARCH TREE 0. SHOW MENU1. CREATE BINARY TRE 2. INSERT A NODE 3. DELETE A NODE 4. SEARCH A NODE 5. VIEW THE BINARY TREE 6. EXIT Enter ur choice: 1 CREATE A NEW BINARY TREE ENTER THE DATA: 10 DO U WISH TO ADD DATA IN THE TREE(Y/N)?y ENTER THE DATA:7 DO U WISH TO ADD DATA IN THE TREE(Y/N)?y ENTER THE DATA:9 DO U WISH TO ADD DATA IN THE TREE(Y/N)?y ENTER THE DATA:5

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

35

DO U WISH TO ADD DATA IN THE TREE(Y/N)?y ENTER THE DATA:2 DO U WISH TO ADD DATA IN THE TREE(Y/N)?n Enter ur choice:5 BINARY SEARCH TREE IS 10 9 7 5 2 Enter ur choice:2 INSERT THE NODE IN THE TREE ENTER THE DATA:6 Enter ur choice:5 BINARY SEARCH TREE IS 10 9 7 65 2 Enter ur choice:3 DELETE THE NODE FROM THE TREE ENTER THE NODE FOR DELETING: 7Enter ur choice:5 BINARY SEARCH TREE IS 10 9 6 5 2 Enter ur choice:4 SEARCH THE NODE IN THE TREE ENTER THE SEARCHING ELEMENT:7 SEARCH ELEMENT 7 IS NOT FOUND Enter ur choice:4 SEARCH THE NODE IN THE TREE ENTER THE SEARCHING ELEMENT:6 SEARCH ELEMENT 6 IS FOUND Enter ur choice:6 END OF THE RUN OF UR PROGRAM

RESULT:

Thus the binary search tree program has been executed successfully and the output has been verified

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

36

EX NO: 7 AVL TREEAIM: To implement AVL Rotations

ALGORITHM: Step 1: Get the element to be inserted Step 2: Pass the element to be inserted to the add procedure which in turn invokes insert procedure and places the element in correct position by maintaining the height factor Step 3: Continue step-1 till the user request otherwise exit from the process.

PROGRAM:#include<stdio.h> #include<stdlib.h> #include<conio.h> #include<alloc.h> typedef enum { FALSE ,TRUE } bool; struct node { int info; int balance; struct node *lchild; struct node *rchild; }; struct node *insert (int , struct node *, int *); struct node* search(struct node *,int);inorder(struct node *); display(struct node *,int n); main() { int ht_inc; int info ; int choice; struct node *root = (struct node *)malloc(sizeof(struct node)); root = NULL; while(1) { printf("1.Insert\n"); printf("2.Display\n"); printf("3.Quit\n"); printf("Enter your choice : "); scanf("%d",&choice); switch(choice) { case 1: printf("Enter the value to be inserted : "); scanf("%d", &info); if( search(root,info) == NULL ) root = insert(info, root, &ht_inc); else

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

37

printf("Duplicate value ignored\n"); break; case 2: if(root==NULL) { printf("Tree is empty\n"); continue; } printf("Tree is :\n"); display(root, 1); printf("\n\n"); printf("Inorder Traversal is: "); inorder(root);printf("\n"); break; case 3: exit(1); default: printf("Wrong choice\n"); } } } struct node* search(struct node *ptr,int info) { if(ptr!=NULL) if(info < ptr->info)ptr=search(ptr->lchild,info); else if( info > ptr->info) ptr=search(ptr->rchild,info); return(ptr); }/*End of search()*/ struct node *insert (int info, struct node *pptr, int *ht_inc) { struct node *aptr; struct node *bptr; if(pptr==NULL) { pptr = (struct node *) malloc(sizeof(struct node)); pptr->info = info; pptr->lchild = NULL; pptr->rchild = NULL; pptr->balance = 0; *ht_inc = TRUE; return (pptr); } if(info < pptr->info) { pptr->lchild = insert(info, pptr->lchild, ht_inc); if(*ht_inc==TRUE) {

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

38

switch(pptr->balance){ case -1: /* Right heavy */ pptr->balance = 0; *ht_inc = FALSE; break; case 0: /* Balanced */ pptr->balance = 1; break; case 1: /* Left heavy */ aptr = pptr->lchild; if(aptr->balance == 1) { printf("Left to Left Rotation\n"); pptr->lchild= aptr->rchild; aptr->rchild = pptr; pptr->balance = 0; aptr->balance=0; pptr = aptr; } else { printf("Left to right rotation\n"); bptr = aptr->rchild; aptr->rchild = bptr->lchild; bptr->lchild = aptr; pptr->lchild = bptr->rchild; bptr->rchild = pptr; if(bptr->balance == 1 ) pptr->balance = -1; else pptr->balance = 0; if(bptr->balance == -1) aptr->balance = 1; else aptr->balance = 0; bptr->balance=0; pptr=bptr; }*ht_inc = FALSE; }/*End of switch */ }/*End of if */ }/*End of if*/ if(info > pptr->info) { pptr->rchild = insert(info, pptr->rchild, ht_inc); if(*ht_inc==TRUE) { switch(pptr->balance)

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

39

{ case 1: /* Left heavy */ pptr->balance = 0; *ht_inc = FALSE; break; case 0: /* Balanced */ pptr->balance = -1; break; case -1: /* Right heavy */ aptr = pptr->rchild; if(aptr->balance == -1) { printf("Right to Right Rotation\n"); pptr->rchild= aptr->lchild; aptr->lchild = pptr; pptr->balance = 0; aptr->balance=0; pptr = aptr; } else { printf("Right to Left Rotation\n"); bptr = aptr->lchild; aptr->lchild = bptr->rchild; bptr->rchild = aptr; pptr->rchild = bptr->lchild; bptr->lchild = pptr;if(bptr->balance == -1) pptr->balance = 1; else pptr->balance = 0; if(bptr->balance == 1) aptr->balance = -1; else aptr->balance = 0; bptr->balance=0; pptr = bptr; }/*End of else*/ *ht_inc = FALSE; }/*End of switch */ }/*End of if*/ }/*End of if*/ return(pptr); }/*End of insert()*/ display(struct node *ptr,int level) { int i;if ( ptr!=NULL ) { display(ptr->rchild, level+1);

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

40

printf("\n"); for (i = 0; i < level; i++) printf(" "); printf("%d", ptr->info); display(ptr->lchild, level+1); } return(0); } inorder(struct node *ptr) { if(ptr!=NULL) { inorder(ptr->lchild); printf("%d ",ptr->info);inorder(ptr->rchild); } return(0); }

OUTPUT

1.Insert 2.Display 3.Quit Enter your choice : 1 Enter the value to be inserted : 10 Right to Right Rotation 1.Insert 2.Display 3.Quit Enter your choice : 1 Enter the value to be inserted : 12 Right to Right Rotation 1.Insert 2.Display 3.Quit Enter your choice : 1 Enter the value to be inserted : 14 Right to Right Rotation 1.Insert 2.Display 3.Quit Enter your choice : 1 Enter the value to be inserted : 16 1.Insert 2.Display 3.Quit Enter your choice : 1 Enter the value to be inserted : 18 Right to Right Rotation

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

41

1.Insert 2.Display 3.Quit Enter your choice : 2 Tree is : 18 16 14 12 10 8 6 4 2 Inorder Traversal is: 2 4 6 8 10 12 14 16 18 1.Insert 2.Display 3.Quit Enter your choice : 3

RESULT:

Thus the program for implementing AVL rotations is executed.

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

42

EX NO: 8 QUEUE USING BINARY HEAPING

AIM: To implement binary heap

ALGORITHM: Step 1: Get the choice which ADT to perform i) If insert get the element to be inserted and pass it to insert function ii) If delete call delete function iii) If search get the element to be searched and pass it so search function iv) If display call the display function Step 2: Continue step 1 till the user request Step 3: Exit from the process if the user don’t want to continue step 3

PRIORITY QUEUE:PROGRAM:#include<stdio.h> #include<stdlib.h> #include<conio.h> #include<alloc.h> insert(); del(); display(); struct node{ int priority; int info;struct node *link; }*front = NULL; main() { int choice; while(1) { printf("1.Insert\n"); printf("2.Delete\n"); printf("3.Display\n"); printf("4.Quit\n"); printf("Enter your choice : "); scanf("%d", &choice); switch(choice) { case 1: insert(); break; case 2: del(); break; case 3:

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

43

display(); break; default : printf("Wrong choice\n"); }/*End of switch*/ }/*End of while*/ }/*End of main()*/ insert() { struct node *tmp,*q; int added_item,item_priority; tmp = (struct node *)malloc(sizeof(struct node)); printf("Input the item value to be added in the queue : "); scanf("%d",&added_item); printf("Enter its priority : ");scanf("%d",&item_priority); tmp->info = added_item; tmp->priority = item_priority; /*Queue is empty or item to be added has priority more than first item*/ if( front == NULL || item_priority < front->priority ) { tmp->link = front; front = tmp; } else { q = front; while( q->link != NULL && q->link->priority <= item_priority ) q=q->link; tmp->link = q->link; q->link = tmp; } return(0); } del() { struct node *tmp; if(front == NULL) printf("Queue Underflow\n"); else { tmp = front; printf("Deleted item is %d\n",tmp->info); front = front->link; free(tmp); } return(0); } display()

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

44

{ struct node *ptr; ptr = front;if(front == NULL) printf("Queue is empty\n"); else { printf("Queue is :\n"); printf("Priority Item\n"); while(ptr != NULL) { printf("%5d %5d\n",ptr->priority,ptr->info); ptr = ptr->link; } } return(0); }

OUTPUT

Enter your choice : 1 Input the item value to be added in the queue : 4 Enter its priority : 3 1.Insert 2.Delete 3.Display 4.Quit Enter your choice : 1 Input the item value to be added in the queue : 5 Enter its priority : 2 1.Insert 2.Delete 3.Display 4.Quit Enter your choice : 1 Input the item value to be added in the queue : 6 Enter its priority : 4 1.Insert 2.Delete 3.Display4.Quit Enter your choice : 3 Queue is : Priority Item 1 2 2 5 3 4 4 6 1.Insert 2.Delete 3.Display

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

45

4.Quit Enter your choice : 2 Deleted item is 2 1.Insert 2.Delete 3.Display 4.Quit Enter your choice : 3 Queue is : Priority Item 2 5 3 4 4 6 1.Insert 2.Delete 3.Display 4.Quit Enter your choice : 4

RESULT:

Thus the program for implementing heap (priority queue) ADT is executed successfully.

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

46

EX NO: 9 HASHING TECHNIQUES

AIM: To implement hashing using Open Addressing

ALGORITHM: Step 1: Get the Hash Size Step 2: Get the element to placed inside the Hash Table perform open hashing place the element in the particular position chain Step 3: If the element is already in particular index, find next Empty Space Step 4: If index is HashSize-1 then Index becomes 0. Step 5: Continue step-2 till the user request otherwise exit from the process.

PROGRAM:#include <stdio.h> #include <conio.h> #define HSIZE 7 void main() { int key[10],H[HSIZE]={0,0,0,0,0,0,0},hash[10],hash1,i,j,n; clrscr(); printf("Enter no of elements:\n"); scanf("%d",&n); printf("Enter Key values:\n");for(j=0;j<n;j++) { scanf("%d",&key[j]); } printf("output:\n"); printf("Index\t\tHashtablevalue:\n"); printf("------------------------:\n"); for(j=0;j<n;j++) { hash[j]=key[j]%HSIZE; hash1=hash[j]; printf("Index=%d\n",hash1); if(H[hash1]==0) { H[hash1]=key[j]; } else { if(hash1==HSIZE-1) hash1=0; for(i=hash1;i<HSIZE;i++) { if(H[i]==0) { H[i]=key[j];

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

47

break; } } } } for(i=0;i<HSIZE;i++) { printf("%d\t\t%d\n",i,H[i]); } getch();}

OUTPUT

Enter no of elements: 5 Enter Key values: 18 72 65 34 13

Index Hashtablevalue: ------------------------: Index=4 Index=2 Index=2 Index=6 Index=6 0 13 1 0 2 72 3 65 4 18 5 0 6 34

RESULT:

Thus the program for implementing hashing is executed successfully.

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

48

EX NO: 10 TOPOLOGICAL SORTING

AIM:To write a C program to implement topological sort.

ALGORITHM:Step 1: Start the programStep 2: Find a vertex with no incoming edges.Step 3: Delete it along with all the edges outgoing from it.Step 4: If there are more than one such vertices then break the tie randomly.Step 5: Note the vertices that are deleted.Step 6: All these recorded vertices give topologically sorted list.Step 7: Stop the program.

PROGRAM:#include<stdio.h>#define max 20int n,adj[max][max];int front=-1,rear=-1,queue[max];void main(){int i,j=0,k;int topsort[max],indeg[max];clrscr();create_graph();printf("\nThe Adjacency Matrix is ::\n");display();for(i=1;i<=n;i++){indeg[i]=indegree(i);if(indeg[i]==0)insert_queue(i);}while(front<=rear){k=delete_queue();topsort[j++]=k;for(i=1;i<=n;i++){if(adj[k][i]==1){adj[k][i]=0;indeg[i]=indeg[i]-1;if(indeg[i]==0);insert_queue(i);}}}

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

49

printf("Nodes after topological sorting are ::\n");for(i=0;i<=n;i++){printf("%d",topsort[i]);printf("\n");}}create_graph(){int i,max_edges,origin,destin;printf("Enter the number of Vertices::");scanf("%d",&n);max_edges=n*(n-1);for(i=1;i<=max_edges;i++){printf("Enter edge %d(0,0 to quit): ",i);scanf("%d%d",&origin,&destin);if((origin==0)&&(destin==0))break;if(origin>n || destin>n || origin<=0 || destin<=0){printf("Invalid Edge!!!\n");i--;}elseadj[origin][destin]=1;}}display(){int i,j;for(i=1;i<=n;i++){for(j=1;j<=n;j++)printf("%d",adj[i][j]);printf("\n");}}insert_queue(int node){if(rear==max-1)printf("Queue Overflow!!!\n");else{if(front==-1)front=0;rear=rear+1;queue[rear]=node;}}

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

50

delete_queue(){int del_item;if(front==-1 || front>rear){printf("Queue Overflow!!!\n");return;}else{del_item=queue[front];front=front+1;return del_item;}}int indegree(int node){int i,in_deg=0;for(i=1;i<=n;i++)if(adj[i][node]==1)in_deg++;return in_deg;}

OUTPUTEnter the number of Vertices::7Enter edge 1(0,0 to quit): 1 2Enter edge 2(0,0 to quit): 1 3Enter edge 3(0,0 to quit): 1 4Enter edge 4(0,0 to quit): 4 3Enter edge 5(0,0 to quit): 2 4Enter edge 6(0,0 to quit): 2 5Enter edge 7(0,0 to quit): 3 6Enter edge 8(0,0 to quit): 4 6Enter edge 9(0,0 to quit): 4 7Enter edge 10(0,0 to quit): 5 4Enter edge 11(0,0 to quit): 5 7Enter edge 12(0,0 to quit): 7 6Enter edge 13(0,0 to quit): 0 0The Adjacency Matrix is:0111000000110000000100010011000100100000000000010Nodes after topological sorting are:125

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

51

4376

RESULT:

Thus the program for topological sort is successfully executed.

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

52

EX NO: 11 DIJKSTRA’S ALGORITHM

AIM:To write a C program to implement dijikstra’s algorithm to find shortest path.

ALGORITHM:Step 1: Include all the header filesStep 2: Call allSelected( )Step 3: Call Shortpath( )Step 4: Access the functions from mainStep 5: EndALGORITHM for ALLSELECTED ( ):Step 1: Initialise i=0Step 2: Check whether i<maxStep 3: Check whether Selected[i]=0 Return 0Step 4: Else Return 1Step 5: ReturnALGORITHM for SHORTPATH ( ):Step 1: Initialise i=0, Check i<max Distance[i]=INFINITEStep 2: Assign selected [current].distance [0]=0, Current=0Step 3: While (!allSelected(Selected)) Perform(Selected[i]= =0) Current=k Selected[current]=1 Print k

PROGRAM:#include<stdio.h>#include<conio.h>#define infinity 999#define max 10int G[max][max],Q[max];int n,path[max],p[max];int dest,scr,y,z;void display(int,int);void main(){void buildgraph();void dijkstra(int,int);void insert(int,int);void insertq(int);int front,rear;clrscr();printf(“\nProgram for the shortest path algorithm using priority queue”);printf(“\nEnter the number of the vertices:”);scanf(“%d”,&n);buildgraph();printf(“\nEnter the source:”);

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

53

scanf(“%d”,&scr);printf(“\nEnter the destination:”);scanf(“%d”,&dest);dijkstra(scr,dest);for(y=1;y<=max;y++)p[y]=infinity;printf(“\nThe shortest path is:\n\t”);display(dest,scr);printf(“%d”,dest);getch();}void display(int dest,int scr){int z=1;while(dest>scr){int a;a=path[dest];if(a!=scr){p[z]=a;}else{p[z]=a;}++z;dest=a;}for(y=max;y>0;y--){if(p[y]!=infinity){printf(“%d”,p[y]);}}}void buildgraph(){int i,j,v1,v2;for(i=1;i<=n;i++){for(j=1;j<=n;j++)

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

54

{printf(“\nEnter the edge of v%d to v%d:”,i,j);scanf(“%d”,&G[i][j]);}printf(“\n”);}}void insertq(int index){Q[index]=1;}void insert(int index,int vertex){path[index]=vertex;}void dijkstra(int scr,int dest){int small,dist[10],current,start,new1;int temp,i,a[10];void insertq(int);for(i=0;i<=n;i++){a[i]=0;dist[i]=infinity;}Q[scr]=1;dist[scr]=0;current=scr;while(current!=dest){small=infinity;start=dist[current];for(i=1;i<=n;i++){if(Q[i]==0){new1=start+G[current][i];if(new1<dist[i]){dist[i]=new1;insert(i,current);}if(dist[i]<small)

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

55

{small=dist[i];temp=i;}}}current=temp;insertq(current);}printf(“\nThe minimum cost is:%d”,small);}

OUTPUTProgram for the shortest path algorithm using priority queueEnter the number of the vertices: 3

Enter the edge of v1 to v1:0Enter the edge of v1 to v2:4Enter the edge of v1 to v3:5Enter the edge of v2 to v1:2Enter the edge of v2 to v2:0Enter the edge of v2 to v3:3Enter the edge of v3 to v1:4Enter the edge of v3 to v2:2Enter the edge of v3 to v3:0Enter the source: 1Enter the destination: 3The minimum cost is: 5The shortest path is: 1 3

RESULT:

Thus the program for dijikstra’s algorithm to find shortest path is successfully executed.

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

56

EX NO: 12 PRIMS ALGORITHM

AIM: To implement prim’s algorithm

ALGORITHM: Step 1: Get the no of vertex in the graph Step 2: Get the edge details from the user i.e from which source to which destination edge is present Step 3: Get which algorithm to perform i) If prims call prims algorithm display the result exit from the process Step 4: continue to step-1 till the user request Step 5: Exit from the process

PROGRAM:#include<conio.h> #include<stdio.h> #define MAX 10 #define TEMP 0#define PERM 1 #define FALSE 0 #define TRUE 1 #define infinity 9999 struct node { int predecessor; int dist; /*Distance from predecessor */ int status; }; struct edge { int u; int v; }; int adj[MAX][MAX]; int n; create_graph(); display(); maketree(struct edge tree[MAX] , int *); all_perm(struct node state[MAX]); main() {int i; //int path[MAX]; int wt_tree,count; struct edge tree[MAX]; create_graph(); printf("Adjacency matrix is :\n"); display(); count = maketree(tree,&wt_tree);

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

57

printf("Weight of spanning tree is : %d\n", wt_tree); printf("Edges to be included in spanning tree are : \n"); for(i=1;i<=count;i++) { printf("%d->",tree[i].u); printf("%d\n",tree[i].v);return(0); } create_graph() { int i,max_edges,origin,destin,wt; printf("Enter number of vertices : "); scanf("%d",&n); max_edges=n*(n-1)/2; for(i=1;i<=max_edges;i++) { printf("Enter edge %d(0 0 to quit) : ",i); scanf("%d %d",&origin,&destin); if((origin==0) && (destin==0)) break; printf("Enter weight for this edge : "); scanf("%d",&wt); if( origin > n || destin > n || origin<=0 || destin<=0) { printf("Invalid edge!\n"); i--; } else { adj[origin][destin]=wt; adj[destin][origin]=wt; } }/*End of for*/ if(i<n-1) { printf("Spanning tree is not possible\n"); } return(0); } display() { int i,j; for(i=1;i<=n;i++){ for(j=1;j<=n;j++) printf("%3d",adj[i][j]); printf("\n"); } return(0);

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

58

} int maketree(struct edge tree[MAX],int *weight) { struct node state[MAX]; int i,min,count,current; //int m; int u1,v1; *weight=0; /*Make all nodes temporary*/ for(i=1;i<=n;i++) { state[i].predecessor=0; state[i].dist = infinity; state[i].status = TEMP; } /*Make first node permanent*/ state[1].predecessor=0; state[1].dist = 0; state[1].status = PERM; /*Start from first node*/ current=1; count=0; /*count represents number of nodes in tree */ while( all_perm(state) != TRUE ) /*Loop till all the nodes become PERM*/ { for(i=1;i<=n;i++) { if ( adj[current][i] > 0 && state[i].status == TEMP ) { if( adj[current][i] < state[i].dist ) { state[i].predecessor = current;state[i].dist = adj[current][i]; } } }/*End of for*/ /*Search for temporary node with minimum distance and make it current node*/ min=infinity; for(i=1;i<=n;i++) { if(state[i].status == TEMP && state[i].dist < min) { min = state[i].dist; current=i; } }/*End of for*/ state[current].status=PERM; /*Insert this edge(u1,v1) into the tree */ u1=state[current].predecessor;

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

59

v1=current; count++; tree[count].u=u1; tree[count].v=v1; /*Add wt on this edge to weight of tree */ *weight=*weight+adj[u1][v1]; }/*End of while*/ return (count); }/*End of maketree()*/ /*This function returns TRUE if all nodes are permanent*/ int all_perm(struct node state[MAX] ) { int i; for(i=1;i<=n;i++) if( state[i].status == TEMP ) return FALSE; return TRUE; }/*End of all_perm()*/

OUTPUT

Enter number of vertices: 3 Enter edge 1(0,0 to quit): 1 2 Enter weight for this edge:1 Enter edge 2(0,0 to quit): 2 3 Enter weight for this edge: 4 Enter edge 3(0,0 to quit): 3 1 Enter weight for this edge: 2 Adjacency matrix: 0 1 2 1 0 4 2 4 0

Weight of the spanning tree: 4Edges to be included in spanning tree are: 1 31 2

RESULT:

Thus the program for implementing prim’s algorithm is executed successfully

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

60

EX NO: 13 BACKTRACKING ALGORITHM – KNAPSACK PROBLEM

AIM:To write a C program to solve the knapsack problem using backtracking algorithm

ALGORITHM:Step 1: Declare the variables, array size and functionsStep 2: Get the value of number of objects and size of knapsackStep 3: Enter weight and profit of objectsStep 4: Assign the initial valuesStep 5: Call the necessary function and display the profitStep 6: End of program

PROGRAM:#include<stdio.h>#include<conio.h>int c,cl,n,i,j,k;int q[10],x[10][10],w[10],p[10],max;void get();void knapsack();void display();void get(){printf("Enter the number of objects:");scanf("%d",&n);printf("Enter the size of knapsack: ");scanf("%d",&c);printf("\nEnter the weight & profit of the objects\n");for(i=1;i<=n;i++){printf("Enter the weight %d:",i);scanf("%d",&w[i]);printf("\nEnter 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[j][i]=0;q[j]=0;

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

61

}cl=c;for(i=j;i<=n&&w[i]<=cl;i++){x[j][i]=1;cl=cl-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("The optimal solution \t Profit \n");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("\nThe maximum Profit is: %d",max);}void main(){clrscr();get();knapsack();display();getch();}

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

62

OUTPUTEnter the number of objects: 3 Enter the size of knapsack: 100 Enter the weight & profit of the objects Enter the weight 1:60 Enter the profit of weight 1:30 Enter the weight 2:30 Enter the profit of weight 2:20 Enter the weight 3:10 Enter the profit of weight 3:10 The optimal solution Profit 1 1 1 60 0 1 1 30 0 0 1 10 The maximum Profit is: 60

RESULT:

Thus the program for knapsack problem using backtracking algorithm is successfully executed.

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

63

EX NO: 14 BRANCH AND BOUND ALGORITHM FOR TRAVELLING SALESPERSON PROBLEM

AIM:To write a C program to implement traveling sales man problem.

ALGORITHM:

Step 1: Start the program.Step 2: First, find out all (n -1)! Possible solutions, where n is the number of cities.Step 3: Determine the minimum cost by finding out the cost of everyone of these (n -1)! solutionsStep 4: Finally, keep the one with the minimum cost.Step 5: Stop the program

PROGRAM:#include<stdio.h>#include<conio.h>#include<alloc.h>int n;int a[10][10],list[20],bpath[20];int i,j,bcost,tbcost;void get();void initialize();void calc(int list[]);void swap(int x,int y);void perm(int,int);void display();void get(){printf("Enter the number of cities:");scanf("%d",&n);for(i=0;i<n;i++)for(j=0;j<n;j++){if(i!=j){if(a[i][j]==-1){printf("Enter the cost travelling from %d to %d is",i+1,j+1);scanf("%d",&a[i][j]);a[j][i]=a[i][j];}}else a[i][j]=0;}

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

64

for(i=0;i<n;i++)list[i]=i;}void initialize(){for(i=0;i<10;i++)for(j=0;j<10;j++)a[i][j]=-1;bcost=0;}void calc(int list[]){int t;tbcost=0;for(j=1;j<n;j++){t=a[list[j-1]][list[j]];if(t!=0)tbcost=tbcost+a[list[j-1]][list[j]];elsetbcost=bcost+1;}}void swap(int x, int y){int temp;temp=x;x=y;y=temp;}void perm(int k,int m){int temp,i,j;if(k==m){calc(list);if(bcost==0)bcost=tbcost+1;if((tbcost<bcost)&&(a[0][list[n-1]])!=0){bcost=tbcost;for(j=0;j<n;j++)bpath[j]=list[j];

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

65

}}else{for(i=k;i<=m;i++){swap(list[k],list[i]);perm(k+1,m);swap(list[k],list[i]);}}}void display(){printf("The best path is: \n");for(i=0;i<n;i++)printf("%d --> ",bpath[i]+1);printf("\nThe cost is %d ",bcost+a[0][bpath[n-1]]);}void main(){clrscr();initialize();get();perm(1,n-1);display();getch();}

OUTPUTEnter the number of cities: 3Enter the cost travelling from 1 to 2 is10Enter the cost travelling from 1 to 3 is15Enter the cost travelling from 2 to 3 is20The best path is:1 --> 2 --> 3 -->The cost is 45

RESULT:

Thus the program for travelling salesperson problem using branch and bound algorithm is successfully executed.

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

66

EX NO: 15 RANDOMIZED ALGORITHMAIM:To write a C program to implement randomized algorithm

ALGORITHM:Step 1: Start the programStep 2: Gives the input of some random numbersStep 3: During the execution make some random choicesStep 4: Find the smallest and largest numbers of the input by randomlyStep 5: Print the outputStep 6: Stop the program

PROGRAM:#include <stdio.h>#include <stdlib.h> /* required for randomize () and random () */#include <conio.h> /* required for clrscr() */int gen_rand(void); /* note these are declarations of functions */int find_max(int x, int y, int z);int find_min(int x, int y, int z);void main(void){int num1, num2, num3, max, min;clrscr(); /* clear the screen */num1=gen_rand();num2=gen_rand();num3=gen_rand();max=find_max(num1, num2, num3);min=find_min(num1, num2, num3);printf("Random numbers are %d, %d, and %d\n", num1, num2, num3);printf("Largest is %d. Smallest is %d.\n", max, min);}int gen_rand(void)/* returns random number in range of 0 to 99 */{int n;n=random(100); /* n is random number in range of 0 - 99 */return(n);}int find_max( int x, int y, int z)/* returns largest number */{int max;if ((x>=y) && (x>=z))

www.rejin

paul.

com

III SEM EEE EE2209-Data Structures and Algorithms

67

{max = x;}else if ((y>=x) && (y>=z)){max = y;}else{max = z;}return(max);}int find_min( int x, int y, int z)/* returns smallest number */{int min;if ((x<=y) && (x<=z)){min = x;}else if ((y<=x) && (y<=z)){min = y;}else{min = y;}return(min);}

OUTPUT

Random numbers are 1, 0, and 33Largest is 33. Smallest is 0.

RESULT:

Thus the randomized algorithm has been implemented successfully.

www.rejin

paul.

com