Sie sind auf Seite 1von 59

J.K.K.MUNIRAJAH COLLEGE OF TECHNOLOGY,T.N.PALAYAM638506 DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING.

EC 2209 - DATA STRUCTURES AND OBJECT ORIENTED PROGRAMMING LAB MANUAL

YEAR: II

SEM:III

LIST OF EXPERIMENTS
EXP NO 1 2 3 4 5 6 NAME OF THE EXPERIMENT Basic Programs for C++ Concepts Array implementation of List Abstract Data Type (ADT) Linked list implementation of List ADT Cursor implementation of List ADT Stack ADT - Array and linked list implementations The next two exercises are to be done by implementing the following source files a) b) c) d) Program source files for Stack Application 1 Array implementation of Stack ADT Linked list implementation of Stack ADT Program source files for Stack Application 2

An appropriate header file for the Stack ADT should be #included in (a) and (d) Implement any Stack Application using array implementation of Stack ADT (by implementing files (a) and (b) given above) and then using linked list implementation of Stack ADT (by using files (a) 7 8 9 10 and implementing file (c)) Queue ADT Array and linked list implementations Search Tree ADT - Binary Search Tree Heap Sort Quick Sort

CLASS AND OBJECT IMPLEMENTATION


Ex.No.: 1a Aim To write a C++ programs for basic operations. Date:

Algorithm: 1. 2. 3. 4. 5. 6. 7. Start the program Create a class Declare the variables and function Create an object for class name Calling a function through an object Execute the program Stop

PROGRAM #include<iostream.h> #include<string.h> Class student { Int regno;

Char name[20]; Public: Void setdata(int r, char*n); Void put data() { Cout<<reg.no<<regno; Cout<<Name<<name; } }; Void student::setdata(int r, char *n) { regno=r; strcpy(name,n); } Int main() { Stuident s1,s2; S1.setdata(100,ajay); S2.setdata(101,vijay); S1.putdata(); S2.putdata(); } Output: Regno 100 Name ajay Regno 101 Name vijay

RESULT: Thus the c++ program was executed successfully. INHERITENCE (MULTILEVEL INHERITANCE) Ex.No.: 1b Aim To write a C++ programs for basic operations. Date:

Algorithm: 1. 2. 3. 4. 5. 6. 7. Start the program Create a class Declare the variables and function Create an object for class name Calling a function through an object Execute the program Stop

PROGRAM
#include<iostream.h> Class student{ Protected: int rollno;

Public: void getnumber(int a) { rollno=a; } Void putnumber() { Cout<<rollno; } }; Class test: public student { Protected: float sub1,sub2; Public: void getmarks (float x, float y) { Sub1=x; Sub2=y; } Void putmarks() { Cout<<sub1<<sub2; } }; Class result: public test { Float total; Public: void display () { Total=Sub1+Sub2; Putnumber(); Putmarks(); Cout<<total; }}; Int main(){ result stud1; Sud1.getnumber(100); Sud1.getmarks(85,75); Sud1.diaplay(); }

OUTPUT:
Rollno 100 Sub 185 Sub 275

Total 1160

RESULT: Thus the c++ program was executed successfully.

LIST IMPLEMENTATION USING ARRAY


Ex.No.: 2 Aim: To write a C program to do the list operations. Date:

Algorithm: 1. Initialize the list with n items. 2. Get the choice of operation either insertion or deletion. 3. For insertion, get the item to be inserted and its position. Then position to last position move the items in the list one step forward, then insert the new item in its corresponding position. 4. For deletion get the item to be deleted and find its position then move the items in the list one step backward from last position to position found.

Program: #include<stdio.h> #include<conio.h> #define MAX 20 //maximum no of elements in the list struct {

