You are on page 1of 38

DATA STRUCTURE LAB ASSIGNMENT

ABHRATANU PAL ROLL NO-000911102017 BACHELOR OF INSTRUMENTATION AND ELECTRONICS ENGINEERING THIRD YEAR FIRST SEMESTER

2011

Legend: Wacp- write a C program. bst- Binary Search tree. 1. Suppose that an ordered list of numbers is implemented by means of an array. Wacp using separate functions to i) insert a number ii) delete an element iii) reverse the list. Write a main program where an initial list is created and the user is prompted to ask which operation (insert, delete, reverse or quit) the user wants to perform. Depending on the users response, more inputs may be taken and the resultant list is printed after each operation by the user. The main program continues unless the user chose the quit operation. Code: /* 1. Suppose that an ordered list of numbers is implemented by means of an array, Write a C program using separate functions to i. Insert a number ii. Delete an element iii. Reverse the list */ #include <stdio.h> void array_print(int *a, size_t size) { while(size--) printf("%i ",*a++); } int array_insert(int *a, size_t size, int element, size_t position) /* Inserts the `element' to the array `a'.The`size' denotes the number of current elements in the array. The `element' is inserted at a[position]. The `size' should not be the size of the array allocated. The function will check if the position specified is within the size specified. It returns a positive integer if the insertion was successful else returns a false with the error printed on stderr*/ { int *p,q; p=&q; if (position >=size) { fprintf(stderr,"\narray_insert: The specified position %i is not less than the" " size of the array which is %i\n",position,size); return 0;

} p=a+position;//the pointer to the location where the new element will get inserted a+=size;//a points to one past the last element of original array while(a>p) *(a)=*(a-1),a--; *a=element; return 1; } int array_delete(int *a, size_t size, size_t position) /*Removes the element a[position] from the array. The `size' denotes the number of elements in the array before the removal. Returned zero if the deletion failed else returns a positive integer.*/ { int *last,l; last=&l; if (position >=size) { fprintf(stderr,"\narray_delete: The specified position %i is not less than the" " size of the array which is %i\n",position,size); return 0; } last=a+size-1;// points to the last element a+=position;//a now points to the position of the deltetion while(a<last) *(a)=*(a+1),a++; return 1; } void array_reverse(int *a, size_t size) /* Reverses the array `a'. The `size' represents the number of elements in `a'*/ { int i,t; for(i=0; i < size/2 ; i++) { t=a[i]; a[i]=a[size-i-1]; a[size-i-1]=t; } } void input_array(int *a, size_t size) /*Inputs from cin*/ { while(size--) scanf("%i",a++); } int main() {

const MAX = 20; int a[20]; size_t s,p; int e; int i; printf("With How many numbers do you want to start with?,Maximum 20\n"); scanf("%i", &s); printf("Enter the array:"); input_array(a,s); step: printf("\nWhat do you want to do?" "\n 1. Insert an element.\n 2. Delete an element \n 3. Reverse" "\n 4. Display \n 5. Exit\n"); scanf("%d", &i); switch(i) { case 1: { printf("Enter the Position (zero-based) and the element to be inserted:"); scanf("%i%i",&p,&e); array_insert(a,s,e,p); s++; printf("Done!\n"); break; } case 2: { printf("Enter the position at which you want to delete the element:"); scanf("%i",&p); array_delete(a,s,p); s--; printf("Done!\n"); break; } case 3: { array_reverse(a,s); printf("Done!\n"); break; } case 4: { printf("\n"); array_print(a,s);

printf("\n\n"); break; } case 5: exit(1); default: return(1); } goto step; } 2. Wacp for i) adding and multiplying two polynomials where a polynomial is implemented by an array of records. ii) adding two sparse matrices and transposing a sparse matrix where a sparse matrix is implemented by an array of records. iii) solving Josephus problem. Code: /*adding and multiplying two polynomials where a polynomial is implemented by an array of records.*/ #include <stdio.h> #define MAX 10 struct term { int coeff ; int exp ; }; struct poly { struct term t [10] ; int noofterms ; }; void initpoly ( struct poly * ) ; void polyappend ( struct poly *, int c, int e ) ; struct poly polyadd ( struct poly, struct poly ) ; void display ( struct poly ) ; void main( ) { struct poly p1, p2, p3 ; clrscr( ) ; initpoly ( &p1 ) ; initpoly ( &p2 ) ; initpoly ( &p3 ) ; polyappend ( &p1, 1, 7 ) ;

