3rd sem ece ds&oops

73
J.K.K.MUNIRAJAH COLLEGE OF TECHNOLOGY,T.N.PALAYAM-638506 DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING. EC 2209 - DATA STRUCTURES AND OBJECT ORIENTED PROGRAMMING LAB MANUAL YEAR: II SEM:III

Transcript of 3rd sem ece ds&oops

Page 1: 3rd sem ece ds&oops

J.K.K.MUNIRAJAH COLLEGE OF TECHNOLOGY,T.N.PALAYAM-638506

DEPARTMENT OF ELECTRONICS AND COMMUNICATION

ENGINEERING.

EC 2209 - DATA STRUCTURES AND OBJECT ORIENTED PROGRAMMING

LAB MANUAL

YEAR: II SEM:III

Page 2: 3rd sem ece ds&oops

LIST OF EXPERIMENTS

EXPNO

NAME OF THE EXPERIMENT

1 Basic Programs for C++ Concepts

2 Array implementation of List Abstract Data Type (ADT)

3 Linked list implementation of List ADT

4 Cursor implementation of List ADT

5 Stack ADT - Array and linked list implementations

6 The next two exercises are to be done by implementing the

following source files

a) Program source files for Stack Application 1

b) Array implementation of Stack ADT

c) Linked list implementation of Stack ADT

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

and implementing file (c))

7 Queue ADT – Array and linked list implementations

8 Search Tree ADT - Binary Search Tree

9 Heap Sort

10 Quick Sort

Page 3: 3rd sem ece ds&oops

CLASS AND OBJECT IMPLEMENTATION

Ex.No.: 1a Date:

Aim To write a C++ programs for basic operations.

Algorithm:

1. Start the program2. Create a class3. Declare the variables and function4. Create an object for class name5. Calling a function through an object6. Execute the program7. Stop

Page 4: 3rd sem ece ds&oops

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 100Name ajayRegno 101Name vijay

RESULT:

Page 5: 3rd sem ece ds&oops

Thus the c++ program was executed successfully.INHERITENCE (MULTILEVEL INHERITANCE)

Ex.No.: 1b Date:

Aim To write a C++ programs for basic operations.

Algorithm:

1. Start the program2. Create a class3. Declare the variables and function4. Create an object for class name5. Calling a function through an object6. Execute the program7. Stop

Page 6: 3rd sem ece ds&oops

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

Page 7: 3rd sem ece ds&oops

OUTPUT:

Rollno 100Sub 185Sub 275Total 1160

RESULT:

Thus the c++ program was executed successfully.

Page 8: 3rd sem ece ds&oops

LIST IMPLEMENTATION USING ARRAY

Ex.No.: 2 Date:

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

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.

Page 9: 3rd sem ece ds&oops

Program:

#include<stdio.h>#include<conio.h>#define MAX 20 //maximum no of elements in the liststruct{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();

Page 10: 3rd sem ece ds&oops

}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 elementsint 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 elementsvoid 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' : ");

Page 11: 3rd sem ece ds&oops

scanf("%d", &flag);}}//function to display the elements in the listvoid 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 positionvoid 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 positionvoid 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];

Page 12: 3rd sem ece ds&oops

}l.length--;}//function to find the position of the given element, if existsboolean islistfull(void){if (l.length == MAX)return true;elsereturn false;}//function to check whether the list is empty or notboolean islistempty(void){if (l.length == 0)return true;elsereturn false;}

Page 13: 3rd sem ece ds&oops

OUTPUT:

1.Create2.Insert3.Delete4.Count5.Find6.Display7.ExitEnter your choice:3Enter an element:40TO insert another element press’1’:1Enter an element:20Enter your choice:2Enter the new element:50Enter the position:3Enter your choice:6Element 1:50Element 2:10Element 3:50Element 4:30Enter your choice:3Enter the position of element to be deleted:6Element 1:50Element 2:50Element 3:30Enter your choice:7Exit

RESULT:

Thus the c program list operations was executed successfully.

Page 14: 3rd sem ece ds&oops

I. LINKED LIST IMPLEMENTATION OF LIST ADT- SINGLY LINKED LIST

Ex. No.: 3 a Date:

AIM:To write a C program to implement the single linked list

ALGORITHM:

8. Start the program9. Create a menu in main program10. Get the choice11. If the choice is one create a new node12. If choice is two then insert into the node13. If the choice is three Delete from the node14. else come out of the menu program15. Stop

Page 15: 3rd sem ece ds&oops

PROGRAM :

#include<stdio.h>#include<conio.h>#include<stdlib.h>#define NULL 0typedef struct list{int no;struct list*next;}list;list *p,*t,*h,*y,*ptr,*pt;void create(void);void insert(void);void delet(void);void display(void);int j,pos,k=1,count;void main(){int n,i=1,opt;clrscr();p=NULL;//printf("%d",sizeof(LIST));printf("Enter the 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:

Page 16: 3rd sem ece ds&oops

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

Page 17: 3rd sem ece ds&oops

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