int list[MAX]; int element; int pos; int length; }l; enum boolean { true, false }; typedef enum boolean boolean; int menu(void); void create(void); void insert(int, int); void delet(int); void display(void); boolean islistfull(void); boolean islistempty(void); void main() { int ch; int element; int pos; l.length = 0; while(1) { ch = menu(); switch (ch) { case 1: l.length = 0; create(); break; case 2: if (islistfull() != true) { printf("\tEnter the New element : "); scanf("%d", &element); printf("\tEnter the Position : "); scanf("%d", &pos); insert(element, pos); }else { printf("\tList if Full. Cannot insert"); printf("\nPress any key to continue..."); getch(); }break; case 3: if (islistempty() != true) { printf("Enter the position of element to be deleted : "); scanf("%d", &pos); delet(pos); }else

{ printf("List is Empty."); printf("\nPress any key to continue..."); getch(); }break; case 4: display(); break; case 5: exit(0); break; default:printf("Invalid Choice"); printf("\nPress any key to continue..."); getch(); } } } //function to display the list of elements int menu() { int ch; clrscr(); printf("\n\t\t********************************************\n"); printf("\t\t******LIST Implementation Using Arrays******\n"); printf("\t\t********************************************\n\n"); printf("\t1. Create\n\t2. Insert\n\t3. Delete\n\t4. Display\n\t5. Exit\n\n\tEnter your choice : "); scanf("%d", &ch); printf("\n\n"); return ch; }//function to create initial set of elements void create(void) { int element; int flag=1; while(flag==1) { printf("Enter an element : "); scanf("%d", &element); l.list[l.length] = element; l.length++; printf("To insert another element press '1' : "); scanf("%d", &flag); } }//function to display the elements in the list void display(void) { int i; for (i=0; i<l.length; i++) printf("Element %d : %d \n", i+1, l.list[i]);

printf("Press any key to continue..."); getch(); }//function to insert the given element at specified position void insert(int element, int pos) { int i; if (pos == 0) { printf("\n\nCannot insert at zeroth position"); getch(); return; }if (pos-1 > l.length) { printf("\n\nOnly %d elements exit. Cannot insert at %d postion", l.length, pos); printf("\nPress any key to continue..."); getch(); }else { for (i=l.length; i>=pos-1; i--) { l.list[i+1] = l.list[i]; }l.list[pos-1] = element; l.length++; } }//function to delete the element at given position void delet(int pos) { int i; if(pos == 0) { printf("\n\nCannot delete at zeroth position"); getch(); return; }if (pos > l.length) { printf("\n\nOnly %d elements exit. Cannot delete", l.length, pos); printf("\nPress any key to continue..."); getch(); return; }for (i=pos-1; i<l.length; i++) { l.list[i] = l.list[i+1]; }l.length--; }//function to find the position of the given element, if exists boolean islistfull(void) { if (l.length == MAX) return true; else return false;

}//function to check whether the list is empty or not boolean islistempty(void) { if (l.length == 0) return true; else return false; }

OUTPUT: 1.Create 2.Insert 3.Delete 4.Count

5.Find 6.Display 7.Exit Enter your choice:3 Enter an element:40 TO insert another element press1:1 Enter an element:20 Enter your choice:2 Enter the new element:50 Enter the position:3 Enter your choice:6 Element 1:50 Element 2:10 Element 3:50 Element 4:30 Enter your choice:3 Enter the position of element to be deleted:6 Element 1:50 Element 2:50 Element 3:30 Enter your choice:7 Exit

RESULT: Thus the c program list operations was executed successfully. I. LINKED LIST IMPLEMENTATION OF LIST ADT- SINGLY LINKED LIST Ex. No.: 3 a AIM: To write a C program to implement the single linked list Date:

ALGORITHM: 8. Start the program 9. Create a menu in main program 10. Get the choice 11. If the choice is one create a new node 12. If choice is two then insert into the node 13. If the choice is three Delete from the node 14. else come out of the menu program 15. Stop

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 number of nodes = \n"); scanf("%d",&n); count=n; while(i<=n) { create(); i++; } printf("\n Enter your option:\n"); printf("1 insert\t\t2 delete\t\t3 display\t\t4 exit\n"); do { scanf("%d",&opt); switch(opt) { case 1: insert(); count++; break; case 2: delet(); count--; if(count==0) { printf("\nlist 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 elements :\n"); scanf("%d",&p->no); p->next=NULL; h=p; } else { t=(list*)malloc(sizeof(list)); printf("\n Enter 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 inserted:\n"); scanf("%d",&p->no); printf("Enter the position to insert :\n"); scanf("&d",&pos); if(pos==1) { h=p; p->next=t; }

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

