Data Structure Lab Manual Aim & Algo

97
IT 2205 DATA STRUCTURES LAB EX.NO . DESCRIPTION PAGE NO. 1 – A Implement singly linked lists 1 – B Implement 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 a double-ended queue (dequeue) where insertion and deletion operations are possible at both the ends. 5 Implement an expression tree. Produce its pre-order, in-order, and post-order traversals 6 Implement binary search tree 7 Implement insertion in AVL trees 8 Implement priority queue using binary heaps 9 Implement hashing with open addressing 10 Implement Prim's algorithm using priority queues to find MST of an Undirected graph 1

Transcript of Data Structure Lab Manual Aim & Algo

Page 1: Data Structure Lab Manual Aim & Algo

IT 2205 DATA STRUCTURES LAB

EX.NO. DESCRIPTION PAGE NO.

1 – A Implement singly linked lists

1 – B Implement doubly linked lists

2Represent a polynomial as a linked list and write functions

for polynomial addition

3Implement stack and use it to convert infix to postfix

expression

4

Implement a double-ended queue (dequeue) where

insertion and deletion operations are possible at both the

ends.

5Implement an expression tree. Produce its pre-order, in-

order, and post-order traversals

6 Implement binary search tree

7 Implement insertion in AVL trees

8 Implement priority queue using binary heaps

9 Implement hashing with open addressing

10Implement Prim's algorithm using priority queues to find

MST of an Undirected graph

BEYOND THE SYLLABUS

1 Implement Radix Sort.

1

Page 2: Data Structure Lab Manual Aim & Algo

1-A SINGLY LINKED LISTAIM:

To write a program to implement singly linked list.

ALGORITHM:

1. Start

2. Creation: Get the number of elements, and create the nodes having structures

DATA LINK and store the element in Data field, link them together to form a

linked list.

3. Insertion: Get the number to be inserted and create a new node store the value in

DATA field. And insert the node in the required position.

4. Deletion: Get the number to be deleted. Search the list from the beginning and

locate the node then delete the node.

5. Display: Display all the nodes in the list.

6. Stop.

2

Page 3: Data Structure Lab Manual Aim & Algo

PROGRAM:

 #include<stdio.h>#include<conio.h>#include<stdlib.h>#define NULL 0typedef 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{scanf("%d",&opt);switch( opt ){case 1:insert();count++;break;case 2:delet();count--;if ( count == 0 )

3

Page 4: Data Structure Lab Manual Aim & Algo

{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 );if( pos == 1 ){h = p;h->next = t;}

4

Page 5: Data Structure Lab Manual Aim & Algo

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 );} 

5

Page 6: Data Structure Lab Manual Aim & Algo

OUTPUT :

Enter the no of nodes : 3Enter the element:1 Enter the element 2 Enter the element 3 Enter your option:1.Insert         2.Delete        3.Display       4.Exit3List elements are:        1       2        3Enter your option 1Enter the element to be insrted:12Enter the position to insert: 1 Enter your option 3List elements are:        12      1       2        3Enter your option 1Enter the element to be insrted:13Enter the position to insert: 3 Enter your option 1Enter the element to be insrted:14Enter the position to insert:6 Enter your option 3List elements are:12      1       13      2       3        14Enter your option 2Enter the position to delete:1 Enter your option 3List elements are:1       13      2       3        14Enter your option 2Enter the position to delete:3 Enter your option 3List elements are:1       13      3        14Enter your option 2Enter the position to delete:4 Enter your option 3List elements are:1       13       3Enter your option 

6

Page 7: Data Structure Lab Manual Aim & Algo

1-B DOUBLY LINKED LIST

AIM:

To write a program to implement doubly linked list with Insert, Delete and Display operations.

ALGORITHM:

1. Start

2. Creation: Get the number of elements to create the list. Then create the node

having the structure BLINK DATA FLINK and store the elements in Data

field. Link them together to form a doubly linked list.

3. Insertion: Get the number to be Inserted, create a new node to store the value.

Search the list and insert the node in its right position.

4. Deletion: Get the number to be deleted. Search the list from the beginning and try

to locate node p with DATA. If found then delete the node.

5. FLINK P’s previous node to P’s Next node. BLINK P’s Next node to P’s

Previous node else display “Data not Found”.

6. Display: Display all the nodes in the list.

7. Stop.

7

Page 8: Data Structure Lab Manual Aim & Algo

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;

8

Page 9: Data Structure Lab Manual Aim & Algo

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);

9

Page 10: Data Structure Lab Manual Aim & Algo

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 );

10

Page 11: Data Structure Lab Manual Aim & Algo

}  

OUTPUT:

Enter the no of nodes: 3Enter the element3Enter your option:1.Insert         2.Delete        3.Display       4.Exit3List elements are:1      2    3Enter your option 1Enter the element to be insrted:22Enter the position to insert:1 Enter your option 3List elements are:22      1    2    3Enter your option 1Enter the element to be insrted:11Enter the position to insert:5 Enter your option 3List elements are:22 1 2 3 11 Enter your option2Enter the position to delete:1Enter your option3List elements are:1 2 3 11Enter your option 2Enter your option 4 

11

Page 12: Data Structure Lab Manual Aim & Algo

2. REPRESENT A POLYNOMIAL AS A LINKED LIST AND WRITE FUNCTIONS FOR POLYNOMIAL ADDITION

AIM:

To develop a program to represent a polynomial as a linked list and write functions for polynomial addition.

ALGORITHM:

1. Start.

2. Create a Linked lists used to represent and manipulate polynomials.

3. A polynomial can be represented as 

            P(X)  = anxne+an-1xn-1e+…+a1x1e +a 

Where ai – nonzero coefficients,0<i<n

     ei – exponent