Page 18: 3rd sem ece ds&oops

OUTPUT:

Enter the number of nodes:4Enter the elements:10Enter the elements:20Enter the element:30Enter the element:40Enter your option:1.Insert2.Delete3.Display4.ExitList elements are 10 20 30 40Enter your option1Enter the elements to be inserted3Enter your option:3List elements are:10 20 50 30Enter your option2Enter the position to be deleted3Enter your option3List elements are10 20 30 40Enter your option4

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

Page 19: 3rd sem ece ds&oops

II. LINKED LIST IMPLEMENTATION OF LIST ADT- DOUBLY LINKED LIST

Ex.No.: 2 Date:

Aim:To write a C++ program for doubly linked list

Algorithm:1. Start the program2. Create a menu in main program3. Get the choice4. If the choice is one create a new node which has double link5. If choice is two then insert into the node ,change the appropriate link6. If the choice is three Delete from the node, remove the link and join it7. else come out of the menu program8. Stop

Page 20: 3rd sem ece ds&oops

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

Page 21: 3rd sem ece ds&oops

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{

Page 22: 3rd sem ece ds&oops

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

Page 23: 3rd sem ece ds&oops

} */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;*/}}}

Page 24: 3rd sem ece ds&oops

OUTPUT:

Enter the number of nodes:4Enter the elements:10Enter the elements:20Enter the element:30Enter the element:40Enter your option:1.Insert2.Delete3.Display4.ExitList elements are 10 20 30 40Enter your option1Enter the elements to be inserted3Enter your option:3List elements are:10 20 50 30Enter your option2Enter the position to be deleted3Enter your option3List elements are10 20 30 40Enter your option4

RESULT:

Thus the c program doubly linked list was executed successfully.

Page 25: 3rd sem ece ds&oops

CURSOR IMPLEMENTATION OF LIST ADT

Ex. No.: 4 Date:

Aim: To write a C++ program to implement the list using cursor.

Algorithm:

1. Start the program2. Create a menu in main program3. Get the choice4. 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 exit10. Stop

Page 26: 3rd sem ece ds&oops

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

Page 27: 3rd sem ece ds&oops

case 4:if(L==-1)printf("\nList is not yet initialized");elseMakeEmpty(L);break;case 5:if(L==-1)printf("\nList is not yet initialized");elseDisplay();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;}

Page 28: 3rd sem ece ds&oops

OUTPUT

1.Create2.Insert3.Delet4.Make empty5.Display6.Find7.Exit

Enter ur choice:1Enter ur choice:2Where you want to insert ?5Enter the element to insert 10Position is not in the listEnter your choice 50 0 3 1 -1 -12 -1 -13 0 -14 0 45 0 56 0 67 78 89 9

Enter your choice:6Which element you want to search ?6The element is at -1Enter ur choice:6Which elements you want to search?-1The element is at -1Enter ur choice:7Exit

RESULT:

Thus the c program cursor linked list was executed successfully.

Page 29: 3rd sem ece ds&oops

STACK ADT USING ARRAY IMPLEMENTATION

Ex.No.: 5 a Date:

Aim:

To implement stack using arrays

Algorithm:

1. Declare an array sizeN.2. Assign TOP as a pointer to denote the top element in the stack3. Get the new element Y to be added in to the stack.4. 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.

Page 30: 3rd sem ece ds&oops

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

}}

Page 31: 3rd sem ece ds&oops

OUTPUT:

1.push..2.pop..3.list..4.exit..Select:1Enter the value 201.push..2.pop..3.list..4.exit..Select:1Enter the value 201.push..2.pop..3.list..4.exit..Select:310 201.push..2.pop..3.list..4.exit..Select:2The output element 201.push..2.pop..3.list..4.exit..Select:310 20Select 4:Exit

RESULT:

Thus the c program stack using array was executed successfully.

Page 32: 3rd sem ece ds&oops

II. STACK ADT USING LINKED IMPLEMENTATION

Aim: To implement stack using Link

Algorithm:

1. Start the program2. Create a menu in main program3. Get the choice4. If the choice is one Push5. If choice is two Pop6. If the choice is three Display list 7. else come out of the menu program8. Stop

Page 33: 3rd sem ece ds&oops

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

Page 34: 3rd sem ece ds&oops

RESULT:

Thus the c program stack using linked list was executed successfully.

Page 35: 3rd sem ece ds&oops

PROGRAM TO CONVERT INFIX EXPRESSION TO POSTFIX EXPRESSION USING STACK

Ex. No: 6 Date:

Aim:To write a C program for conversion of infix to postfix.

Algorithm:

1. Start the program 2. Enter the equation 3. CONVERT THE infix expressions to postfix using post function4. print the values of infix and postfix expression5. Stop the program.

Page 36: 3rd sem ece ds&oops

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;

elseif (x==')')

while ((y=pop())!='(')postfix[l++]=y;

else{

while (isp(stack[top])>=icp(x))postfix[l++]=pop();

push(x);}

Page 37: 3rd sem ece ds&oops

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