Enter the element: 30 Enter the element: 40 Enter your option: 1.Insert 2.Delete 3.Display 4.Exit List elements are 10 20 30 40 Enter your option 1 Enter the elements to be inserted 3 Enter your option: 3 List elements are: 10 20 50 30 Enter your option 2 Enter the position to be deleted 3 Enter your option 3 List elements are 10 20 30 40 Enter your option 4

RESULT: Thus the c program singly linked list was executed successfully. LINKED LIST IMPLEMENTATION OF LIST ADT- DOUBLY LINKED LIST Ex.No.: 2 Aim: To write a C++ program for doubly linked list Algorithm: Date:

1. 2. 3. 4. 5. 6. 7. 8.

Start the program Create a menu in main program Get the choice If the choice is one create a new node which has double link If choice is two then insert into the node ,change the appropriate link If the choice is three Delete from the node, remove the link and join it else come out of the menu program Stop

PROGRAM: #include<stdio.h> #include<conio.h> typedef struct s1 { int val; struct s1*next;

struct s1*prev; }node; node*head; node*getnode() { node*temp; temp=(node*)malloc(sizeof(node)); temp->next=NULL; temp->prev=NULL; return temp; } void create() { node*t,*temp; int n,f=0; char ch='y'; while(ch=='Y'||ch=='y') { printf ("\n Enter the Element:"); scanf ("%d",&n); t=getnode(); t->val=n; t->next=NULL; if(f==0) { t->prev=NULL; head=t; f=1; } else {temp=head; while(temp->next) temp=temp->next; t->prev=temp; temp->next=t; } printf("Doyou want to add one more Element(y/n):"); fflush(stdin); scanf("%c",&ch); } } void display() {node*t; int n=0,c=1; while(c!=3) { printf("\n 1.Forward\n 2.In Reverse\n 3.exit"); scanf("%d",&c); switch(c) {

case 1: n=0; printf("\n The Element are:"); t=head; while(t) { n=n+1; printf("\n%d",t->val); t=t->next; } printf("\n Total Number of Elements:%d",n); break; case 2: n=0; printf("\n In Reverse order"); t=head; while(t->next) t=t->next; while(t>0) {n=n+1; printf("\n%d",t->val); t=t->prev; } printf("\n Total Number of Element:%d",n+1); break; } }} void del(int pos) { node *t,*p,*nt; int n=0; t=p=head; n=0; if(pos==0) { p=head->next; p->prev=NULL; head=head->next; free(t); }else { while(n<pos-1) {t=t->next; n++; } p=t->next; t->next=t->next->next; nt=p->next; nt->prev=t; free(p);

} printf("\n Node Deleted"); } void insert(int val, int pos) { int n=0; node*t,*temp,*p; temp=getnode(); temp->val=val; if(pos==0) { temp->next=head; temp->prev=NULL; temp->prev=temp; head=temp; } else { t=head; while(n<pos-1) {t=t->next; n++;} p=t->next; temp->next=t->next; temp->prev=t; t->next=temp; p->prev=temp; } printf("\n Value Inserted"); } /*void search(int pos) { int n=0; node*t; t=head; while(n<pos) { t=t->next; n++; } printf("\n Value in Position %d is:%d",pos,t->val); } */ void main() { int v,p,ch=1; clrscr(); while(ch!=0) { printf("\n1.Create\n2.Display\n3.Insert\n4.Delete\n0.Exit\nEnter your choice:"); scanf("%d",&ch);

switch(ch) { case 1: create(); break; case 2: display(); break; case 3: printf("\n Enter Value to insert and position to insert:"); scanf("%d%d",&v,&p); insert(v,p); break; case 4: printf("\n Enter position to delete:"); scanf("%d",&p); del(p); break; /*case 5: printf("\n Enter Position to find:"); scanf("%d",&p); search(p); break;*/ } } }