4. Each node in the polynomial is considered as a node .Each node contains three fields

                        Node Structure 

            Coefficient Exponent Link 

 

Coefficient Field -  Which holds the coefficient of a term

Exponent Field -  Which holds the exponent value of that term

Link Field  -   Address of the next term in the polynomial 

5. P and Q are two polynomials.P & Q can be represented as linked list. 

6. P:5x2+6x+7

7. Q:3x3+4x2+x 

8. The resultant polynomial can be represented like this. R:3x3+9x2+7x+7 

9. Stop.

 

12

Page 13: Data Structure Lab Manual Aim & Algo

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);

13

Page 14: Data Structure Lab Manual Aim & Algo

start=insert(start,co,ex);}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{

14

Page 15: Data Structure Lab Manual Aim & Algo

p3->link=tmp;p3=p3->link;}if(p1->expo > p2->expo){tmp->coef=p1->coef;tmp->expo=p1->expo;p1=p1->link;}elseif(p2->expo > p1->expo){tmp->coef=p2->coef;tmp->expo=p2->expo;p2=p2->link;}elseif(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;

15

Page 16: Data Structure Lab Manual Aim & Algo

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()*/ 

16

Page 17: Data Structure Lab Manual Aim & Algo

OUTPUT

Polynomial 1 : How many terms u want to enter : 3Enter coeficient for term 1 : 5Enter exponent for term 1 : 2Enter coeficient for term 2 : 3Enter exponent for term 2 : 1Enter coeficient for term 3 : 1Enter exponent for term 3 : 0 

Polynomial 2 :How many terms u want to enter : 3Enter coeficient for term 1 : 3Enter exponent for term 1 : 3Enter coeficient for term 2 : 4Enter exponent for term 2 : 2Enter coeficient for term 3 : 4Enter 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) 

17

Page 18: Data Structure Lab Manual Aim & Algo

3. IMPLEMENT STACK AND USE IT TO CONVERT INFIX TO POSTFIX EXPRESSION

AIM:

To write a program to implement stack and use it to convert infid to postfix expression.

ALGORITHM:

1. Start.

2. Create a stack to store operand and operator.

3. In Postfix notation the operator follows the two operands and in the infix notation

the operator is in between the two operands. 

4. Consider the sum of A and B. Apply the operator “+” to the operands A and B

and write the sum as A+B is INFIX. + AB is PREFIX. AB+ is POSTFIX

5. Get an Infix Expression as input and evaluate it by first converting it to postfix

and then evaluating the postfix expression.

6. The expressions with in innermost parenthesis must first be converted to postfix

so that they can be treated as single operands. In this way Parentheses can be

successively eliminated until the entire expression is converted.  

7. The last pair of parentheses to be opened with in a group of parentheses encloses

the first expression with in that group to be transformed. This last-in first-out

immediately suggests the use of Stack. Precedence plays an important role in the

transforming infix to postfix.  

8. Stop.

18

Page 19: Data Structure Lab Manual Aim & Algo

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();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])

19

Page 20: Data Structure Lab Manual Aim & Algo

{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 '^':return 3;}/*End of switch*/

20

Page 21: Data Structure Lab Manual Aim & Algo

}/*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);}elsereturn (stack[top--]);}/*End of pop()*/ 