polyappend ( &p1, 2, 6 ) ; polyappend ( &p1, 3, 5 ) ; polyappend ( &p1, 4, 4 ) ; polyappend ( &p1, 5, 2 ) ; polyappend ( &p2, 1, 4 ) ; polyappend ( &p2, 1, 3 ) ; polyappend ( &p2, 1, 2 ) ; polyappend ( &p2, 1, 1 ) ; polyappend ( &p2, 2, 0 ) ; p3 = polyadd ( p1, p2 ) ; printf ( "\nFirst polynomial:\n" ) ; display ( p1 ) ; printf ( "\n\nSecond polynomial:\n" ) ; display ( p2 ) ; printf ( "\n\nResultant polynomial:\n" ) ; display ( p3 ) ; getch( ) ; } /* initializes elements of struct poly */ void initpoly ( struct poly *p ) { int i ; p -> noofterms = 0 ; for ( i = 0 ; i < MAX ; i++ ) { p -> t[i].coeff = 0 ; p -> t[i].exp = 0 ; } } /* adds the term of polynomial to the array t */ void polyappend ( struct poly *p, int c, int e ) { p -> t[p -> noofterms].coeff = c ; p -> t[p -> noofterms].exp = e ; ( p -> noofterms ) ++ ; } /* displays the polynomial equation */ void display ( struct poly p ) { int flag = 0, i ; for ( i = 0 ; i < p.noofterms ; i++ ) { if ( p.t[i].exp != 0 ) printf ( "%d x^%d + ", p.t[i].coeff, p.t[i].exp ) ; else {

printf ( "%d", p.t[i].coeff ) ; flag = 1 ; } } if ( !flag ) printf ( "\b\b " ) ; } /* adds two polynomials p1 and p2 */ struct poly polyadd ( struct poly p1, struct poly p2 ) { int i, j, c ; struct poly p3 ; initpoly ( &p3 ) ; if ( p1.noofterms > p2.noofterms ) c = p1.noofterms ; else c = p2.noofterms ; for ( i = 0, j = 0 ; i <= c ; p3.noofterms++ ) { if ( p1.t[i].coeff == 0 && p2.t[j].coeff == 0 ) break ; if ( p1.t[i].exp >= p2.t[j].exp ) { if ( p1.t[i].exp == p2.t[j].exp ) { p3.t[p3.noofterms].coeff = p1.t[i].coeff + p2.t[j].coeff ; p3.t[p3.noofterms].exp = p1.t[i].exp ; i++ ; j++ ; } else { p3.t[p3.noofterms].coeff = p1.t[i].coeff ; p3.t[p3.noofterms].exp = p1.t[i].exp ; i++ ; } } else { p3.t[p3.noofterms].coeff = p2.t[j].coeff ; p3.t[p3.noofterms].exp = p2.t[j].exp ; j++ ; } } return p3 ; }

/*Wacp for multiplying two polynomials where a polynomial is implemented by an array of records.*/ #include<stdio.h> /* structure representing a node of a linked list. The node can store a term of a polynomial */ struct polynode { float coeff ; int exp ; struct polynode *link ; }; void poly_append ( struct polynode **, float, int ) ; void display_poly ( struct polynode * ) ; void poly_multiply ( struct polynode *, struct polynode *, struct polynode ** ) ; void padd ( float, int, struct polynode ** ) ; void main( ) { struct polynode *first, *second, *mult ; int i = 1 ; first = second = mult = NULL ; /* empty linked lists */ poly_append ( &first, 3, 5 ) ; poly_append ( &first, 2, 4 ) ; poly_append ( &first, 1, 2 ) ; clrscr( ) ; display_poly ( first ) ; poly_append ( &second, 1, 6 ) ; poly_append ( &second, 2, 5 ) ; poly_append ( &second, 3, 4 ) ; printf ( "\n\n" ) ; display_poly ( second ) ; printf ( "\n" ); while ( i++< 79 ) printf ( "-" ) ; poly_multiply ( first, second, &mult ) ; printf ( "\n\n" ) ; display_poly ( mult ) ; } /* adds a term to a polynomial */ void poly_append ( struct polynode **q, float x, int y ) { struct polynode *temp ; temp = *q ; /* create a new node if the list is empty */ if ( *q == NULL )