OUTPUT: Enter the number of nodes: 4 Enter the elements: 10 Enter the elements: 20 Enter the element:

30 Enter the element: 40 Enter your option: 1.Insert 2.Delete 3.Display 4.Exit List elements are 10 20 30 40 Enter your option 1 Enter the elements to be inserted 3 Enter your option: 3 List elements are: 10 20 50 30 Enter your option 2 Enter the position to be deleted 3 Enter your option 3 List elements are 10 20 30 40 Enter your option 4

RESULT: Thus the c program doubly linked list was executed successfully.

CURSOR IMPLEMENTATION OF LIST ADT Ex. No.: 4 Aim: To write a C++ program to implement the list using cursor. Date:

Algorithm: 1. Start the program 2. Create a menu in main program 3. Get the choice 4. The choice is one create a new 5. The choice is two then insertion. 6. The choice is three delete a element. 7. The choice is four search 8. The choice is five search 9. The choice six exit 10. Stop

PROGRAM: #include<stdio.h> #include<conio.h> #include"curslist.h" void main() {

LIST L=-1; POSITION P; int choice,place,x; clrscr(); printf("\n1.Create\n2.Insert\n3.Delete\n4.MakeEmpty\n5.Display\n6.Find\n7.Exit"); A: printf("\nEnter ur choice:\t"); scanf("%d",&choice); switch(choice) { case 1: if(L==-1) { InitializeCursor(); L=CursorAlloc(); } else printf("\nList is already created"); break; case 2: if(L==-1) printf("\nList is not yet initialized"); else { printf("\nWhere u want to insert?"); scanf("%d",&place); printf("\nEnter the element to insert"); scanf("%d",&x); Insert(x,place); } break; case 3: if(L==-1) printf("\nList is not yet initialized"); else { printf("\nWhich element you want to delete?"); scanf("%d",&x); Delete(x,L); } break; case 4: if(L==-1) printf("\nList is not yet initialized"); else MakeEmpty(L); break; case 5: if(L==-1) printf("\nList is not yet initialized");

else Display(); break; case 6: if(L==-1) printf("\nList is not yet initialized"); else { printf("\nWhich element you want to search?"); scanf("%d",&x); P=Find(x,L); printf("\nThe element is at %d",P); } break; case 7: exit(0); default: printf("\n *******WRONG ENTRY*******"); } goto A; }

OUTPUT 1.Create 2.Insert 3.Delet 4.Make empty

5.Display 6.Find 7.Exit Enter ur choice: 1 Enter ur choice: 2 Where you want to insert ?5 Enter the element to insert 10 Position is not in the list Enter your choice 5 0 0 3 1 -1 -1 2 -1 -1 3 0 -1 4 0 4 5 0 5 6 0 6 7 7 8 8 9 9 Enter your choice:6 Which element you want to search ?6 The element is at -1 Enter ur choice:6 Which elements you want to search?-1 The element is at -1 Enter ur choice:7 Exit

RESULT: Thus the c program cursor linked list was executed successfully.

STACK ADT USING ARRAY IMPLEMENTATION Ex.No.: 5 a Date:

Aim:

To implement stack using arrays Algorithm:


1. 2. 3. 4. Declare an array sizeN. Assign TOP as a pointer to denote the top element in the stack Get the new element Y to be added in to the stack. If TOP is greater than or equal to N then display stack over flow; otherwise set

TOP=TOP+1. 5. Set S [TOP] = Y. 6. To delete top element from the stack check if TOP =0,the display stack underflow, otherwise decrement TOP by one, and display S [TOP+1]. 7. Display the stack S from 1 to TOP.

PROGRAM : #include<iostream.h> #include <conio.h> int main() { clrscr (); int a[20], top=-1, i, ch;

while (1) { cout<<"\n 1.Push.. 2.Pop.. 3.List.. 4. Exit..\n select :"; cin>>ch; switch(ch) { case 1: if(top>=19) cout<<"The stake is full"; else { cout<<"\n Enter the value"; cin>>a[++top]; } break; case 2: if(top<0) cout<<"\n The stake is empty"; else { cout<<"\n The Out element"<< a[top--]; } break; case 3: for(i=0;i<=top;i++) cout<<a[i]<<"\t"; break; case 4: return (0); } getch(); } }