white_space(char symbol){if( symbol == Blank || symbol == Tab || symbol == '\0')return 1;elsereturn 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{

21

Page 22: Data Structure Lab Manual Aim & Algo

  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;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+ 

22

Page 23: Data Structure Lab Manual Aim & Algo

4. IMPLEMENT A DOUBLE-ENDED QUEUE (DEQUEUE) WHERE INSERTION AND DELETION OPERATIONS ARE POSSIBLE AT

BOTH THE ENDS

AIM :

To write a program to implement a double ended queue (DEQUEUE) where insertion and deletion operations are possible at both the ends.

ALGORITHM:

1. Start.2. The operations that can be performed on a dequeue are as follows 

Insert at front Insert at rear Delete from front Delete  from rear

 3. After inserting the element B at front end, the  dequeue will look like this 

      B C    D      E                                                  front                        rear             

4. After inserting the element  F at rear end,the dequeue will look like this

            B C    D      E        F                                         front                               rear   

5. We delete an element from front which has to be B. 

              C    D      E        F                                                    front                     rear   

6. We delete an element from rear which has to be F.            C    D      E                                                             front            rear     

7. Stop.

 

23

Page 24: Data Structure Lab Manual Aim & Algo

PROGRAM :

# include<stdio.h># define MAX 5int deque_arr[MAX];int left = -1;int right = -1;

main(){int choice;printf("1.Input restricted dequeue\n");printf("2.Output restricted dequeue\n");printf("Enter your choice : ");scanf("%d",&choice);switch(choice){case 1 :input_que();break;case 2:output_que();break;default:printf("Wrong choice\n");}/*End of switch*/}/*End of main()*/

input_que(){int choice;while(1){printf("1.Insert at right\n");printf("2.Delete from left\n");printf("3.Delete from right\n");printf("4.Display\n");printf("5.Quit\n");printf("Enter your choice : ");scanf("%d",&choice); switch(choice){case 1:insert_right();break;case 2:

24

Page 25: Data Structure Lab Manual Aim & Algo

delete_left();break;case 3:delete_right();break;case 4:display_queue();break;case 5:exit();default:printf("Wrong choice\n");}/*End of switch*/}/*End of while*/}/*End of input_que() */ 

output_que(){int choice;while(1){printf("1.Insert at right\n");printf("2.Insert at left\n");printf("3.Delete from left\n");printf("4.Display\n");printf("5.Quit\n");printf("Enter your choice : ");scanf("%d",&choice); switch(choice){case 1:insert_right();break;case 2:insert_left();break;case 3:delete_left();break;case 4:display_queue();break;case 5:exit();default:printf("Wrong choice\n");

25

Page 26: Data Structure Lab Manual Aim & Algo

}/*End of switch*/}/*End of while*/}/*End of output_que() */ 

insert_right(){int added_item;if((left == 0 && right == MAX-1) || (left == right+1)){printf("Queue Overflow\n");return;}if (left == -1)  /* if queue is initially empty */{left = 0;right = 0;}elseif(right == MAX-1)  /*right is at last position of queue */right = 0;elseright = right+1;printf("Input the element for adding in queue : ");scanf("%d", &added_item);deque_arr[right] = added_item ;}/*End of insert_right()*/ 

insert_left(){int added_item;if((left == 0 && right == MAX-1) || (left == right+1)){printf("Queue Overflow \n");return;}if (left == -1)/*If queue is initially empty*/{left = 0;right = 0;}elseif(left== 0)left=MAX-1;elseleft=left-1;printf("Input the element for adding in queue : ");

26

Page 27: Data Structure Lab Manual Aim & Algo

scanf("%d", &added_item);deque_arr[left] = added_item ;}/*End of insert_left()*/ 

delete_left(){if (left == -1){printf("Queue Underflow\n");return ;}printf("Element deleted from queue is : %d\n",deque_arr[left]);if(left == right) /*Queue has only one element */{left = -1;right=-1;}elseif(left == MAX-1)left = 0;elseleft = left+1;}/*End of delete_left()*/ 

delete_right(){if (left == -1){printf("Queue Underflow\n");return ;}printf("Element deleted from queue is : %d\n",deque_arr[right]);if(left == right) /*queue has only one element*/{left = -1;right=-1;}elseif(right == 0)right=MAX-1;elseright=right-1;}/*End of delete_right() */ 

display_queue(){

27

Page 28: Data Structure Lab Manual Aim & Algo

int front_pos = left,rear_pos = right;if(left == -1){printf("Queue is empty\n");return;}printf("Queue elements :\n");if( front_pos <= rear_pos ){while(front_pos <= rear_pos){printf("%d ",deque_arr[front_pos]);front_pos++;}}else{while(front_pos <= MAX-1){printf("%d ",deque_arr[front_pos]);front_pos++;}front_pos = 0;while(front_pos <= rear_pos){printf("%d ",deque_arr[front_pos]);front_pos++;}}/*End of else */printf("\n");}/*End of display_queue() */ 

28

Page 29: Data Structure Lab Manual Aim & Algo

OUTPUT:

1.Input restricted dequeue2.Output restricted dequeue Enter your choice : 1

1.Insert at right2.Delete from left3.Delete from right4.Display5.QuitEnter your choice : 1

Input the element for adding in queue : 10

1.Insert at right2.Delete from left3.Delete from right4.Display5.QuitEnter your choice : 1

Input the element for adding in queue : 20

1.Insert at right2.Delete from left3.Delete from right4.Display5.QuitEnter your choice : 1

Input the element for adding in queue : 30

1.Insert at right2.Delete from left3.Delete from right4.Display5.QuitEnter your choice : 4

Queue elements :10 20 30

1.Insert at right2.Delete from left

29

Page 30: Data Structure Lab Manual Aim & Algo

3.Delete from right4.Display5.QuitEnter your choice : 2

Element deleted from queue is : 101.Insert at right2.Delete from left3.Delete from right4.Display5.QuitEnter your choice : 4

Queue elements :20 30

1.Insert at right2.Delete from left3.Delete from right4.Display5.QuitEnter your choice : 3

Element deleted from queue is : 30

1.Insert at right2.Delete from left3.Delete from right4.Display5.QuitEnter your choice : 4

Queue elements :20

1.Insert at right2.Delete from left3.Delete from right4.Display5.QuitEnter your choice : 3

Element deleted from queue is : 20

1.Insert at right2.Delete from left

30

Page 31: Data Structure Lab Manual Aim & Algo

3.Delete from right4.Display5.QuitEnter your choice : 3

Queue Underflow

1.Insert at right2.Delete from left3.Delete from right4.Display5.QuitEnter your choice :5 

31

Page 32: Data Structure Lab Manual Aim & Algo

 5. IMPLEMENT AN EXPRESSION TREE. PRODUCE ITS PRE-

ORDER, IN-ORDER, AND POST- ORDER TRAVERSALS

AIM:

To develop a program to implement an expression tree, that produce its pre-order, in-order and post-order traversals.

  ALGORITHM:

1. Start.

2. Create a binary tree with the nodes partitioned into three disjoint subsets. The

first  subset consists of a single element called the root of the tree.the other two

subsets are themselves binary trees called the left and right sub trees of the

original tree.A left or right sub tree can be empty.Each element of a binary tree is

called node of the tree. 

3. A common operation in the binary tree is to traverse that is to pass through the

tree enumerating each nodes once.The traversal of the binary tree can be done in

three ways they are preorder,inorder,postorder traversal. 

4. To traverse a nonempty binary tree preorder we perform the following three

operations(as depth-first order) 

o Visit the root

o Traverse the left subtree in preorder

o Traverse the right  subtree in preorder

  5. To traverse a nonempty binary tree inorder we perform the following three

operations(as symmetric order) 

o Traverse the left subtree in inorder

o Visit the root

o Traverse the right subtree in inorder

32

Page 33: Data Structure Lab Manual Aim & Algo

 6. To traverse a nonempty binary tree postorder we perform the following three

operations

o Traverse the left subtree in postorder

o Traverse the right  subtree in postorder

o Visit the root

7. Stop.

33

Page 34: Data Structure Lab Manual Aim & Algo

PROGRAM:

#include<stdio.h>#include<conio.h>#include<ctype.h>#include<alloc.h>#define size 20typedef 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");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;

34

Page 35: Data Structure Lab Manual Aim & Algo

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);}elseprintf("\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)

35

Page 36: Data Structure Lab Manual Aim & Algo

{btree *temp;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);}} 