{ *q = malloc ( sizeof ( struct polynode ) ) ; temp = *q ; } else { /* traverse the entire linked list */ while ( temp -> link != NULL ) temp = temp -> link ; /* create new nodes at intermediate stages */ temp -> link = malloc ( sizeof ( struct polynode ) ) ; temp = temp -> link ; } /* assign coefficient and exponent */ temp -> coeff = x ; temp -> exp = y ; temp -> link = NULL ; } /* displays the contents of linked list representing a polynomial */ void display_poly ( struct polynode *q ) { /* traverse till the end of the linked list */ while ( q != NULL ) { printf ( "%.1f x^%d : ", q -> coeff, q -> exp ) ; q = q -> link ; } printf ( "\b\b\b " ) ; /* erases the last colon(:) */ } /* multiplies the two polynomials */ void poly_multiply ( struct polynode *x, struct polynode *y, struct polynode **m ) { struct polynode *y1 ; float coeff1, exp1 ; y1 = y ; /* point to the starting of the second linked list */ if ( x == NULL && y == NULL ) return ; /* if one of the list is empty */ if ( x == NULL ) *m = y ; else { if ( y == NULL ) *m = x ; else /* if both linked lists exist */ { /* for each term of the first list */

while ( x != NULL ) { /* multiply each term of the second linked list with a term of the first linked list */ while ( y != NULL ) { coeff1 = x -> coeff * y -> coeff ; exp1 = x -> exp + y -> exp ; y = y -> link ; /* add the new term to the resultant polynomial */ padd ( coeff1, exp1, m ) ; } y = y1 ; /* reposition the pointer to the starting of the second linked list */ x = x -> link ; /* go to the next node */ } } } } /* adds a term to the polynomial in the descending order of the exponent */ void padd ( float c, int e, struct polynode **s ) { struct polynode *r, *temp = *s ; /* if list is empty or if the node is to be inserted before the first node */ if ( *s == NULL || e > ( *s ) -> exp ) { *s = r = malloc ( sizeof ( struct polynode ) ) ; ( *s ) -> coeff = c ; ( *s ) -> exp = e ; ( *s ) -> link = temp ; } else { /* traverse the entire linked list to search the position to insert a new node */ while ( temp != NULL ) { if ( temp -> exp == e ) { temp -> coeff += c ; return ; } if ( temp -> exp > e && ( temp -> link -> exp< e || temp -> link == NULL ) ) { r = malloc ( sizeof ( struct polynode ) ) ; r -> coeff = c; r -> exp = e ; r -> link = temp -> link ; temp -> link = r ;

return ; } temp = temp -> link ; /* go to next node */ } r -> link = NULL ; temp -> link = r ; } } /*********************************************************************** ****************** *josephus.c: Solve the josephus problem for an arbitrary number of players and an * arbitrary number of players missed each time. *University of Sussex * *Author: Vuldoraq *Version History: * 6/12/2009 Version 1.0 * *Input1:Number of players *Input2:Number of players to miss each time *Output:The lucky survivor ************************************************************************ *****************/ #include <stdlib.h> /*For calloc, free and sizeof*/ #include <stdio.h> /*For printf, scanf*/ /*---Global structure to hold player details and a pointer to the next player---*/ struct player{ int player_num; struct player *next; };

int main (void) { int i, j; /*Loop counters*/ int n; /*Number of players*/ int k; /*Number to skip each time*/ struct player *firstplayer; /*Hold firstplayer, so list can be circular linked*/ struct player *current_player; /*Hold current player*/ struct player *victim; /*Hold victim, for freeing*/ /*---Welcome statement---*/ printf("\njosephus.c: Program to solve the Josephus problem for an arbitrary number of " "\n players and an arbitrary choice of count. The output will be the "

"\n number of the surviving player.\n\n");

/*---Request the number of players and assign to n---*/ printf("Please input the number of players.\n>>"); scanf("%d", &n) ; /*---Request how many players to miss and assign to k---*/ printf("Please input the number of players you want to miss before execution.\n>>"); scanf("%d", &k); /*---Alert the user, and exit the program, if they entered the wrong type of input---*/ if (n<=0 || k<=0) { printf("\a\n\nPlease enter positive integers only for the player and count!! " "\nExiting...\n\n"); return 0; } /*---Set initial current player and firstplayer to be the same and assign space dynamically to hold them---*/ firstplayer=current_player=calloc(1, sizeof(struct player)); /*---Detect allocation failure---*/ if (current_player==NULL) { printf("\a\nAllocation failure. Program terminates...\n\n"); exit(1); } current_player->player_num=1; /*Set the first/initial current players number to one*/ /*---Loop over n, assigning space for all the players and linking each successive one to * the previous. Note: we do not count from 1, since already done above---*/ for (i=2; i<=n; ++i) { current_player->next=calloc(1, sizeof(struct player)); /*---Detect allocation failure---*/ if (current_player->next==NULL) { printf("\a\nAllocation failure. Program terminates...\n\n"); exit(1); } current_player=current_player->next; /*Current player now points to the next player*/ current_player->player_num=i; /*Define each player number*/ } /*Finally link the final current player to the firstplayer, to make the list circular*/

current_player->next=firstplayer;

/*---Loop over n, counting up one every time a player dies---*/ for (i=1; i<n; ++i) { /*Cycle through players until the one just before the unlucky one is reached*/ for (j=1; j<k; ++j) { current_player=current_player->next; } /*Victim is the player just after the current player*/ victim=current_player->next; /*Set the current player to point at the space just after where the victim was*/ current_player->next=current_player->next->next; /*Set space now pointed to by victim free*/ free(victim); } /*Notify user of the game survivor*/ printf("\nThe lucky survivor is = %d\n\n", current_player->player_num); /*---Set the final players space free---*/ free(current_player); return 0; } 3. Wacp to implement a linked list of numbers using arrays.