OUTPUT:
1.push..2.pop..3.list..4.exit.. Select:1 Enter the value 20 1.push..2.pop..3.list..4.exit.. Select:1 Enter the value 20

1.push..2.pop..3.list..4.exit.. Select:3 10 20 1.push..2.pop..3.list..4.exit.. Select:2 The output element 20 1.push..2.pop..3.list..4.exit.. Select:3 10 20 Select 4: Exit

RESULT: Thus the c program stack using array was executed successfully.

II. STACK ADT USING LINKED IMPLEMENTATION


Aim: To implement stack using Link Algorithm:

1. 2. 3. 4. 5. 6. 7. 8.

Start the program Create a menu in main program Get the choice If the choice is one Push If choice is two Pop If the choice is three Display list else come out of the menu program Stop

PROGRAM : #include<iostream.h> #include<conio.h> class Node { public : int data; Node *next;

void getdata() { cout<<"Enter the Data"; cin>>data; } void putdata() { cout<<data<<"\t"; } }; int main() { Node *a,*tmp; int ch; a = NULL; while(1) { cout<<"\n1. Push... 2. Pop... 3. Display... 4. Exit... \nSelect... : "; cin>>ch; switch(ch) { case 1: tmp=(Node*)new(Node); tmp->getdata(); tmp->next=a; a= tmp; break; case 2: if(a==NULL) { cout<<" Stack is Empty"; } else { a->putdata(); a=a->next; } break; case 3: cout<<"The Elements are....:"; tmp=a; while(tmp!=NULL) { tmp->putdata(); tmp=tmp->next; } break; case 4: return(1); } getch(); }}

RESULT: Thus the c program stack using linked list was executed successfully. PROGRAM TO CONVERT INFIX EXPRESSION TO POSTFIX EXPRESSION USING STACK Ex. No: 6 Aim: To write a C program for conversion of infix to postfix. Date:

Algorithm: 1. Start the program 2. Enter the equation 3. CONVERT THE infix expressions to postfix using post function 4. print the values of infix and postfix expression 5. Stop the program.

PROGRAM: #include<stdio.h> #include<string.h> #define operand(x) (x>='a' && x<='z' || x>='A' && x<='Z' || x>='0' && x<='9') char infix[30],postfix[30],stack[30]; int top,i=0; /* FUNCTION TO INITIALIZE THE STACK */ void init()

{ top=-1; } void push(char x) { stack[++top]=x; } char pop() { return(stack[top--]); } int isp(char x) { int y; y=(x=='('?0:x=='^'?4:x=='*'?2:x=='/'?2:x=='+'?1:x=='-'?1:x==')'?6:-1); return y; } int icp(char x) { int y; y=(x=='('?4:x=='^'?4:x=='*'?2:x=='/'?2:x=='+'?1:x=='-'?1:x==')'?6:-1); return y; } void infixtopostfix() { int j,l=0; char x,y; stack[++top]='\0'; for (j=0; (x=infix[i++])!='\0'; j--) if (operand(x)) postfix[l++]=x; else if (x==')') while ((y=pop())!='(') postfix[l++]=y; else { while (isp(stack[top])>=icp(x)) postfix[l++]=pop(); push(x); } while (top>=0) postfix[l++]=pop(); } void main() { init(); printf("Enter an infix expression :\n"); scanf("%s",infix); infixtopostfix();

printf("The resulting postfix expression is %s",postfix); }

OUTPUT:
Enter an infix expression : a+b The resulting postfix expression is ab+ Enter an infix expression : a^2+b^2+2ab The resulting postfix expression is a2^b2^+2ab+

RESULT: Thus the c program infix to postfix was executed successfully.

PROGRAM FOR QUEUE IMPLEMENTATION THROUGH ARRAY


Ex.No.: 7 Date:

Aim:
To write a C++ program to do the Queue operations.