36

Page 37: Data Structure Lab Manual Aim & Algo

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-* 

37

Page 38: Data Structure Lab Manual Aim & Algo

6. IMPLEMENT BINARY SEARCH TREE

AIM :

To write a program to create binary search tree and perform insertion and search operations on it.

ALGORITHM:

1. Start

2. Create a binary tree using linked representation with nodes having the structure

LEFTDATARIGHT. Build the tree in such a way that values at each left is

less and values at each right is greater.

3. Insert: Get the value to be inserted. Create a new node and set the data field to X.

then set the left and right links to NULL.

4. Compare X with root node data in X <root continue search in left subtree. If

X=root, then display “Duplicate data”, if X>root then search in right subtree.

Then insert the node in its right position.

5. Display: Display all the data in the tree.

6. Stop.

38

Page 39: Data Structure Lab Manual Aim & Algo

PROGRAM:

#include<stdio.h>#include<conio.h>#include<alloc.h>#define NULL 0struct search{int element;struct search* left;struct search *right;};struct search *t;struct search *makeempty(struct search *);struct search *findmin(struct search *);struct search *findmax(struct search *);void inorder(struct search *);struct search *insert(int,struct search *);struct search *delet(int,struct search *);int retrieve(struct search *);

void main(){int choice,element;clrscr();printf(“\n\t\t tree”);t=makeempty(NULL);printf(“\n Operations on tree”);printf("\n 1.Findmin \t 2.Findmax \t 3.Insert \t 4.Delete \t 5.Exit \n");do{printf("\nEnter your choice:");scanf("%d",&choice);  switch(choice)      {      case 1:printf("\n Minimum:%d",retrieve(findmin(t)));break;case 2:printf("\n Maximum:%d",retrieve(findmax(t)));break;case 3:printf("\n Enter an element to insert:");scanf("%d",&element);t=insert(element,t);inorder(t);

39

Page 40: Data Structure Lab Manual Aim & Algo

break;case 4:printf("\nEnter the element to delete:");scanf("%d",&element);t=delet(element,t);inorder(t);break;case 5:exit(0);}      }while(choice!=6);getch();}

struct search *makeempty(struct search *t){if(t!=NULL){makeempty(t->left);makeempty(t->right);free(t);}return(0);}

struct search *findmin(struct search *t){if(t==NULL)return(NULL);else if(t->left==NULL)return(t);elsereturn(findmin(t->left));}struct search *findmax(struct search *t){if(t!=NULL)while(t->right!=NULL)t=t->right;return(t);}

