Professional Documents
Culture Documents
Data Structure Lab Manual Aim Algo
Data Structure Lab Manual Aim Algo
IT 2205
EX.NO. DESCRIPTION 1 A Implement singly linked lists 1B Implement doubly linked lists Represent a polynomial as a linked list and write functions 2 for polynomial addition Implement stack and use it to convert infix to postfix 3 expression Implement a double-ended queue (dequeue) where ends. Implement an expression tree. Produce its pre-order, inorder, and post-order traversals Implement binary search tree Implement insertion in AVL trees Implement priority queue using binary heaps Implement hashing with open addressing Implement Prim's algorithm using priority queues to find MST of an Undirected graph BEYOND THE SYLLABUS Implement Radix Sort.
PAGE NO.
5 6 7 8 9 10 1
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
3 PROGRAM: #include<stdio.h> #include<conio.h> #include<stdlib.h> #define NULL 0 typedef struct list { int no; struct list *next; }LIST; LIST *p,*t,*h,*y,*ptr,*pt; void create( void ); void insert( void ); void delet( void ); void display ( void ); int j,pos,k=1,count; void main() { int n,i = 1,opt; clrscr(); p = NULL; printf("%d",sizeof(LIST)); printf( "Enter the no of nodes :\n " ); scanf( "%d",&n ); count = n; while( i <= n) { create(); i++; } printf("\nEnter your option:\n"); printf("1.Insert \t 2.Delete \t 3.Display \t 4.Exit\n"); do { scanf("%d",&opt); switch( opt ) { case 1: insert(); count++; break; case 2: delet(); count--; if ( count == 0 )
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
4 { 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; }
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
5 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 ); }
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
6 OUTPUT : Enter the no of nodes : 3 Enter the element:1 Enter the element 2 Enter the element 3 Enter your option: 1.Insert 2.Delete 3.Display 3 List elements are: 1 2 3 Enter your option 1 Enter the element to be insrted: 12 Enter the position to insert: 1 Enter your option 3 List elements are: 12 1 2 3 Enter your option 1 Enter the element to be insrted: 13 Enter the position to insert: 3 Enter your option 1 Enter the element to be insrted: 14 Enter the position to insert:6 Enter your option 3 List elements are: 12 1 13 2 3 14 Enter your option 2 Enter the position to delete:1 Enter your option 3 List elements are: 1 13 2 3 14 Enter your option 2 Enter the position to delete:3 Enter your option 3 List elements are: 1 13 3 14 Enter your option 2 Enter the position to delete:4 Enter your option 3 List elements are: 1 13 3 Enter your option
4.Exit
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
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
.e
ee
ex
7. Stop.
cl u
si
ve
.b l
og
sp ot
3. Insertion: Get the number to be Inserted, create a new node to store the value.
.c o
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;
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
9 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);
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
10 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 );
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
11 } OUTPUT: Enter the no of nodes: 3 Enter the element3 Enter your option: 1.Insert 2.Delete 3.Display 3 List elements are: 1 2 3 Enter your option 1 Enter the element to be insrted:22 Enter the position to insert:1 Enter your option 3 List elements are: 22 1 2 3 Enter your option 1 Enter the element to be insrted: 11 Enter the position to insert:5 Enter your option 3 List elements are: 22 1 2 3 11 Enter your option 2 Enter the position to delete: 1 Enter your option 3 List elements are: 1 2 3 11 Enter your option 2 Enter your option 4
4.Exit
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
12
Exponent Field - Which holds the exponent value of that term Link Field - Address of the next term in the polynomial
7. Q:3x3+4x2+x 8. The resultant polynomial can be represented like this. R:3x3+9x2+7x+7 9. Stop.
6. P:5x2+6x+7
.e
ee
ex
cl u
si
ve
.b l
4. Each node in the polynomial is considered as a node .Each node contains three fields
og
sp ot
.c o
13 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);
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
14 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 {
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
15 p3->link=tmp; p3=p3->link; } if(p1->expo > p2->expo) { tmp->coef=p1->coef; tmp->expo=p1->expo; p1=p1->link; } else if(p2->expo > p1->expo) { tmp->coef=p2->coef; tmp->expo=p2->expo; p2=p2->link; } else if(p1->expo == p2->expo) { tmp->coef=p1->coef + p2->coef; tmp->expo=p1->expo; p1=p1->link; p2=p2->link; } }/*End of while*/ while(p1!=NULL) { tmp=malloc(sizeof(struct node)); tmp->coef=p1->coef; tmp->expo=p1->expo; if (p3_start==NULL) /*poly 2 is empty*/ { p3_start=tmp; p3=p3_start; } else { p3->link=tmp; p3=p3->link; } p1=p1->link; }/*End of while */ while(p2!=NULL) { tmp=malloc(sizeof(struct node)); tmp->coef=p2->coef;
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
16 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()*/
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
17 OUTPUT Polynomial 1 : How many terms u want to enter : 3 Enter coeficient for term 1 : 5 Enter exponent for term 1 : 2 Enter coeficient for term 2 : 3 Enter exponent for term 2 : 1 Enter coeficient for term 3 : 1 Enter exponent for term 3 : 0 Polynomial 2 : How many terms u want to enter : 3 Enter coeficient for term 1 : 3 Enter exponent for term 1 : 3 Enter coeficient for term 2 : 4 Enter exponent for term 2 : 2 Enter coeficient for term 3 : 4 Enter exponent for term 3 : 1 Polynomial 1 is : (5.0x^2) + (3.0x^1) + (1.0x^0) Polynomial 2 is : (3.0x^3) + (4.0x^2) + (4.0x^1)
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
18
immediately suggests the use of Stack. Precedence plays an important role in the
.e
ee
ex
cl u
so that they can be treated as single operands. In this way Parentheses can be
si
ve
.b l
og
sp ot
.c o
19 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])
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
20 { 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*/
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
21 }/*End of prec()*/ push(long int symbol) { if(top > MAX) { printf("Stack overflow\n"); exit(1); } else { top=top+1; stack[top] = symbol; } }/*End of push()*/ long int pop() { if (top == -1 ) { printf("Stack underflow \n"); exit(2); } else return (stack[top--]); }/*End of pop()*/
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 {
white_space(char symbol) { if( symbol == Blank || symbol == Tab || symbol == '\0') return 1; else return 0; }/*End of white_space()*/
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
22 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+
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
23
4. After inserting the element F at rear end,the dequeue will look like this F front rear 5. We delete an element from front which has to be B. C D E
ee
ex
.e
front
cl u
BC
si
front 7. Stop.
ve
rear
.b l
rear
3. After inserting the element B at front end, the dequeue will look like this BC D E front rear
og
sp ot
.c o
24 PROGRAM : # include<stdio.h> # define MAX 5 int 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:
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
25 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");
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
26 }/*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; } else if(right == MAX-1) /*right is at last position of queue */ right = 0; else right = 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; } else if(left== 0) left=MAX-1; else left=left-1; printf("Input the element for adding in queue : ");
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
27 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; } else if(left == MAX-1) left = 0; else left = 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; } else if(right == 0) right=MAX-1; else right=right-1; }/*End of delete_right() */ display_queue() {
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
28 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() */
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
29
OUTPUT: 1.Input restricted dequeue 2.Output restricted dequeue Enter your choice : 1 1.Insert at right 2.Delete from left 3.Delete from right 4.Display 5.Quit Enter your choice : 1
Input the element for adding in queue : 20 1.Insert at right 2.Delete from left 3.Delete from right 4.Display 5.Quit Enter your choice : 1
1.Insert at right 2.Delete from left 3.Delete from right 4.Display 5.Quit Enter your choice : 4 Queue elements : 10 20 30 1.Insert at right 2.Delete from left
.e
ee
ex
cl u
si
ve
.b l
1.Insert at right 2.Delete from left 3.Delete from right 4.Display 5.Quit Enter your choice : 1
og
sp ot
.c o
30 3.Delete from right 4.Display 5.Quit Enter your choice : 2 Element deleted from queue is : 10 1.Insert at right 2.Delete from left 3.Delete from right 4.Display 5.Quit Enter your choice : 4 Queue elements : 20 30 1.Insert at right 2.Delete from left 3.Delete from right 4.Display 5.Quit Enter your choice : 3 Element deleted from queue is : 30 1.Insert at right 2.Delete from left 3.Delete from right 4.Display 5.Quit Enter your choice : 4 Queue elements : 20
1.Insert at right 2.Delete from left 3.Delete from right 4.Display 5.Quit Enter your choice : 3 Element deleted from queue is : 20 1.Insert at right 2.Delete from left
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
31 3.Delete from right 4.Display 5.Quit Enter your choice : 3 Queue Underflow 1.Insert at right 2.Delete from left 3.Delete from right 4.Display 5.Quit Enter your choice :5
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
32
5. IMPLEMENT AN EXPRESSION TREE. PRODUCE ITS PREORDER, 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:
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 called node of the tree. original tree.A left or right sub tree can be empty.Each element of a binary tree is 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 4. To traverse a nonempty binary tree preorder we perform the following three operations(as depth-first order) three ways they are preorder,inorder,postorder traversal.
5. To traverse a nonempty binary tree inorder we perform the following three operations(as symmetric order)
o o o
Traverse the left subtree in preorder Traverse the right subtree in preorder
Traverse the left subtree in inorder Visit the root Traverse the right subtree in inorder
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
2. Create a binary tree with the nodes partitioned into three disjoint subsets. The
1. Start.
33 6. To traverse a nonempty binary tree postorder we perform the following three operations
o o o
Traverse the left subtree in postorder Traverse the right subtree in postorder Visit the root
7. Stop.
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
34 PROGRAM: #include<stdio.h> #include<conio.h> #include<ctype.h> #include<alloc.h> #define size 20 typedef struct node { char data; struct node *left; struct node *right; } btree; /*stack stores the operand nodes of the tree*/ btree *stack[size]; int top; void main() { btree *root; char exp[80];/*exp stores postfix expression*/ btree *create(char exp[80]); void inorder(btree *root); void preorder(btree *root); void postorder(btree *root); clrscr(); printf("\n enter the postfix expression:\n"); 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;
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
35 void push(btree*); btree *pop(); pos=0; ch=exp[pos]; while(ch!='\0') { /*create new node*/ temp=((btree*)malloc(sizeof(btree))); temp->left=temp->right=NULL; temp->data=ch; if(isalpha(ch)) push(temp); else if(ch=='+' ||ch=='-' || ch=='*' || ch=='/') { temp->right=pop(); temp->left=pop(); push(temp); } else printf("\n Invalid char Expression\n"); pos++; ch=exp[pos]; } temp=pop(); return(temp); } void push(btree *Node) { if(top+1 >=size) printf("Error:Stack is full\n"); top++; stack[top]=Node; }
btree* pop() { btree *Node; if(top==-1) printf("\nerror: stack is empty..\n"); Node =stack[top]; top--; return(Node); } void inorder(btree *root)
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
36 { 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); } }
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
37
OUTPUT: Enter the postfix expression: ab+cd-* The tree is created..... Inorder traversal: a+b*c-d Preorder traversal: *+ab-cd
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
38
.e
ee
ex
cl u
si
ve
.b l
X=root, then display Duplicate data, if X>root then search in right subtree.
og
sp ot
.c o
39 PROGRAM: #include<stdio.h> #include<conio.h> #include<alloc.h> #define NULL 0 struct 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);
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
40 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); else return(findmin(t->left)); } struct search *findmax(struct search *t) { if(t!=NULL) while(t->right!=NULL) t=t->right; return(t); }
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
41 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) {
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
42 return(p->element); } void inorder(struct search *t) { if(t!=NULL) { inorder(t->left); printf("\t %d\t",t->element); inorder(t->right); } }
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
43 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
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
44
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
45 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)
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
46 { 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; else root->BF=0; if(temp2->BF==-1) temp1->BF=1; else temp1->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) {
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
47 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; else root->BF=0; if(temp2->BF==1) temp1->BF=-1; else temp1->BF=0; root=temp2; } root->BF=0; *current=FALSE; } } } return(root); } void display(node *root)
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
48 { 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 {
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
49 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:
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
50 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; else root->BF=0; if(temp2->BF==-1) root->BF=1; else root->BF=0; if(temp2->BF==1) temp1->BF=-1; else temp1->BF=0; root=temp2; temp2->BF=0; } }
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
51 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; else root->BF=0; if(temp2->BF==-1)
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
52 temp1->BF=1; else temp1->BF=0; root=temp2; temp2->BF=0; } } return root; } void main() { node *root=NULL; int current; clrscr(); root=insert(40,¤t); printf("\n\t\t"); display(root); root=insert(50,¤t); printf("\n\t\t"); display(root); root=insert(70,¤t); printf("\n\t\t"); display(root); root=insert(30,¤t); printf("\n\t\t"); display(root); root=insert(20,¤t); printf("\n\t\t"); display(root); root=insert(45,¤t); printf("\n\t\t"); display(root); root=insert(25,¤t); printf("\n\t\t"); display(root); root=insert(10,¤t); printf("\n\t\t"); display(root); root=insert(5,¤t); printf("\n\t\t"); display(root); printf("\n\n\n Final AVL tree is : \n"); display(root); }
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
53
OUTPUT 40 50 Inserting 70 Single rotation : L Rotation 40 50 70 Inserting 30 30 40 50 70 Inserting 20 Single rotation : r Rotation 20 30 40 50 70 Inserting 45 Double rotation : lr Rotation 20 30 40 45 50 70 Inserting 25 Double rotation : lr Rotation 20 25 30 40 45 50 70 Inserting 10 10 20 25 30 40 45 50 70 Inserting 5 Single Rotation : r Rotation 5 10 20 25 30 40 45 50 70 Final AVL Tree is: 5 10 20 25 30 40 45 50 70 AVL tree after deletion of a node 20: 5 10 25 30 40 45 50 70 AVL tree after deletion of a node 45: 5 10 25 30 40 50 70
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
54
with the highest priority across a series of operations. The basic operations are: implementations also efficiently support join two priority queues (meld), delete an 3. Formal Definition: The operations new(), insert(v, PQ), find-minimum or
9.
then insert(w, PQ) else insert(v, dm(insert(w, PQ))) where PQ is a priority queue,
.e
8.
ee
ex
7.
cl u
6.
si
5.
min(insert(v, new())) = v
ve
4.
.b l
semantics as follows.
og
sp ot
.c o
55 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?");
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
56 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; }
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
57 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]); }
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
58 OUTPUT Priority Queue Main Menu 1.Insert 2.Delete 3.Display Enter Your Choice : 1 Enter the Elements : 50 Do you Want to continue? Main Menu 1.Insert 2.Delete 3.Display Enter Your Choice : 1 Enter the Elements : 10 Do you Want to continue? Priority Queue Main Menu 1.Insert 2.Delete 3.Display Enter Your Choice : 1
Main Menu 1.Insert 2.Delete 3.Display Enter Your Choice : 3 The Queue is : 10 20 50 Do you Want to continue?
Priority Queue
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
Priority Queue
59
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 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.
DELETE:
.e
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 .
ee
ex
cl u
si
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.
ve
.b l
og
sp ot
INSERT:
.c o
60
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).
.e
ee
ex
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.
cl u
si
ve
.b l
og
sp ot
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
.c o
Linear Probing:
61 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
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
62 { 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]); }
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
63 OUTPUT Collision Handling By Linaer Probling Enter the Number 131 Do U Wish to Contiue?(Y/N Enter the Number 21 Do U Wish to Contiue?(Y/N Enter the Number 3 Do U Wish to Contiue?(Y/N Enter the Number 4 Do U Wish to Contiue?(Y/N Enter the Number 5 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
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
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
.e
Enew = {}
ee
ex
cl u
si
ve
The algorithm continuously increases the size of a tree starting with a single vertex until
.b l
og
sp ot
Jarnk and later independently by computer scientist Robert C. Prim in 1957 and
.c o
tree that includes every vertex, where the total weight of all the edges in the tree is
65 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() {
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
66 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;
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
67 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;
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
68 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()*/
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
69 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 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 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->5 5->4 4->3 3->2 Enter edge 8(0 0 to quit) : 0 0 Enter weight for this edge : 1
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
70
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. significant to most significant digit. For sorting each of these digit groups, a stable sorting 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.
algorithm is needed. Also, the elements in this group to be sorted are in the fixed range of
.e
As has been mentioned, the sorting of numbers proceeds by sorting the least
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
71
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;
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
72 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 array for(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]); }
.e
ee
ex
cl u
si
ve
.b l
og
sp ot
.c o
.e
ee
ex
cl u
si
ve
.b l
DATA AFTER SORTING: 1.4 2.12 3.34 4.43 5.55 6.76 7.78 8.90 9.98
og
sp ot
.c o