Code: #include <stdio.h> #include <stdlib.h> #define NUMNODES 1000 int avail=0; struct nodetype{ int info,next; }; struct nodetype node[NUMNODES]; int getnode(void); void freenode(int);

main() { int q,x; int n,i=0; for(i=0;i<NUMNODES-1;i++) node[i].next=i+1; node[NUMNODES-1].next=-1; printf("Enter the number of numbers you want to insert\n Maximum 1000\n"); scanf("%d",&n); for(i=0;i<n;i++) { printf("Enter the no.\n"); scanf("%d",&x); q=getnode(); node[q].info=x; } i=0; printf("Numbers in the list are\n"); while(n>0) { printf("%d\n",node[i].info); i=node[i].next; n--; } } int getnode() { int p; if (avail==-1) { printf("overflow\n"); exit(1); } p=avail; avail=node[avail].next; return(p); } void freenode(int p) { node[p].next=avail; avail=p; } 4. Wacp to convert an infix expression to postfix expression and to evaluate a postfix expression.

Code: /*Wacp to convert an infix expression to postfix expression*/ #include<stdio.h> struct stack { int top; char item[100]; }; int empty(struct stack*); char pop(struct stack*); void push(struct stack*,char); int prior(char c,char d); void main() { char exp[100]={'\0'},res[100]={'\0'},c; struct stack s1,*sp; int j=0,i; sp=&s1; sp->top=-1; printf("Enter the infix expression you want to convert\n"); gets(exp); printf("The postfix expression is\n"); for(i=0;exp[i]!='\0';i++) { c=exp[i]; if(isdigit(c)) res[j++]=c; else if(c=='(') push(sp,c); else if(c=='+'||c=='-'||c=='*'||c=='/'||c=='^') { step: if(empty(sp)) push(sp,c); else if(sp->item[sp->top]=='(') push(sp,c); else if(prior(c,sp->item[sp->top])) push(sp,c); else { res[j++]=pop(sp); goto step; } } else if(c==')')

{ while(sp->item[sp->top]!='(') { res[j++]=pop(sp); } sp->top=sp->top-1; } } while(!empty(sp)) res[j++]=pop(sp); puts(res); } int empty(struct stack *sp) { if(sp->top==-1) return(1); else return(0); } char pop(struct stack *sp) { if(empty(sp)) return('c'); else return(sp->item[sp->top--]); } void push(struct stack *sp,char c) { sp->item[++sp->top]=c; } int prior(char c,char d) { if(c=='^'&&d!='^') return(1); else if(c=='/'&&(d=='+'||d=='-'||d=='*')) return(1); else if(c=='*'&&(d=='+'||d=='-')) return(1); else return(0); } /*Evaluating a postfix expresiion*/ #include<stdio.h> #include<stdlib.h> #include<ctype.h>

#define maxcols 80 struct stack { int top; float items[maxcols]; }; float eval(char expr[]); void push(struct stack*,float); int empty(struct stack*); float pop(struct stack*); float oper(char,float,float); float pow(float,float); main() { char expr[maxcols]; int position=0; while((expr[position++]=getchar())!='\n'); expr[--position]='\0'; printf("The original postfix operation is %s\n",expr); printf("%f\n",eval(expr)); } float eval( char expr[]) { int c,position; float opnd1,opnd2,value; struct stack s1,*sp; sp=&s1; sp->top=-1; for(position=0;(c=expr[position++])!='\0';) { if(isdigit(c)) push(sp,(float)(c-'0')); else { opnd2=pop(sp); opnd1=pop(sp); value=oper(c,opnd1,opnd2); push(sp,value); } } return(pop(sp)); } int empty(struct stack *sp) { if(sp->top==-1) return(1);