struct search *insert(int x,struct search *t){if(t==NULL){

40

Page 41: Data Structure Lab Manual Aim & Algo

t=(struct search *)malloc(sizeof(struct search));if(t==NULL){exit(1);}else{t->element=x;t->left=t->right=NULL;}}else{if(x<t->element)t->left=insert(x,t->left);else if(x>t->element)t->right=insert(x,t->right);}      return(t);      }      struct  search *delete(int x, struct  search *t)      {      if(t==NULL)printf("\nElement not found");else if(x<t->element)t->left=delet(x,t->left);else if(x>t->element)t->right=delet(x,t->right);else if(t->left && t->right){tmp=findmin(t->right);t->element=tmp->element;      t->right=delet(t->element,t->right);}else{tmp=t;if(t->left==NULL)t=t->right;else if(t->right==NULL)t=t->left;free(tmp);}

int retrieve(struct search *p){

41

Page 42: Data Structure Lab Manual Aim & Algo

return(p->element);}

void inorder(struct search *t){if(t!=NULL){inorder(t->left);printf("\t %d\t",t->element);inorder(t->right);}} 

42

Page 43: Data Structure Lab Manual Aim & Algo

OUTPUT:

      Enter an element to insert:89      63    89      Enter your choice:3      Enter an element to insert:52      52    63           89      Enter  your choice:3      Enter an element to insert:95      52   63  89   95      Enter your choice1      Minimum :52      Enter  your choice2      Maximum:95      Enter  your choice4       Enter an element to delete:52      63              89             95      Enter your choice:5 

43

Page 44: Data Structure Lab Manual Aim & Algo

7. IMPLEMENT INSERTION IN AVL TREES

AIM:

To develop a program to implement the insertion on AVL Trees.

ALGORITHM:

1. Start.

2. Declare the node with leftlink, rightlink, data and height of node.

3. Enter the number of elements to be inserted.

4. While inserting each element the height of each node will be checked.

5. If the height difference of left and right node is equal to 2 for an node then the

height is unbalanced at the node.

6. The present node while inserting a new node at left sub tree then perform rotation

with left child otherwise rotation with right chile.

7. Height is unbalanced at Grand Parent node while inserting a new node at right

subtree of parent node then perform double rotation with left.

8. Height is unbalanced at grandparent node while inserting a new node then

perform double rotation with right.

9. To view the tree perform traversal on tree.

10. Stop.

44

Page 45: Data Structure Lab Manual Aim & Algo

PROGRAM: #include<stdio.h>#include<conio.h>#include<stdlib.h>#define FALSE 0#define TRUE 1

typedef struct Node{int data;int BF;struct Node *left;struct Node *right;}node;node *root;node *create(node *root,int data,int *current);node *remove(node *root,int data,int *current);node *find_succ(node *temp,node *root,int *current);node *right_rotation(node *root,int *current);node *left_rotation(node *root,int *current);void display(node *root); 

node *insert(int data,int *current){root=create(root,data,current);return root;} 

node *create(struct Node *root,int data,int *current){node *temp1,*temp2;if(root==NULL){root= new node;root->data=data;root->left=NULL;root->right=NULL;root->BF=0;*current=TRUE;return(root);}if(data<root->data){root->left=create(root->left,data,current);if(*current)

45

Page 46: Data Structure Lab Manual Aim & Algo

{switch(root->BF){case 1 :       temp1=root->left;       if(temp1->BF==1){printf("\n\n Single Rotation : R Rotation");root->left=temp1->right;temp1->right=root;root->BF=0;root=temp1;}else{printf("\n Double rotation : LR rotation");temp2=temp1->right;temp1->right=temp2->left;temp2->left=temp1;root->left=temp2->right;temp2->right=root;if(temp2->BF==1)root->BF=-1;elseroot->BF=0;if(temp2->BF==-1)temp1->BF=1;elsetemp1->BF=0;root=temp2;}root->BF=0;*current=FALSE;break;case 0:root->BF=1;break;case -1:root->BF=0;*current=FALSE;}}}if(data > root->data){root->right=create(root->right,data,current);if(*current!=NULL){

46

Page 47: Data Structure Lab Manual Aim & Algo

switch(root->BF){case 1:root->BF=0;*current=FALSE;break;case 0:root->BF=-1;break;case -1:temp1=root->right;if(temp1->BF==-1){printf("\n\n\n       single rotation : L Rotation");root->right=temp1->left;temp1->left=root;root->BF=0;root=temp1;}else{printf("\n Double rotation : RL rotation");temp2=temp1->left;temp1->left=temp2->right;temp2->right=temp1;root->right=temp2->left;temp2->left=root;if(temp2->BF==-1)root->BF=1;elseroot->BF=0;if(temp2->BF==1)temp1->BF=-1;elsetemp1->BF=0;root=temp2;}root->BF=0;*current=FALSE;}}}return(root);}

void display(node *root)

47

Page 48: Data Structure Lab Manual Aim & Algo

{if(root!=NULL){display(root->left);printf("  %d",root->data);display(root->right);}}

node *remove(node *root,int data,int *current){node *temp;if(root->data==13)printf("  %d",root->data);if(root==NULL){printf("\n No Such data");return (root);}else{if(data<root->data){root->left=remove(root->left,data,current);if(*current)root=right_rotation(root,current);}else{if(data>root->data){root->right=remove(root->right,data,current);if(*current)root=left_rotation(root,current);}else{temp=root;if(temp->right==NULL){root=temp->left;*current=TRUE;delete(temp);}else{

48

Page 49: Data Structure Lab Manual Aim & Algo

if(temp->left==NULL){root=temp->right;*current=TRUE;delete(temp);}else{temp->right=find_succ(temp->right,temp,current);if(*current)root=left_rotation(root,current);}}}}}return(root);}node *find_succ(node *succ,node *temp,int *current){node *temp1=succ;if(succ->left!=NULL){succ->left=find_succ(succ->left,temp,current);if(*current)succ=right_rotation(succ,current);}else{temp1=succ;temp->data=succ->data;succ=succ->right;delete(temp1);*current = TRUE;}return(succ);}node *right_rotation(node *root,int *current){node *temp1,*temp2;switch(root->BF){case 1:root->BF=0;break;case 0:

49

Page 50: Data Structure Lab Manual Aim & Algo

root->BF=-1;*current=FALSE;break;case -1:temp1=root->right;if(temp1->BF<=0){printf("\n Single Rotation : L rotation");root->right=temp1->left;temp1->left=root;if(temp1->BF==0){root->BF=-1;temp1->BF=1;*current=FALSE;}else{root->BF=temp1->BF=0;}root=temp1;}else{printf("\n   Double Rotation : RL Rotation");temp2=temp1->left;temp1->left=temp2->right;temp2->right=temp1;root->right=temp2->left;temp2->left=root;if(temp2->BF==-1)root->BF=1;elseroot->BF=0;if(temp2->BF==-1)root->BF=1;elseroot->BF=0;if(temp2->BF==1)temp1->BF=-1;elsetemp1->BF=0;root=temp2;temp2->BF=0;}}

50

Page 51: Data Structure Lab Manual Aim & Algo

return (root);}node *left_rotation(node *root,int *current){node *temp1,*temp2;switch(root->BF){case -1:root->BF=0;break;case 0:root->BF=1;*current=FALSE;break;case 1:temp1=root->left;if(temp1->BF>=0){printf("\n    Single Rotation R Rotation");root->left=temp1->right;temp1->right=root;if(temp1->BF==0){root->BF=1;temp1->BF=-1;*current=FALSE;}else{root->BF=temp1->BF=0;}root=temp1;}else{printf("\n  Double Rotatuion  : LR Rotation");temp2=temp1->right;temp1->right=temp2->left;temp2->left=temp1;root->left=temp2->right;temp2->right=root;if(temp2->BF==1)root->BF=-1;elseroot->BF=0;if(temp2->BF==-1)

51

Page 52: Data Structure Lab Manual Aim & Algo

temp1->BF=1;elsetemp1->BF=0;root=temp2;temp2->BF=0;}}return root;}void main(){node *root=NULL;int current;clrscr();root=insert(40,&current);printf("\n\t\t");display(root);root=insert(50,&current);printf("\n\t\t");display(root);root=insert(70,&current);printf("\n\t\t");display(root);root=insert(30,&current);printf("\n\t\t");display(root);root=insert(20,&current);printf("\n\t\t");display(root);root=insert(45,&current);printf("\n\t\t");display(root);root=insert(25,&current);printf("\n\t\t");display(root);root=insert(10,&current);printf("\n\t\t");display(root);root=insert(5,&current);printf("\n\t\t");display(root);printf("\n\n\n   Final AVL tree is : \n");display(root);}  

52

Page 53: Data Structure Lab Manual Aim & Algo

  OUTPUT 

4050 Inserting 70Single rotation :  L Rotation      40 50 70Inserting 30      30 40 50 70Inserting 20Single rotation :  r Rotation      20 30 40 50 70Inserting 45Double rotation :  lr Rotation      20 30 40 45 50 70Inserting 25Double rotation :  lr Rotation      20 25 30 40 45 50 70Inserting 10      10 20 25 30 40 45 50 70Inserting 5Single Rotation :   r Rotation5 10 20 25 30 40 45 50 70Final AVL Tree is:5 10 20 25 30 40 45 50 70AVL tree after deletion of a node 20:5 10 25 30 40 45 50 70AVL  tree after deletion of a node 45:

5 10 25 30 40 50 70   

53

Page 54: Data Structure Lab Manual Aim & Algo

8. IMPLEMENT PRIORITY QUEUE USING BINARY HEAPS

AIM:

To develop a program to implement the priority queue using Binary Heaps.

ALGORITHM:

1. Start.

2. Definition: An abstract data type to efficiently support finding the item

with the highest priority across a series of operations. The basic operations are:

insert, find-minimum (or maximum), and delete-minimum (or maximum). Some

implementations also efficiently support join two priority queues (meld), delete an

arbitrary item, and increase the priority of a item (decrease-key).

3. Formal Definition: The operations new(), insert(v, PQ), find-minimum or

min(PQ), and delete-minimum or dm(PQ) may be defined with axiomatic

semantics as follows.

4. new() returns a priority queue

5. min(insert(v, new())) = v

6. dm(insert(v, new())) = new()

7. min(insert(v, insert(w, PQ))) = if priority(v) < priority(min(insert(w, PQ)))

then v else min(insert(w, PQ))

8. dm(insert(v, insert(w, PQ))) = if priority(v) < priority(min(insert(w, PQ)))

then insert(w, PQ) else insert(v, dm(insert(w, PQ))) where PQ is a priority queue,

v and w are items, and priority(v) is the priority of item v. 

9. Stop.

54

Page 55: Data Structure Lab Manual Aim & Algo

PROGRAM 

#include<stdio.h>#include<conio.h>#define SIZE 5

void main(void){int rear,front,que[SIZE],choice;int Qfull(int rear),Qempty(int rear,int front);int insert(int que[SIZE],int rear,int front);int delet(int que[SIZE],int front);void display(int que[SIZE],int rear,int front);char ans;clrscr();front=0;rear=-1;do{clrscr();printf("\n\t\t     Priority Queue   \n");printf("\n Main Menu");printf("\n 1.Insert\n2.Delete\n3.Display");printf("\n Enter Your Choice  : ");scanf("%d",&choice);switch(choice){case 1 : if(Qfull(rear))printf("\n  Queue if FUll");else  rear=insert(que,rear,front);  break;  case 2:  if(Qempty(rear,front))  printf("\n  Cannot delete elements");  else  front=delet(que,front);  break;  case 3:if(Qempty(rear,front))  printf("\n  eue is empty");  else  display(que,rear,front);  break;  default:printf("\n Wrong Choice");  break;  }  printf("\n  Do you Want to continue?");

55

Page 56: Data Structure Lab Manual Aim & Algo

  ans=getche();  }  while(ans=='Y'||ans=='y');  getch();  }

  int insert(int que[SIZE],int rear,int front)  {  int item,j;  printf("\n Enter the Elements : ");  scanf("%d",&item);  if(front == -1)  front++;  j=rear;  while(j>=0 && item<que[j])  {  que[j+1]=que[j];  j--;  }  que[j+1]=item;  rear=rear+1;  return rear;  }  int Qfull(int rear)  {  if(rear==SIZE-1)  return 1;  else  return 0;  }

  int delet(int que[SIZE],int front)  {  int item;  item=que[front];  printf("\n The item deleted is %d",item);  front++;  return front;  }  Qempty(int rear,int front)  {  if((front==-1) || (front>rear))  return 1;  else  return 0;  }

56

Page 57: Data Structure Lab Manual Aim & Algo

  void display(int que[SIZE],int rear,int front)  {  int i;  printf("\n  The Queue is :  ");  for(i=front;i<=rear;i++)  printf("   %d",que[i]);  }                 

57

Page 58: Data Structure Lab Manual Aim & Algo

OUTPUT 

    Priority Queue

Main Menu 1.Insert2.Delete3.DisplayEnter Your Choice  : 1 

Enter the Elements : 50   Do you Want to continue? 

                     Priority QueueMain Menu1.Insert2.Delete3.DisplayEnter Your Choice  : 1Enter the Elements : 10

  Do you Want to continue?

Priority QueueMain Menu1.Insert2.Delete3.DisplayEnter Your Choice  : 1

Enter the Elements : 20  Do you Want to continue?

                     Priority QueueMain Menu1.Insert2.Delete3.DisplayEnter Your Choice  : 3 

  The Queue is :     10  20   50  Do you Want to continue? 

58

Page 59: Data Structure Lab Manual Aim & Algo

9. IMPLEMENT HASHING WITH OPEN ADDRESSING

AIM :

To develop a program to implement Hashing with open addressing.

ALGORITHM:

      Open addressing hashing works on the same principle as other types of hashing; that is, it uses a hashing function h and the key of a datum x to map x to h[key(x)], and the values are s tored in a table. The difference is in what is stored in the table. Instead of maintaining a pointer to a linked list, the table contains the actual values of key(x). Implementation

The table is T[0..m-1] where m is the table size, and the input is x_1,...,x_n. The has function h is given.

INSERT:

      We apply our hash function to the first value: the last digit is 9, so 19 goes in slot 9. Next is 33: this goes in slot 3. Now we come to a problem: the next number, 43 should also go into slot 3. We have no linked lists, so where does it go? In open addressing, a value that is slated for an occupied slot goes into the next empty slot. 43 then goes into slot 4. 53: slot 3 is filled, go to slot 4. Slot 4 is filled, go to slot 5. Slot 5 is empty, so 53 goes into slot 5.

The table is usually made circular, so that a value meant to be inserted into the last slot (which is occupied) is sent around to the front of the list. So if we were to insert 99 into the table, we see that slot 9 is occupied, and 99 is sent to slot 0, which is empty. Note that if we have more values entered than slots, we can run out of room in the table, and be unable to make any more insertions. For this reason, the load factor a in open addressing can never exceed 1.0 .

DELETE:

Say we want to delete 43. First we go to slot 3: It's occupied, but not by 43. So we go on to the next occupied slot. We continue to do this until we find either the number we're looking for (success), an empty slot or we arrive back where we started. In this case, the very next slot is occupied by 43, so we remove it and mark the slot as deleted. (We'll see why in a moment.)

Probing and the Probe Sequence Probing is simply another word for the sequence we used for our search and insert routines. We "probe" the table until we find an available slot. Due to the (usually) circular

59

Page 60: Data Structure Lab Manual Aim & Algo

nature of the table we have to limit the number of slots the algorithm will examine. Since there are only m slots in the table, we limit the algorithm to m comparisons.

The probe sequence is the permutation of 0,1,...,m-1 used for searching for an available slot when inserting an element. For a key k the sequence is denoted by:

h(k,0), h(k,1), ..., h(k,m-1)

Thus, h(k,0) is what we used to call h(k). The probe sequence used in the simple introductory example is simply

h(k), h(k) + 1, ..., h(k) + m - 1

all mod m (to force the circular inspection of the array). Clearly, this is a permutation, but not a very good one (we'll see why in a moment).

Linear Probing:

This is more or less self-explanatory. In linear probing, the slots in the has table are probed in a linear fashion, in order (ie. check slot 4, then slot 5, then 6, then 7,...etc). We express linear probing as

h(k,i)=[h(k) + c*i] mod m

where c is an integer. While the slots are probed in a linear fashion, they are not necessarily probed in exact order. Note that we use mod m to account for the (usually) circular nature of the table. One of the problems with linear probing is called primary clustering. In this, "blocks" of occupied slots tend to accumulate; the larger a block is, the faster it grows, by the principles of probability. This increases the average search time in the table.

60

Page 61: Data Structure Lab Manual Aim & Algo

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;if(a[key]==-1)a[key]=num;else

61

Page 62: Data Structure Lab Manual Aim & Algo

{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]);} 

62

Page 63: Data Structure Lab Manual Aim & Algo

OUTPUT 

Collision Handling By Linaer Probling  Enter the Number 131 Do U Wish to Contiue?(Y/N

  Enter the Number21 

Do U Wish to Contiue?(Y/N  Enter the Number3 

Do U Wish to Contiue?(Y/N  Enter the Number4 

Do U Wish to Contiue?(Y/N  Enter the Number 5 

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    18   1    131   2    21   3    3   4    4   5    5   6    -1   7    -1   8    8   9    9 

63

Page 64: Data Structure Lab Manual Aim & Algo

10. IMPLEMENT PRIM'S ALGORITHM USING PRIORITY QUEUES TO FIND MST OF AN UNDIRECTED GRAPH

AIM :

To develop a program to implement the Prim’s Algorithm using Priority Queues to find MST of an Undirected Graph.

ALGORITHM :

      Prim's algorithm is an algorithm in graph theory that finds a minimum spanning tree

for a connected weighted graph. This means it finds a subset of the edges that forms a

tree that includes every vertex, where the total weight of all the edges in the tree is

minimized. The algorithm was developed in 1930 by Czech mathematician Vojtěch

Jarník and later independently by computer scientist Robert C. Prim in 1957 and

rediscovered by Edsger Dijkstra in 1959. Therefore it is sometimes called the DJP

algorithm, the Jarník algorithm, or the Prim-Jarník algorithm.

The algorithm continuously increases the size of a tree starting with a single vertex until

it spans all the vertices.

1. Input: A connected weighted graph with vertices V and edges E.

2. Initialize: Vnew = {x}, where x is an arbitrary node (starting point) from V,

Enew = {}

3. Repeat until Vnew = V:

Choose edge (u,v) with minimal weight such that u is in Vnew and v is not (if

there are multiple edges with the same weight, choose arbitrarily but

consistently)

Add v to Vnew, add (u, v) to Enew

4. Output: Vnew and Enew describe a minimal spanning tree

64

Page 65: Data Structure Lab Manual Aim & Algo

PROGRAM 

#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; 

main(){      int i,j;      int path[MAX];      int wt_tree,count;      struct edge tree[MAX];       create_graph();      printf("Adjacency matrix is :\n");      display();       count = maketree(tree,&wt_tree);       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);      }}/*End of main()*/ 

create_graph(){

65

Page 66: Data Structure Lab Manual Aim & Algo

      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");            exit(1);      }}/*End of create_graph()*/ 

display(){      int i,j;      for(i=1;i<=n;i++)      {            for(j=1;j<=n;j++)                  printf("%3d",adj[i][j]);            printf("\n");      }}/*End of display()*/ 

int maketree(struct edge tree[MAX],int *weight){      struct node state[MAX];      int i,k,min,count,current,newdist;      int m;

66

Page 67: Data Structure Lab Manual Aim & Algo

      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;            v1=current;            count++;            tree[count].u=u1;

67

Page 68: Data Structure Lab Manual Aim & Algo

            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()*/      

68

Page 69: Data Structure Lab Manual Aim & Algo

OUTPUT 

Enter number of vertices : 5

Enter edge 1(0 0 to quit) : 0 1

Enter weight for this edge : 10

Invalid edge!

Enter edge 1(0 0 to quit) : 1 2

Enter weight for this edge : 10

Enter edge 2(0 0 to quit) : 2 3

Enter weight for this edge : 1

Enter edge 3(0 0 to quit) : 2 4

Enter weight for this edge : 6

Enter edge 4(0 0 to quit) : 3 4

Enter weight for this edge : 2

Enter edge 5(0 0 to quit) : 3 5

Enter weight for this edge : 7

Enter edge 6(0 0 to quit) : 4 5

Enter weight for this edge : 3

Enter edge 7(0 0 to quit) : 5 1

Enter weight for this edge : 5

Enter edge 8(0 0 to quit) : 0 0

Adjacency matrix is :

  0 10  0  0  5

10  0  1  6  0

  0  1  0  2  7

  0  6  2  0  3

  5  0  7  3  0

Weight of spanning tree is : 11

Edges to be included in spanning tree are :1->55->44->33->2 

69

Page 70: Data Structure Lab Manual Aim & Algo

  RADIX SORT

AIM:To develop a program to implement Radix Sort.

ALGORITHM:      Radix sort is one of the linear sorting algorithms for integers. It functions by sorting

the input numbers on each digit, for each of the digits in the numbers. However, the

process adopted by this sort method is somewhat counterintuitive, in the sense that the

numbers are sorted on the least-significant digit first, followed by the second-least

significant digit and so on till the most significant digit.

      To appreciate Radix Sort, consider the following analogy: Suppose that we wish to

sort a deck of 52 playing cards (the different suits can be given suitable values, for

example 1 for Diamonds, 2 for Clubs, 3 for Hearts and 4 for Spades). The 'natural' thing

to do would be to first sort the cards according to suits, then sort each of the four seperate

piles, and finally combine the four in order. This approach, however, has an inherent

disadvantage. When each of the piles is being sorted, the other piles have to be kept aside

and kept track of. If, instead, we follow the 'counterintuitive' aproach of first sorting the

cards by value, this problem is eliminated. After the first step, the four seperate piles are

combined in order and then sorted by suit. If a stable sorting algorithm (i.e. one which

resolves a tie by keeping the number obtained first in the input as the first in the output) it

can be easily seen that correct final results are obtained.

      As has been mentioned, the sorting of numbers proceeds by sorting the least

significant to most significant digit. For sorting each of these digit groups, a stable sorting

algorithm is needed. Also, the elements in this group to be sorted are in the fixed range of

0 to 9. Both of these characteristics point towards the use of Counting Sort as the sorting

algorithm of choice for sorting on each digit (If you haven't read the description on

Counting Sort already, please do so now).

      The time complexity of the algorithm is as follows: Suppose that the n input numbers

have maximum k digits. Then the Counting Sort procedure is called a total of k times.

Counting Sort is a linear, or O(n) algorithm. So the entire Radix Sort procedure takes

O(kn) time. If the numbers are of finite size, the algorithm runs in O(n) asymptotic time.  

 

70

Page 71: Data Structure Lab Manual Aim & Algo

PROGRAM 

#define NUMELTS 100# include<stdio.h>#include<conio.h>#include<math.h>void radixsort(int a[],int);

void main(){   int n,a[20],i;   clrscr();    printf("enter the number :");   scanf("%d",&n);   printf(" ENTER THE DATA -");   for(i=0;i<n;i++)    {      printf("%d.  ",i+1);      scanf("%d",&a[i]);    }    radixsort(a,n);   getch();}

void radixsort(int a[],int n){int rear[10],front[10],first,p,q,exp,k,i,y,j;struct{  int info;  int next;}node[NUMELTS];for(i=0;i<n-1;i++) {  node[i].info=a[i];  node[i].next=i+1;}node[n-1].info=a[n-1];node[n-1].next=-1;first=0;   for(k=1;k<=2;k++)      //consider only 2 digit number  {   for(i=0;i<10;i++)     {      front[i]=-1;

71

Page 72: Data Structure Lab Manual Aim & Algo

      rear[i]=-1;     }     while(first!=-1)      {       p=first;       first=node[first].next;       y=node[p].info;       exp=pow(10,k-1);       j=(y/exp)%10;       q=rear[j];       if(q==-1)       front[j]=p;       else       node[q].next=p;       rear[j]=p;      }    for(j=0;j<10&&front[j]==-1;j++)     ;    first=front[j];    while(j<=9)     {      for(i=j+1;i<10&&front[i]==-1;i++)       ;      if(i<=9)      {      p=i;      node[rear[j]].next=front[i];      }      j=i;    }    node[rear[p]].next=-1;}//copy into original arrayfor(i=0;i<n;i++){  a[i]=node[first].info;  first=node[first].next;}clrscr();textcolor(YELLOW);cprintf(" DATA AFTER SORTING:");for(i=0;i<n;i++)printf(" %d.%d",i+1,a[i]);}  

72

Page 73: Data Structure Lab Manual Aim & Algo

OUTPUT  enter the number :9

ENTER THE DATA -1.  90

2.  76

3.  12

4.  34

5.  98

6.  55

7.  43

8.  4

9.  78 

 

DATA AFTER SORTING: 1.4 2.12 3.34 4.43 5.55 6.76 7.78 8.90 9.98 

 

 

 

73