Algorithm:
1. Start the Program. 2. Assign top= -1 in the main function. 3. Create a main program. 4. Get the choice.

5. 6. 7. 8. 9.

If the choice 1 is In. If the choice 2 is Out. If the choice 3 is List. If the choice 4 is come out of the main program. Stop

PROGRAM: #include <stdio.h> #include<ctype.h> # define MAXSIZE 200 int q[MAXSIZE]; int front, rear; void main() {

void add(int); int del(); int will=1,i,num; front =0; rear = 0; clrscr(); printf("Program for queue demonstration through array"); while(will ==1) { printf("MAIN MENU: 1.Add element to queue 2.Delete element from the queue"); scanf("%d",&will); switch(will) { case 1: printf("Enter the data... "); scanf("%d",&num); add(num); break; case 2: i=del(); printf("Value returned from delete function is %d ",i); break; default: printf("Invalid Choice ... "); } printf(" Do you want to do more operations on Queue ( 1 for yes, any other key to exit) ); scanf("%d" , &will); } //end of outer while } void add(int a) { if(rear>MAXSIZE) { printf("QUEUE FULL "); return; } else { q[rear]=a; rear++; printf(" Value of rear = %d and the value of front is %d",rear,front); } }

int del() { int a; if(front == rear) { printf("QUEUE EMPTY"); return(0); } else { a=q[front]; front++; } return(a); }

OUTPUT: Program for queue demonstration through array MAIN MENU: 1.Add element to queue 2.Delete element from the queue 1 Enter the data... 20 Value of rear = 1 and the value of front is 20

Do you want to do more operationson Queue ( 1 for yes, any other key to exit) 1 MAIN MENU: 1.Add element to queue 2.Delete element from the queue 1 Enter the data... 30 Value of rear = 2 and the value of front is 30 Do you want to do more operationson Queue ( 1 for yes, any other key to exit) 1 MAIN MENU: 1.Add element to queue 2.Delete element from the queue 2 Value returned from delete function is 20 Do you want to do more operations onQueue ( 1 for yes, any other key to exit)3

RESULT: Thus the c program queue using array was executed successfully.

BINARY SEARCH
Ex. No: 8 Aim: To write a C program for Binary search tree traversing. Date:

Algorithm: 1. Start the program 2. Select the menu choice 3. If the choice is 1 insert a node to binary tree 4. If the choice is 2 the node will be in Pre order traversal 5. If the choice is 3 the node will be in In order traversal 6 If the choice is 4 the node will be in Post order traversal 7. If the choice is 5 it exits the program 8. Stop the program

PROGRAM: #include<conio.h> #include<stdio.h> #include<stdlib.h> struct node { int info;

struct node *lchild; struct node *rchild; }*root; main() { int choice,num; root=NULL; while(1) { printf("\n"); printf("1.Insert\n"); printf("2.Delete\n"); printf("3.Inorder Traversal\n"); printf("4.Preorder Traversal\n"); printf("5.Postorder Traversal\n"); printf("6.Display\n"); printf("7.Quit\n"); printf("Enter your choice : "); scanf("%d",&choice); switch(choice) { case 1: printf("Enter the number to be inserted : "); scanf("%d",&num); insert(num); break; case 2: printf("Enter the number to be deleted : "); scanf("%d",&num); del(num); break; case 3: inorder(root); break; case 4: preorder(root); break; case 5: postorder(root); break; case 6: display(root,1); break; case 7: exit(); default: printf("Wrong choice\n"); }/*End of switch */

}/*End of while */ }/*End of main()*/ find(int item,struct node **par,struct node **loc) { struct node *ptr,*ptrsave; if(root==NULL) /*tree empty*/ { *loc=NULL; *par=NULL; return; } if(item==root->info) /*item is at root*/ { *loc=root; *par=NULL; return; } /*Initialize ptr and ptrsave*/ if(iteminfo) ptr=root->lchild; else ptr=root->rchild; ptrsave=root; while(ptr!=NULL) { if(item==ptr->info) { *loc=ptr; *par=ptrsave; return; } ptrsave=ptr; if(iteminfo) ptr=ptr->lchild; else ptr=ptr->rchild; }/*End of while */ *loc=NULL; /*item not found*/ *par=ptrsave; }/*End of find()*/ insert(int item) { struct node *tmp,*parent,*location; find(item,&parent,&location); if(location!=NULL) { printf("Item already present"); return;

} tmp=(struct node *)malloc(sizeof(struct node)); tmp->info=item; tmp->lchild=NULL; tmp->rchild=NULL; if(parent==NULL) root=tmp; else if(iteminfo) parent->lchild=tmp; else parent->rchild=tmp; }/*End of insert()*/ del(int item) { struct node *parent,*location; if(root==NULL) { printf("Tree empty"); return; } find(item,&parent,&location); if(location==NULL) { printf("Item not present in tree"); return; } if(location->lchild==NULL && location->rchild==NULL) case_a(parent,location); if(location->lchild!=NULL && location->rchild==NULL) case_b(parent,location); if(location->lchild==NULL && location->rchild!=NULL) case_b(parent,location); if(location->lchild!=NULL && location->rchild!=NULL) case_c(parent,location); free(location); }/*End of del()*/ case_a(struct node *par,struct node *loc ) { if(par==NULL) /*item to be deleted is root node*/ root=NULL; else if(loc==par->lchild) par->lchild=NULL;

else par->rchild=NULL; }/*End of case_a()*/ case_b(struct node *par,struct node *loc) { struct node *child; /*Initialize child*/ if(loc->lchild!=NULL) /*item to be deleted has lchild */ child=loc->lchild; else /*item to be deleted has rchild */ child=loc->rchild; if(par==NULL ) /*Item to be deleted is root node*/ root=child; else if( loc==par->lchild) /*item is lchild of its parent*/ par->lchild=child; else /*item is rchild of its parent*/ par->rchild=child; }/*End of case_b()*/ case_c(struct node *par,struct node *loc) { struct node *ptr,*ptrsave,*suc,*parsuc; /*Find inorder successor and its parent*/ ptrsave=loc; ptr=loc->rchild; while(ptr->lchild!=NULL) { ptrsave=ptr; ptr=ptr->lchild; } suc=ptr; parsuc=ptrsave; if(suc->lchild==NULL && suc->rchild==NULL) case_a(parsuc,suc); else case_b(parsuc,suc); if(par==NULL) /*if item to be deleted is root node */ root=suc; else if(loc==par->lchild) par->lchild=suc; else par->rchild=suc;

suc->lchild=loc->lchild; suc->rchild=loc->rchild; }/*End of case_c()*/ preorder(struct node *ptr) { if(root==NULL) { printf("Tree is empty"); return; } if(ptr!=NULL) { printf("%d ",ptr->info); preorder(ptr->lchild); preorder(ptr->rchild); } }/*End of preorder()*/ inorder(struct node *ptr) { if(root==NULL) { printf("Tree is empty"); return; } if(ptr!=NULL) { inorder(ptr->lchild); printf("%d ",ptr->info); inorder(ptr->rchild); } }/*End of inorder()*/ postorder(struct node *ptr) { if(root==NULL) { printf("Tree is empty"); return; } if(ptr!=NULL) { postorder(ptr->lchild); postorder(ptr->rchild); printf("%d ",ptr->info); } }/*End of postorder()*/

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

OUTPUT: 1.Insert 2.Delete 3.Inorder Traversal 4.Preorder Traversal 5.Postorder Traversal 6.Display

7.Quit Enter your choice : 1 Enter the number to be inserted : 10 Enter your choice : 1 Enter the number to be inserted : 20 Enter your choice : 1 Enter the number to be inserted : 30 Enter your choice : 3 30 20 10 Enter your choice : 4 10 20 30 Enter your choice : 5 30 20 10 Enter your choice : 6 10 20 30 Enter your choice : 7

RESULT: Thus the c program binary search was executed successfully.

A PROGRAM TO IMPLEMENT HEAP SORT


Ex. No: 9 Aim : To write a C program for Heap sort. Algorithm: 1. Start the program Date:

2. Construct a min heap, such that the value of the root node should Be less than the left key value & right key value. 3. Use an empty array for storing the sorted elements 4. Delete the root value (minimum element) and store it as a first element Of the array. 5. Delete the last value of the root and store it as a root 6. Reconstruct the min heap 7. Repeat these steps until we get the sorted array and display it. 8. Stop the program.

PROGRAM: #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 : "); scanf("%d",&n); printf(" Enter the elements : "); 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 is it... "); for(i=1;i<=n;i++) printf("%4d",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; }

OUTPUT:
Enter the number of elements to sort : 10 Enter the elements :15 11 17 18 19 10 16

15 13 12 Here is it... 10 11 15 17 12 15 13 16 18 19

RESULT: Thus the c program heap sort was executed successfully.

Quick sort [array]


Ex. No: 10 Aim : To write a C++ program for Quick sort. Algorithm: 1. Start the program Date:

2. Read the number of elements to be sorted 3. Initialize a pivot (center) , left and right positions 4. Check whether the center element is less than the left element. Then swap left and center values 5. Check whether the right element is less than the left element. Then swap right and left values 6. Check whether the right element is less than the center element. Then swap center and right 7. Finally the element in the left of pivot will be less than the pivot Element and the element to the right of the pivot will be greater Than the pivot element . 8. Repeat the steps until the given elements are arranged in a sorted Manner 9. Stop the program.

PROGRAM: #include <stdio.h> #define MAXARRAY 10 void quicksort(int arr[], int low, int high); int main(void) { int array[MAXARRAY] = {0}; int i = 0; /* load some random values into the array */ for(i = 0; i < MAXARRAY; i++) array[i] = rand() % 100;

/* print the original array */ printf("Before quicksort: "); for(i = 0; i < MAXARRAY; i++) { printf(" %d ", array[i]); } printf("\n"); quicksort(array, 0, (MAXARRAY - 1)); /* print the `quicksorted' array */ printf("After quicksort: "); for(i = 0; i < MAXARRAY; i++) { printf(" %d ", array[i]); } printf("\n"); return 0; } /* sort everything inbetween `low' <-> `high' */ void quicksort(int arr[], int low, int high) { int i = low; int j = high; int y = 0; /* compare value */ int z = arr[(low + high) / 2]; /* partition */ do { /* find member above ... */ while(arr[i] < z) i++; /* find element below ... */ while(arr[j] > z) j--; if(i <= j) { /* swap two elements */ y = arr[i]; arr[i] = arr[j]; arr[j] = y; i++; j--; } } while(i <= j); /* recurse */ if(low < j) quicksort(arr, low, j); if(i < high) quicksort(arr, i, high); } #include #include /*global declaration*/ int a[20],n; /*main function*/ void main()