else return(0); } float pop(struct stack *sp){ if(empty(sp)) { printf("Invalid expression\n"); exit(0); } else return(sp->items[sp->top--]); } void push(struct stack *sp,float value) { if(sp->top==maxcols-1) { printf("Stack overflow\n"); exit(0); } else sp->items[++sp->top]=value; } float oper(char c,float x1,float x2) { if(c=='+') return(x1+x2); else if(c=='-') return(x1-x2); else if(c=='*') return(x1*x2); else if(c=='/') return(x1/x2); else if(c=='^') return(pow(x1,x2)); else { printf("Invalid expression\n"); exit(0); } } float pow(float x1,float x2) { int i=1,j=1; for(j=1;j<=x2;j++) i=x1*i; return(i);

5.Wacp to i) create a bst. ii) search for an element from the bst. iii) insert an element in the bst. iv) delete a node from the bst. Code: //WAP to implement Binary Search Tree operations (insert,delete,search,size,height) #include<stdio.h> #include<stdlib.h> void insert(int); void showBST(); int search(int); void delete(int); void size();

struct node { int data; struct node *left; struct node *right; struct node *parent; }; typedef struct node Node; Node *root=NULL,*prev,*ptr,*par=NULL; int count=0,side;

int main() { int ch,item,h; while(1) { ch=list(); if(ch==1) { printf("Enter data to insert "); scanf("%d",&item); insert(item);

} else if(ch==2) { printf("Enter data to delete "); scanf("%d",&item); delete(item); } else if(ch==3) { printf("Enter data to Search "); scanf("%d",&item); search(item); } else if(ch==4) { size(); } else if(ch==5) { h = height(root); printf("Height of BST is %d",h); } else if(ch==6) showBST(root); else exit(0); } } int height(Node *curNode) { int curHeight = 0; int curMax = 0; return(height1(curNode, curHeight, curMax)); } int height1(Node *curNode, int curHeight, int curMax) { if(curNode != NULL) { if(curHeight > curMax) { curMax = curHeight; }

if(curNode->left != NULL) { curMax = height1(curNode->left, curHeight + 1, curMax); } if(curNode->right != NULL) { curMax = height1(curNode->right, curHeight + 1, curMax); } } return(curMax); }

int list() { int ch; printf("\nChoose your option\n"); printf("1. Insert in BST\n"); printf("2. Delete in BST\n"); printf("3. Search in BST\n"); printf("4. Size of BST\n"); printf("5. Height of BST\n"); printf("6. Show BST content\n"); printf("7. Exit\n"); printf("Enter Choice "); scanf("%d",&ch); return(ch); } void insert(int item) { Node *n; n=(Node *)malloc(sizeof(Node)); n->data=item; n->left=NULL; n->right=NULL; n->parent=NULL; count=count+1; if(root==NULL) root=n; else { ptr=root; while(ptr!=NULL) { prev=ptr;

if(item>ptr->data) { ptr=ptr->right; side=1; } else { ptr=ptr->left; side=0; } } if(side==1) { prev->right=n; n->parent=prev; } else { prev->left=n; n->parent=prev; } } printf("Insert Successfully!!"); } int search(int item) { ptr=root; if(ptr==NULL) printf("BST is empty so no match Found!!"); else { while(ptr!=NULL) { if(ptr->data==item) { printf("Data is present\n"); return ptr->data; } else if(item>ptr->data) { par=ptr; ptr=ptr->right; } else {

par=ptr; ptr=ptr->left; } } printf("Data is not present in BST\n"); } }