Page 38: 3rd sem ece ds&oops

OUTPUT:

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

RESULT:

Thus the c program infix to postfix was executed successfully.

Page 39: 3rd sem ece ds&oops

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. If the choice 1 is In.6. If the choice 2 is Out.7. If the choice 3 is List.8. If the choice 4 is come out of the main program.9. Stop

Page 40: 3rd sem ece ds&oops

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

");

Page 41: 3rd sem ece ds&oops

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

}

Page 42: 3rd sem ece ds&oops

OUTPUT:

Program for queue demonstration through array MAIN MENU: 1.Add element to queue 2.Delete element from the queue1Enter the data... 20 Value of rear = 1 and the value of front is 20Do you want to do more operationson Queue ( 1 for yes, any other key to exit) 1MAIN MENU: 1.Add element to queue 2.Delete element from the queue1Enter the data... 30 Value of rear = 2 and the value of front is 30Do you want to do more operationson Queue ( 1 for yes, any other key to exit) 1MAIN MENU: 1.Add element to queue 2.Delete element from the queue2Value 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.

Page 43: 3rd sem ece ds&oops

BINARY SEARCH

Ex. No: 8 Date:

Aim:

To write a C program for Binary search tree traversing.

Algorithm:

1. Start the program 2. Select the menu choice3. If the choice is 1 insert a node to binary tree4. If the choice is 2 the node will be in Pre order traversal5. If the choice is 3 the node will be in In order traversal6 If the choice is 4 the node will be in Post order traversal7. If the choice is 5 it exits the program8. Stop the program

Page 44: 3rd sem ece ds&oops

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:

Page 45: 3rd sem ece ds&oops

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;elseptr=root->rchild;ptrsave=root;

while(ptr!=NULL){if(item==ptr->info){ *loc=ptr;*par=ptrsave;return;}ptrsave=ptr;if(iteminfo)ptr=ptr->lchild;elseptr=ptr->rchild;}/*End of while */*loc=NULL; /*item not found*/

Page 46: 3rd sem ece ds&oops

*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;elseif(iteminfo)parent->lchild=tmp;elseparent->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);

Page 47: 3rd sem ece ds&oops

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;elseif(loc==par->lchild)par->lchild=NULL;elsepar->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;elseif( 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);

Page 48: 3rd sem ece ds&oops

elsecase_b(parsuc,suc);

if(par==NULL) /*if item to be deleted is root node */root=suc;elseif(loc==par->lchild)par->lchild=suc;elsepar->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");

Page 49: 3rd sem ece ds&oops

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

Page 50: 3rd sem ece ds&oops

OUTPUT:

1.Insert2.Delete3.Inorder Traversal4.Preorder Traversal5.Postorder Traversal6.Display7.QuitEnter your choice : 1Enter the number to be inserted : 10

Enter your choice : 1Enter the number to be inserted : 20

Enter your choice : 1Enter the number to be inserted : 30

Enter your choice : 330 20 10Enter your choice : 410 20 30Enter your choice : 530 20 10

Enter your choice : 6

10 20 30Enter your choice : 7

RESULT:

Thus the c program binary search was executed successfully.

Page 51: 3rd sem ece ds&oops

A PROGRAM TO IMPLEMENT HEAP SORT

Ex. No: 9 Date:

Aim :

To write a C program for Heap sort.

Algorithm:

1. Start the program 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 elements4. 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 root6. Reconstruct the min heap7. Repeat these steps until we get the sorted array and display it.8. Stop the program.

Page 52: 3rd sem ece ds&oops

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

Page 53: 3rd sem ece ds&oops

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

Page 54: 3rd sem ece ds&oops

OUTPUT:

Enter the number of elements to sort : 10Enter the elements :15111718191016151312Here is it... 10 11 15 17 12 15 13 16 18 19

RESULT:

Thus the c program heap sort was executed successfully.

Page 55: 3rd sem ece ds&oops

Quick sort [array]

Ex. No: 10 Date:

Aim : To write a C++ program for Quick sort.

Algorithm:

1. Start the program 2. Read the number of elements to be sorted3. Initialize a pivot (center) , left and right positions4. Check whether the center element is less than the left element. Then swap

left and center values5. Check whether the right element is less than the left element. Then swap

right and left values6. Check whether the right element is less than the center element. Then swap

center and right7. 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 Manner9. Stop the program.

Page 56: 3rd sem ece ds&oops

PROGRAM:

#include <stdio.h>#define MAXARRAY 10void 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);

Page 57: 3rd sem ece ds&oops

/* 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");}elsebreak;}temp=a[pivot];a[pivot]=a[j];

Page 58: 3rd sem ece ds&oops

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

Page 59: 3rd sem ece ds&oops

OUTPUT:

Enter the array size5

Enter the elements to be sorted10252045

10 5 20 4 2510 5 4 20 254 5 10 20 254 5 10 20 254 5 10 20 25The sorted elements are4 5 10 20 25

RESULT:

Thus the c program heap sort was executed successfully.