{ int i; void qsort(int,int); clrscr(); printf("Enter the array size"); scanf("%d",&n); printf("\nEnter the elements to be sorted\n"); for(i=0;i scanf("%d",&a[i]); qsort(0,n-1); printf("The sorted elements are\n"); for(i=0;i printf("%d\t",a[i]); getch(); } /*quick sort function*/ void qsort(int left,int right) { int i,j,pivot,temp,k; if(left { i=left+1; j=right; pivot=left; for(;;) { while(a[pivot]>a[i]) i=i+1; while(a[pivot] j=j-1; if(i { temp=a[i]; a[i]=a[j]; a[j]=temp; for(k=0;k printf("%d\t",a[k]); printf("\n"); } else break; } temp=a[pivot]; a[pivot]=a[j]; a[j]=temp; for(k=0;k printf("%d\t",a[k]); printf("\n"); qsort(left,j-1); qsort(j+1,right); } return; }/*End of program*/

OUTPUT:
Enter the array size5 Enter the elements to be sorted 10 25 20 4 5

10 5 20 4 25 10 5 4 20 25 4 5 10 20 25 4 5 10 20 25 4 5 10 20 25 The sorted elements are 4 5 10 20 25

RESULT: Thus the c program heap sort was executed successfully.

Das könnte Ihnen auch gefallen