void showBST(Node *ptr) { if(ptr!=NULL) { showBST(ptr->left); printf("%d ",ptr->data); showBST(ptr->right); } } void delete(int item) { int k=search(item); if(k!=item) printf(" so delete unsuccessful!!!"); else { Node *ptr1,*ptr2; count=count-1; if(ptr->left==NULL||ptr->right==NULL) { ptr1=ptr; } else { Node *y; if(ptr->right!=NULL) { y=ptr->right; while(y->left!=NULL) { y=y->left; } ptr1=y; } else

{ y=ptr->parent; while(y!=NULL&&ptr==y->right) { ptr=y; y=y->parent; } ptr1=y; } } if(ptr1->left!=NULL) ptr2=ptr1->left; else ptr2=ptr1->right; if(ptr2!=NULL) ptr2->parent=ptr1->parent; if(ptr1->parent==NULL) root=ptr2; else if(ptr1==ptr1->parent->left) ptr1->parent->left=ptr2; else ptr1->parent->right=ptr2; if(ptr1!=ptr) ptr->data=ptr1->data; printf("Delete successfull "); showBST(root); } } void size() { printf("Total no. of nodes are : %d\n",count); } 6. Wacp to implement merge sort i) recursively ii) in a bottom up fashion. iii) using linked list. Code: /*Wacp to implement merge sort recursively*/ #include <stdio.h> #include <stdlib.h> void merge ( int a[], int first, int mid, int last ) {

int i = first, j = mid, k = 0; int *save = malloc ( ( last - first ) * sizeof *save ); while ( i < mid && j < last ) { if ( a[i] <= a[j] ) save[k++] = a[i++]; else save[k++] = a[j++]; } while ( i < mid ) save[k++] = a[i++]; while ( j < last ) save[k++] = a[j++]; for ( i = 0; i < ( last - first ); i++ ) a[first + i] = save[i]; free ( save ); } void mergesort_r ( int a[], int first, int last ) { if ( first < last - 1 ) { int mid = ( first + last ) / 2; mergesort_r ( a, first, mid ); mergesort_r ( a, mid, last ); merge ( a, first, mid, last ); } } void mergesort ( int a[], int n ) { mergesort_r ( a, 0, n ); } const int MAX=20; size_t ARRAY_SIZE; int main() { int A[20]; int i; printf("How many elements? (MAX: %i)",MAX); scanf("%i",&ARRAY_SIZE); printf("Enter the Elements:\n"); for (i=0; i<ARRAY_SIZE; ++i)

scanf("%i",A+i);

mergesort( A, ARRAY_SIZE ); printf("\n\nSorted array is: "); for(i = 0; i < ARRAY_SIZE; ++i) printf(" %d ", A[i]); printf("\n"); } /*Wacp to implement merge sort in a bottom up fashion.*/ #include<stdio.h> #define MAX 100 void mergesort( int x[],int n) { int aux[MAX],i,j,k,l1,l2,size,u1,u2; size=1; while(size<n){ l1=0; k=0; while(l1+size<n) { l2=l1+size; u1=l2-1; u2=(l2+size-1<n)?l2+size-1:n-1; for(i=l1,j=l2;i<=u1&&j<=u2;k++) if(x[i]<=x[j]) aux[k]=x[i++]; else aux[k]=x[j++]; for(;i<=u1;k++) aux[k]=x[i++]; for(;j<=u2;k++) aux[k]=x[j++]; l1=u2+1; } for(i=l1;k<n;i++) aux[k++]=x[i]; for(i=0;i<n;i++) x[i]=aux[i]; size *=2; } } void main(){ int n,x[MAX],i;

printf("Enter the nember of elements.Maximum 100\n"); scanf("%d",&n); printf("Enter the elements\n"); for(i=0;i<n;i++) scanf("%d",&x[i]); printf("Elements before sorting\n"); for(i=0;i<n;i++) printf("%d\n",x[i]); mergesort(x,n); printf("Elements after sorting\n"); for(i=0;i<n;i++) printf("%d\n",x[i]); } /*Wacp to implement merge sort using linked list.*/ #include <stdio.h> #include <stdlib.h> struct node { int number; struct node *next; }; /* add a node to the linked list */ struct node *addnode(int number, struct node *next); /* preform merge sort on the linked list */ struct node *mergesort(struct node *head); /* merge the lists.. */ struct node *merge(struct node *head_one, struct node *head_two); int main(void) { struct node *head; struct node *current; struct node *next; int test[100]; int i,n; printf("Enter the number of elements.Maximum 100\n"); scanf("%d",&n); printf("Enter the elements\n"); for(i=0;i<n;i++) scanf("%d",&test[i]); head = NULL; /* insert some numbers into the linked list */ for(i = 0; i <n ; i++) head = addnode(test[i], head); /* sort the list */

head = mergesort(head); /* print the list */ printf(" before after\n"), i = 0; for(current = head; current != NULL; current = current->next) printf("%4d\t%4d\n", test[i++], current->number); /* free the list */ for(current = head; current != NULL; current = next) next = current->next, free(current); /* done... */ return 0; } /* add a node to the linked list */ struct node *addnode(int number, struct node *next) { struct node *tnode; tnode = (struct node*)malloc(sizeof(*tnode)); if(tnode != NULL) { tnode->number = number; tnode->next = next; } return tnode; } /* preform merge sort on the linked list */ struct node *mergesort(struct node *head) { struct node *head_one; struct node *head_two; if((head == NULL) || (head->next == NULL)) return head; head_one = head; head_two = head->next; while((head_two != NULL) && (head_two->next != NULL)) { head = head->next; head_two = head->next->next; } head_two = head->next; head->next = NULL;

return merge(mergesort(head_one), mergesort(head_two)); } /* merge the lists.. */ struct node *merge(struct node *head_one, struct node *head_two) { struct node *head_three; if(head_one == NULL) return head_two; if(head_two == NULL) return head_one; if(head_one->number < head_two->number) { head_three = head_one; head_three->next = merge(head_one->next, head_two); } else { head_three = head_two; head_three->next = merge(head_one, head_two->next); } return head_three; } 7. Wacp to implement heap sort. Code: /*Wacp to implement heap sort.*/ #include<stdio.h> void restoreHup(int*,int); void restoreHdown(int*,int,int); void main() { int a[20],n,i,j,k; printf("Enter the number of elements to sort :\n "); scanf("%d",&n); printf("Enter the elements :\n"); for(i=1;i<=n;i++){ scanf("%d",&a[i]); restoreHup(a,i); }

j=n;

for(i=1;i<=j;i++) { int temp; temp=a[1]; a[1]=a[n]; a[n]=temp; n--; restoreHdown(a,1,n); } n=j; printf("Here it is...\n"); for(i=1;i<=n;i++) printf("%4d\n",a[i]); }

void restoreHup(int *a,int i) { int v=a[i]; while((i>1)&&(a[i/2]<v)) { a[i]=a[i/2]; i=i/2; } a[i]=v; } void restoreHdown(int *a,int i,int n) { int v=a[i]; int j=i*2; while(j<=n) { if((j<n)&&(a[j]<a[j+1])) j++; if(a[j]<a[j/2]) break; a[j/2]=a[j]; j=j*2; } a[j/2]=v; }

8. Wacp to implement quick sort i) Recursively and ii) non-recursively. Code: /*Wacp to implement quick sort recursively*/ #include<stdio.h> #define MAX 1000 void quick(int a[],int,int); void partition(int a[],int,int,int*); main() { int n,x[MAX],i,lb=0,ub; printf("Enter the no. of numbers\n Maximum %d\n",MAX); scanf("%d",&n); for(i=0;i<n;i++) { printf("Enter element no. %d\n",i+1); scanf("%d",&x[i]); } ub=n-1; quick(x,lb,ub); printf("Elements after sorting\n"); for(i=0;i<n;i++) { printf("%d\n",x[i]); } } void quick(int x[],int lb,int ub) { int j; j=ub/2; if(lb>=ub) return; partition(x,lb,ub,&j); quick(x,lb,j-1); quick(x,j+1,ub); } void partition(int x[],int lb,int ub,int *pj) { int a,down,temp,up; a=x[lb]; up=ub; down=lb;

while(down<up){ while(x[down]<=a&&down<ub) down++; while(x[up]>a) up--; if(down<up){ temp=x[down]; x[down]=x[up]; x[up]=temp; } } x[lb]=x[up]; x[up]=a; *pj=up; } /*Wacp to implement quick sort non-recursively*/ #include <stdio.h> #define MAXELT 100 #define INFINITY 32760 // numbers in list should not exceed // this. change the value to suit your // needs #define SMALLSIZE 10 // not less than 3 #define STACKSIZE 100 // should be ceiling(lg(MAXSIZE)+1) int list[MAXELT+1]; struct { int a,b; } stack[STACKSIZE]; int top=-1; void interchange(int *x,int *y); void split(int first,int last,int *splitpoint); void push(int a,int b); void pop(int *a,int *b); void insertion_sort(int first,int last); void quicksort(int n); int main() // overhead! { int i=0,j,n; char t[10]; void quicksort(int); step1: printf("Enter the number <End by -1>: "); scanf("%d",&n); // one extra, to hold INFINITY // stack element.

// initialise stack

if(n==-1) goto step2; else list[i++]=n; goto step1; step2:quicksort(i-1); printf("\nThe list obtained is "); for (j=0;j<i;j++) printf("\n %d",list[j]); printf("\n\nProgram over."); getch(); return 0; // successful termination. } void interchange(int *x,int *y) { int temp; temp=*x; *x=*y; *y=temp; } void split(int first,int last,int *splitpoint) { int x,i,j,s,g; // here, atleast three elements are needed if (list[first]<list[(first+last)/2]) { // find median s=first; g=(first+last)/2; } else { g=first; s=(first+last)/2; } if (list[last]<=list[s]) x=s; else if (list[last]<=list[g]) x=last; else x=g; interchange(&list[x],&list[first]); // swap the split-point element // with the first x=list[first]; // swap

i=first+1; // initialise j=last+1; while (i<j) { do { // find j j--; } while (list[j]>x); do { i++; // find i } while (list[i]<x); interchange(&list[i],&list[j]); // swap } interchange(&list[i],&list[j]); // undo the extra swap interchange(&list[first],&list[j]); // bring the split-point // element to the first *splitpoint=j; } void push(int a,int b) { top++; stack[top].a=a; stack[top].b=b; } void pop(int *a,int *b) { *a=stack[top].a; *b=stack[top].b; top--; } void insertion_sort(int first,int last) { int i,j,c; for (i=first;i<=last;i++) { j=list[i]; c=i; while ((list[c-1]>j)&&(c>first)) { list[c]=list[c-1]; c--; } list[c]=j; } } // push

// pop

void quicksort(int n) { int first,last,splitpoint; push(0,n); while (top!=-1) { pop(&first,&last); for (;;) { if (last-first>SMALLSIZE) { // find the larger sub-list split(first,last,&splitpoint); // push the smaller list if (last-splitpoint<splitpoint-first) { push(first,splitpoint-1); first=splitpoint+1; } else { push(splitpoint+1,last); last=splitpoint-1; } } else { // sort the smaller sub-lists // through insertion sort insertion_sort(first,last); break; } } } // iterate for larger list } 9. Wacp to implement quick sort (recursively with one recursive call, not two). Code: /*Wacp to implement quick sort (recursively with one recursive call, not two).*/ #include<stdio.h> #define MAX 1000 void quick(int a[],int,int); void partition(int a[],int,int,int*); main() { int n,x[MAX],i,lb=0,ub; printf("Enter the no. of numbers\n Maximum %d\n",MAX); scanf("%d",&n); for(i=0;i<n;i++) {

printf("Enter element no. %d\n",i+1); scanf("%d",&x[i]); } ub=n-1; quick(x,lb,ub); printf("Elements after sorting\n"); for(i=0;i<n;i++) { printf("%d\n",x[i]); } } void quick(int x[],int lb,int ub) { int j=x[0],i,*k; for(i=lb+1;i<=ub;i++) { if(j>x[i]) j=x[i]; } if(lb>=ub) return; partition(x,lb,ub,&j); lb=lb+1; quick(x,lb,ub); } void partition(int x[],int lb,int ub,int *pj) { int a,down,temp,up; a=x[lb]; up=ub; down=lb; while(down<up){ while(x[down]<=a&&down<ub) down++; while(x[up]>a) up--; if(down<up){ temp=x[down]; x[down]=x[up]; x[up]=temp; } } x[lb]=x[up]; x[up]=a; *pj=up; }

10. Wacp to implement linear time sort. Code: /*Wacp to implement linear time sort.*/ #include <stdio.h> #define MAX 1000 void bucketSort(int array[MAX],int n,int m); int main() { int array[MAX]; int n; int i,m=0; printf("Enter How many Numbers :\n maximun %d\n",MAX); scanf("%d",&n); printf("Enter the elements to be sorted:\n"); for(i = 0; i < n; i++ ){ scanf("%d",&array[i]); if(m<array[i]) m=array[i]; } printf("\nThe array of elements before sorting : \n"); for (i = 0;i < n;i++) { printf("%d ", array[i]); } printf("\nThe array of elements after sorting : \n"); bucketSort(array, n,m+1); for (i = 0;i < n;i++) { printf("%d ", array[i]); } printf("\n"); return(0); } void bucketSort(int array[],int n,int m) { int i, j,k; int count[MAX]; for(i=0; i < m; i++) { count[i] = 0; } for(i=0; i < n; i++) { (count[array[i]])++; } for(i=0,j=0; j < m; j++) {

for(k=count[j];k>0;--k) { array[i++] = j; } } }

You might also like