Vous êtes sur la page 1sur 57

MCA 26 Data structure Lab Manual page 2 of 2

Data Structures
Definition:
Data structure is a representation of logical relationship existing between individual
elements of data.
Or
A data structure is a way of organizing all the data items that considers not only the
elements stored but also their relationship to each other.

Complete Classification of Data Structures

Data structures

Non-Primitive
Primitive Data Data Structures
Structures

int float char Pointer Arrays Lists Files


s

Linear Lists Non-Linear


Lists

Stacks Trees

Queues
Graphs

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

1 /* Write a program to create a sequential file with at least five records each record
having the structure shown below
USN Name Marks1 Marks2 Marks3
Non-Zero 25 characters Positive Positive Positive
positive integer integer integer
integer
Write necessary functions 1.To display all the records in the file. 2. To search for a
specific record based on USN in case the required record is not found suitable
message should be displayed both the options in this case must be demonstrated. */

#include<stdio.h>
struct file
{
int usn;
char name[25];
int m[3];
};
typedef struct file S;
main()
{
int ch;
while(1)
{
clrscr();
printf(" 1 Create\n 2 Display\n 3 Search\n 4 Exit\n");
printf("Enter your choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1: create(); break;
case 2: display(); break;
case 3: search(); break;
case 4: exit(0);
}
getch();
}
}

/* ************************End of main() ****************/

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

create()
{
FILE *fp;
int i,j,n;
S s[10];
fp=fopen("stud.c","w");
if(fp==NULL)
printf("Error..............\n");
else
{
printf("Enter the number of records\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the %d student record\n",i+1);
scanf("%d%s",&s[i].usn,s[i].name);
printf("Enter the 3 marks\n");
for(j=0;j<3;j++)
scanf("%d",&s[i].m[j]);
}
}
for(i=0;i<n;i++)
{
fprintf(fp,"\t%d\t%s\t\t",s[i].usn,s[i].name);
for(j=0;j<3;j++)
fprintf(fp,"%d\t",s[i].m[j]);
fprintf(fp,"%c",'\n');
}
fclose(fp);
}
/*********************Create function***************************/
display()
{
FILE *fp;
char ch;
fp=fopen("stud.c","r");
printf("The Contents of The file is\n");
printf("\tUSN\t NAME\t\tM1\tM2\tM3\n");
printf("______________________________________________\n");
while((ch=getc(fp))!=EOF)

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

{
printf("%c",ch);
}
printf("\n\n__________________________________________\n");
printf("End OF File..............\n");
fclose(fp);
}
/**********************display function()**************************/
search()
{
FILE *fp;
char name[25];
int id,un;
int m1,m2,m3;
fp=fopen("stud.c","r");
if(fp==NULL)
printf("Error......................\n");
else
{
printf("Enter the University number of stud\n");
scanf("%d",&id);
for(;;)
{
fscanf(fp,"%d%s%d%d%d",&un,name,&m1,&m2,&m3);
if(feof(fp))
{ printf("Sorry NOT FOund\n");
break;
}
if(un==id)
{ printf("RECORD is Found\n");
printf("\tUSN is %d\n\tNAME is
%s\n\tM1=%d\n\tM2=%d\n\tM3=%d\n\t",un,name,m1,m2,m3);
return;
}
}
}
fclose(fp);
}
/*** End of search()***********/
/*************************End of program **************/

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

/* 2. Write a C program to construct a stack of integers and to perform the following


options on it PUSH 2.POP 3. DISPLAY
The program should print appropriate messages for stack overflow, stack underflow
and stack empty.*/
#include<stdio.h>
#include<conio.h>
#define MAX 5
int stack[MAX];
int top=0;
void main()
{
int ch;
while(1)
{ clrscr();
printf("1 PUSH\n2 POP\n3 DISPLAY\n4 EXIT\n");
printf("Enter Your choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1: push(); break;
case 2: pop(); break;
case 3: display(); break;
case 4: exit(0);
default: printf("Invalid choice\n");
}
getch();
}
}
/* ****** ** End of main function ******** */
push()
{
if(top==MAX)
printf("Stack Overflow\n");
else
{
printf("Enter the element to be Push\n");
scanf("%d",&stack[top++]);
printf("Operation Success\n");
}
} /* End of push() ***** ** */

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

pop()
{
if(top==0)
printf("Stack Under flow\n");
else
printf("The Poped element is %d\n",stack[--top]);

/* *** End pop() **** */

display()
{ int i;
if(top==0)
printf("Stack Empty\n");
else
{
printf("The Elements in Stack are\n");
for(i=top-1;i>=0;i--)
printf("%d\n",stack[i]);
}
}
/* End of Display() ****** */

/* End of Program *** */

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

3 /* Write a C program to convert and print a given valid parenthesized Infix arithmetic

expressions to postfix expressions. The expression consists of single character

operands and binary operators + (plus) - (minus) *(multiplication) / (divide). */

Algorithm to Convert Infix to Postfix Expression;

Step1: Scan Infix Expression from left to right

Step2: a) If the scanned symbol is left parentheses, push it into the stack.

b) If the scanned symbol is right parentheses, then go on popping all the items

from the stack and place them in the postfix expression till we get the

matching left parentheses.

c) If the scanned symbol is an operand, then place directly in the postfix

expression.

d) If the scanned symbol is an operator, then go on removing all the operators

from the

stack and place them in the postfix expression, as long as precedence of the

operator, which is on the top of the stack, is greater than or equal to the

precedence of the scanned symbol, otherwise push the scanned symbol onto

the stack.

Step3: Repeat the above steps as long as symbols present in infix expression.

/* Program: to convert Infix to Postfix */

#include<stdio.h>
#include<string.h>
char infix[20],pfix[20],stack[20];
int pos,i,len,top=-1;
void main()
{
clrscr();
printf("Enter the valid infix expression\n");
scanf("%s",infix);

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

convert();
printf("The postfix Expression is :%s",pfix);
getch();
}
/* End of main function */

convert()
{
char temp,sym;
len=strlen(infix);
push('#');
while(i<len)
{
sym=infix[i];
switch(sym)
{
case '(': push(sym); break;
case ')': temp=pop();
while(temp!='(')
{ pfix[pos++]=temp;
temp=pop();
}
break;
case '+':
case '-':
case '*':
case '/':
case '^': while(preced( stack[top])>=preced(sym))
{
temp=pop();
pfix[pos++]=temp;
}
push(sym);//condition fails push symbol into stack
break;
default: pfix[pos++]=sym;
}

i++;
}

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

//any items left in the stack pop and add them to postfix expression
while(top>0)
{
pfix[pos++]=pop();
}

/* End of convert function */

preced(char c)
{
int p;
switch(c)
{ case '^': p=3; break;
case '/':
case '*': p=2; break;
case '+':
case '-': p=1; break;
case '(':
case ')': p=0; break;
case '#': p=-1; break;
}
return p;
}
/* End of precedence function it returns precedence of operators*/
push(char c)
{
stack [++top]=c;
}
/* End of Push */

pop()
{
char r;
r=stack [top--];
return r;
}

/* End of POP */

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

4. /* Write a C program to Evaluate Valid Suffix/postfix expressions using stack.


Assume that the suffix /postfix expression is read as a single line consisting of non-
negative single digit operands and binary arithmetic operators. The arithmetic
operators are + (add),-(minus),*(multiply) and / (divide).*/

Algorithm to Evaluate Postfix Expression

Step1: Scan the given Postfix Expression from left to right.

Step2: Store the Numeric values corresponding to each operand, in an array.

Step3: a) If the scanned symbol is an operand, then push its value onto the stack.

b) If the scanned symbol is an operator, then pop out two values from the stack

and store

them in some variable viz op1 and op2.

Step 4: Depending on the operator perform the required arithmetic operation

If the operator is +

Case +: result=op1+op2;

Case -: result=op1-op2;

Case *: result=op1*op2;

Case /: result= op1/op2;

Step5: push the result onto the stack

Step6: Repeat the above steps as long as symbols present in the Postfix Expression

program to Evaluate Valid Suffix/postfix expressions

#include<stdio.h>
char pfix[20];
int stack[20],top=0;
int value[20];
void main()
{
int i=0,r;
clrscr();

printf("Enter the valid suffix expression\n");

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

scanf("%s",pfix);

while(pfix[i]!='\0')
{
if(isalpha(pfix[i])) //isalpha() checks of the charcter
{
printf("Enter the value of %c\n",pfix[i]);
scanf("%d",&value[i]);
}
i++;
}

// after storing values in value[] array we call the evaluate function


r=evaluvate();

printf("The result is :%d\n",r);

getch();
}

/* End of main() function */

evaluvate()
{
int i=0;
int p1,p2,t;
char c;
while(pfix[i]!='\0')
{
c=pfix[i];
if(isalpha(c))
push(value[i]);
else
{
p2=pop();
p1=pop();

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

switch(c)
{
case '+': push(p1+p2);break;
case '-': push(p1-p2); break;
case '/': push(p1/p2); break;
case '*': push(p1*p2); break;
case '^': push(pow(p1,p2)); break;
}
}
i++;
}
t=pop();
return t;
}
/* End of Evaluate Function */

push(int n)
{
stack[++top]=n;

/* End of Push function */


pop()
{
int n;
n=stack[top--];
return n;
}

/* end of POP function */

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

5 /* Write a program to simulate the working of a queue of integers using an array.


Provide the following operations.
1. Insert
2. delete
3. display */

#include<stdio.h>
#include<conio.h>
#define MAX 5
int queue[MAX];
int r=0,f=0;
void main()
{
int ch;
while(1)
{ clrscr();
printf("1 Insert\n2 Delete\n3 Display\n4 Exit\n");
printf("Enter Your choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1: insert(); break;
case 2: del(); break;
case 3: display(); break;
case 4: exit(0);
default: printf("Invalid choice\n");
}
getch();
}
}
/* ****** ** End of main function ******** */

insert()
{
if(r==MAX)
printf("Queue Overflow\n");
else
{
printf("Enter the element to be Insert\n");

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

scanf("%d",&queue[r++]);
printf("Operation Success\n");
}
}

/* End of insert() ***** ** */

del()
{
if(r==f)
printf("Queue Under flow\n");
else
printf("The Deleted element is %d\n",queue[f++]);

}
/* *** End del() **** */

display()
{

int i;
if(r==f)
printf("Queue Empty\n");
else
{
printf("The Elements in Queue are\n");
for(i=f;i<r;i++)
printf("%d\n",queue[i]);
}
}

/* End of Display() ****** */

/* End of Program *** */

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

6 /* Write a C program to simulate the working of a circular queue of integers


using an array. Provide the following operations
1. Insert
2. Delete
3. Display*/

#include<stdio.h>
#define SIZE 5
int queue[SIZE];
void insert(),deletee(),display();
main()
{ int f=0,r=-1,s=0,n;
int ch;
while(1)
{ clrscr();
printf("MENU\n 1 INSERT\n 2 DELETE\n 3 DISPLAY\n 4 EXIT\n");
printf("Enter your choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("Enter the element\n");
scanf("%d",&n);
insert(n,&r,&s); break;
case 2: deletee(&f,&s); break;
case 3: display(f,s); break;
case 4: exit(0); break;
default: printf("Invalid choice\n");
}
getch();
}
}

/* *****************End o f main function ********** */

void insert(int n,int *r,int *s)


{
if(*s==SIZE)
printf("Queue is full\n");
else
{ *r=*r%SIZE+1;

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

queue[*r]=n;
*s=*s+1;
printf("Insert success\n");
}
}
/* End of Insert() */

void delete(int *f,int *s)


{
if(*s==0)
printf("Queue Empty\n");
else
{
printf("The deleted element is %d\n",queue[*f]);
*f=*f%SIZE+1;
*s=*s-1;
}
}

/* ****** End of Deletee() ****** */

void display(int f,int s)


{ int i,k;
if(s==0)
printf("Queue Empty\n");
else
{
printf("Elements of CQ are\n");
k=f;
for(i=0;i<s;i++)
{
printf("%d\t",queue[k]);
k=(k%SIZE)+1;
}

}
}

/* **************** End of Display() ******** */

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

7 /* Write a program to design a priority queue which is maintained as a set of queues


(maximum of three queues). The elements are inserted based upon the given priority;
the deletion of an element is to be done starting from the 1st queue, if it is not empty.
If it is empty from the 2nd queue will be deleted and so on.*/
#include<stdio.h>
#define SIZE 5
int q1[SIZE],q2[SIZE],q3[SIZE];
void main()
{ int f1=0,f2=0,f3=0,r1=0,r2=0,r3=0;
int ch,p,n;
while(1)
{ clrscr();
printf("MENU\n 1 INSERT\n 2 DELETE\n 3 DISPLAY\n 4 EXIT\n");
printf("Enter your choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("Enter priority and element to be inserted\n");
scanf("%d%d",&p,&n);
switch(p)
{
case 1: if(r1==SIZE)
printf("Q1 is full\n");
else
{
insert(q1,n,r1);
r1++;
}
break;
case 2: if(r2==SIZE)
printf("Q2 is full");
else
{
insert(q2,n,r2);
r2++;
}
break;
case 3: if(r3==SIZE)
printf("Q3 is full\n");
else

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

{
insert(q3,n,r3);
r3++;
}
break;
default: printf("Invalid priority element discarded re-enter\n");
}
break;
case 2: if(f1==r1)
{ printf("Q1 is empty\n");
if(f2==r2)
{ printf("Q2 is empty\n");
if(f3==r3)
printf("Q3 is Empty\n");
else
{ printf(" The deleted element is
d\n",deletee(q3,f3));
f3++;
} }
else
{
printf("The deleted element is
\n",deletee(q2,f2));
f2++;
} }
else
{
printf("The deleted element is %d\n",deletee(q1,f1));
f1++;
}
break;
case 3: if(r1==f1)
printf("Q1 is empty\n");
else
{ printf("Elements in Q1 are \n");
display(q1,f1,r1);
}
if(r2==f2)
printf("Q2 is empty\n");
else

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

{ printf("Elements in Q2 are \n");


display(q2,f2,r2);
}
if(r3==f3)
printf("Q3 is empty\n");
else
{ printf("Elements in Q3 are \n");
display(q3,f3,r3);
}
break;
case 4: exit(0); break;
default: printf("Invalid choice\n");
}
getch();
}
} /* *********** End of main Function *********** */

insert(int q[],int m,int r)


{
q[r++]= m;
}
/* *********** End of Insert() *********** */
deletee(int q[],int f)
{
return (q[f++]);

}
/* ************ End of Deletee() function ********** */

display(int q[],int f,int r)


{ int i;
for(i=f;i<r;i++)
printf("|%d|\t",q[i]);

printf("\n");

/* ************* End Of display () ********* */

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

OR
#include<stdio.h>
#include<conio.h>
#define MAX 5
struct pq
{
int queue[MAX];
int f,r;
}Q[3];
void main()
{
int ch,i;
for(i=0;i<3;i++)
{
Q[i].f=0;
Q[i].r=0;
}
while(1)
{ clrscr();
printf("1 Insert\n2 Delete\n3 Display\n4 Exit\n");
printf("Enter Your choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1: insert(); break;
case 2: del(); break;
case 3: display(); break;
case 4: exit(0);
default: printf("Invalid choice\n");
}
getch();
}
}
/* ****** ** End of main function ******** */

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

insert()
{
int qn,n;
printf("Enter the Q number and Element to be insert\n");
scanf("%d%d",&qn,&n);
if(Q[qn-1].r==MAX)
printf(" %d Queue Overflow\n",qn);
else
{
Q[qn-1].queue[Q[qn-1].r++]=n;
printf("Operation success\n");
}
}

/* End of Insert() ***** ** */

del()
{ if(Q[0].f==Q[0].r)
{
printf("%d Queue Underflow\n",1);
if(Q[1].f==Q[1].r)
{
printf("%d Queue Underflow\n",2);
if(Q[2].f==Q[2].r)
printf("%d Queue Underflow\n",3);
else
printf("The Deleted item is %d\n",Q[2].queue[Q[2].f++]);
}
else
printf("The Deleted item is %d\n",Q[1].queue[Q[1].f++]);
}
else
printf("The Deleted item is %d\n",Q[0].queue[Q[0].f++]);
}

/* *** End pop() **** */

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

display()
{ int i,j;
for(i=0;i<3;i++)
{
if(Q[i].f==Q[i].r)
printf(" Queue%d Empty\n",i+1);
else
{
printf("The elements In %d Queue are\n",i+1);
for( j=Q[i].f;j<Q[i].r;j++)
printf("%d\t",Q[i].queue[j]);
}
printf("\n");
}
}
/* End of Display() ****** */

/* End of Program *** */

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

8 /*Write a C program using dynamic variables and pointers, to construct a singly


linked list consisting of the followings information in each node, student id (integer),
student name (character string) and semester (integer).The operations to be supported
are.
a. The insertion operation
1. at the front of the list
2. at the back of the list
3. at any position in the list
b. Deleting a node based on student id.
If the specified node is not present in the list an error message should be displayed.
Both the options should be demonstrated.
c. Searching a node based on student id and updates the information content. If the
specified node is not present in the list an error message should be displayed. Both
situations should be displayed.
d. Displaying all the nodes in the list. */
#include<stdio.h>
#include<string.h>
#define NULL 0
struct stud
{
int rno;
char name[12];
int sem;
struct stud *next;
};
typedef struct stud N;
N *head;
void getdata();
int m,s,p;
char n[12];
main()
{

int ch;
head=(N *)malloc(sizeof(N));
head=NULL;
while(1)
{ clrscr();
printf("\n\t1 InsertFront\n\t2 InsertBack\n\t3 InsertAtpos\n\t4 Delete\n\t5
Display\n\t6 SearchRec\n\t7 Exit\n");

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

printf("\tEnter your choice\n\t");


scanf("%d",&ch);
switch(ch)
{
case 1: insertfront();
break;
case 2: insertback();
break;

case 3: insertatspos();
break;
case 4: deletee();
break;

case 5: display(head); break ;


case 6: search(head,p);
break;
case 7: printf("Byeeeeeeeeeee %c%c",2,2);
getch();
exit(0); break;
default: printf("Invalid choice\n");
}
getch();
}
}
/* ******************End of main() ********** */
void getdata()
{
printf("Enter the student id\n");
scanf("%d",&m);
printf("Enter the student name\n");
scanf("%s",n);
printf("Enter the semester\n");
scanf("%d",&s);
}
/* End of getdata() */

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

insertfront()
{
N *temp;
temp=(N*)malloc(sizeof(N));
getdata();
if(head==NULL)
{ temp->rno=m ;
strcpy(temp->name,n);
temp->sem=s;
temp->next=NULL;
head=temp;
}
else
{
temp->rno=m;
strcpy(temp->name,n);
temp->sem=s;
temp->next=head;
head=temp;
}

/* ************* End of InsertFront Function ************ */

insertback()
{
N *temp,*p;
p=head;
temp=(N *)malloc(sizeof(N));
getdata();
if(head==NULL)
printf("List is Empty\n");
else
{
while(p->next!=NULL)
{
p=p->next;
}

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

temp->rno=m;
strcpy(temp->name,n);
temp->sem=s;
temp->next=NULL;
p->next=temp;
}
}
/* **********End of insertBack function************* */
insertatspos()
{
int c=1,pos;
N *temp,*p;
p=head;
temp=(N*)malloc(sizeof(N));
getdata();
printf("Enter the position\n");
scanf("%d",&pos);
if(head==NULL)
printf("List is Empty\n");
else
{ while(c<pos)
{
p=p->next;
if(p==NULL)
{
printf("Number of nodes Less than the postion\n");
break;
}
else
c++;
}
temp->rno=m;
strcpy(temp->name,n);
temp->sem=s;
temp->next=p->next;
p->next=temp;
}

}
/* ********** End of insertat specified position ***** */

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

display()
{
N *temp;
temp=head;
printf("The list is \n");
printf("____________________________________________________________\n");
printf("SID\t\tNAME\t\tSEM\n");
printf("____________________________________________________________\n");
while(temp!=NULL)
{
printf("%3d\t%12s\t\t%2d\n",temp->rno,temp->name,temp->sem);
temp=temp->next;
}
printf("_________________________________________________________NULL");

}
/* *********** End of Display() ************** */
search()
{
N *temp;
int f=0,id;
printf("Enter the student id\n");
scanf("%d",&id);
if(head==NULL)
{
printf("Not Found\n");
return;
}
temp=head;
while(temp!=NULL)
{
if(temp->rno==id)
{
printf("RECORD FOUND IN THE LIST\n");
printf("\nRNO %d\nNAME %s\nSEM %d",temp->rno,temp->name,temp->sem);
f=1;
break;
}
temp=temp->next;
}

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

if(f==0)
printf("Record Not Found\n");
}

/* ***************End of search Function *********** */

deletee()
{
N *t1,*t2;
int id;
t1=head;
printf("Enter the student id to delete?");
scanf("%d",&id);
if(head==NULL)
printf("List is Empty\n");
else
if(t1->rno==id)
{ t1=t1->next;
head=t1;
}
else
{
while(t1->rno!=id)
{
if(t1->next==NULL)
{printf("NOT Found\n");
return;
}
t2=t1;
t1=t1->next;
}
t2->next=t1->next;
}
printf("The %d is deleted from list\n",id);
}
/* End of Deletee */

/* End of Program */

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

9 /* Write a C program using dynamic variables and pointers to construct a stack of


integers using singly linked list and to perform the following operations.
a. PUSH
b. POP
c. Display
The program should print appropriate messages for stack overflow and stack
underflow **/
#include<stdio.h>
struct stack
{
int data;
struct stack *next;
};
typedef struct stack S;
S *top;
void push();
void pop();
void display();
void main()
{
int ch;
top=(S*)malloc(sizeof(S));
top=NULL;
while(1)
{ clrscr();
printf("1 Push\n2 Pop\n3 Display\n4 Exit\n");
printf("Enter your choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1: push(); break;
case 2: pop(); break;
case 3: display(); break;
case 4: exit(0); break;
default: printf("invalid choice\n");
}
getch();
}
}
/* end of main function */

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

void push()
{
S *temp;
temp=(S*)malloc(sizeof(S));
printf("Enter the element\n");
scanf("%d",&temp->data);

if(top==NULL)
{
temp->next=NULL;
top=temp;
}
else
{
temp->next=top;
top=temp;
}
printf("Element pushed successfully\n");
}
/* *** End of push function ************ */
void pop()
{ S *temp;
temp=top;
if(top==NULL)
printf("Stack Underflow\n");
else
{
top=top->next;
printf("Element deleted is %d",temp->data);
free(temp);
}
} /*** End of delete function **** */

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

void display()
{ S *temp;
temp=top;
if(top==NULL)
printf("Stack Empty\n");
else
{
printf("Elements in stack are\n");
while(temp!=NULL)
{
printf("%d\n",temp->data);
temp=temp->next;
}
}
}
/* *********** end of display ******* */

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

10/* Program using Dynamic Variables and pointers to construct a queue of Integers
using SLL and to perform the following operations.
1. Insert
2. Delete
3. Display
Also check for appropriate conditions like overflow, underflow, Empty.*/

#include<stdio.h>
struct queue
{
int data;
struct queue *next;
};
typedef struct queue Q;
Q *front;
void insert();
void deletee();
void display();
void main()
{
int ch;
front=(Q*)malloc(sizeof(Q));
front=NULL;
while(1)
{ clrscr();
printf("1 Insert\n2 Delete\n3 Display\n4 Exit\n");
printf("Enter your choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1: insert(); break;
case 2: deletee(); break;
case 3: display(); break;
case 4: exit(0); break;
default: printf("invalid choice\n");
}
getch();
}
}
/* end of main function */

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

void insert()
{
Q *temp,*t;
temp=(Q*)malloc(sizeof(Q));
printf("Enter the element to be insert\n");
scanf("%d",&temp->data);

if(front==NULL)
{
temp->next=NULL;
front=temp;
}
else
{ t=front;
while(t->next!=NULL)
{
t=t->next;
}
temp->next=NULL;
t->next=temp;
}
} /* ************************ End of insertQ *********/
void deletee()
{
Q *temp;
if(front==NULL)
printf("Queue underflow\n");
else
{ temp=front;
front=front->next;
printf("Deleted element is %d\n",temp->data);
free(temp);
}
}
/* **************** End of Delete function ************/
void display()
{ Q *temp;
temp=front;
if(front==NULL)

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

printf("Queue Empty\n");
else
{
printf("The elements in Queue are\n");
while(temp!=NULL)
{
printf("%d\t",temp->data);
temp=temp->next;
}
}
}

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

11./* Write a program to support the following operations on doubly linked list where
each node consists of integers.
a Create a doubly linked list by adding each node at the front.
b Insert a new node to the left if the node whose key value is read as an input
c Delete the node of a given data, if it is found, otherwise display appropriate
message.
d Display the contents of the list. */
#include<stdio.h>
#include<conio.h>
struct list
{
int data;
struct list *next;
struct list *prev;
};
typedef struct list NODE;
NODE *head;
main()
{
int ch;
head=(NODE*)malloc(sizeof(NODE));
head=NULL;
while(1)
{
clrscr();
printf("1 InsertB\n2 Display\n3 InsertAtPosition\n4 Delete\n5 Exit\n");
printf("Enter your choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1: insert(); break;
case 2: display(); break;
case 3: insertp(); break;
case 4: deletee(); break;
case 5: exit(0);
}
getch();
}
}
/* End of main function ********* */

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

insert()
{
NODE *temp;
temp=(NODE*)malloc(sizeof(NODE));
printf("Enter the data\n");
scanf("%d",&temp->data);
if(head==NULL)
{
temp->next=NULL; /* if list emty temp is the first and last node*/
temp->prev=NULL;
head=temp;
}
else
{
temp->next=head;
temp->prev=NULL; /* if list is not empty make temp as first node*/
head->prev=temp;
head=temp;
}
}

/* **** End of Insert function ********/


display()
{
NODE *temp,*b;
temp=head;
if(head==NULL)
{
printf("List is Empty\n");
return;
}
printf("Forward Traversing is\n");
while(temp!=NULL)
{
b=temp;
printf("%d->",temp->data);
temp=temp->next;
}

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

printf("\nBackword Traversing is\n");


while(b!=NULL)
{
printf("%d->",b->data);
b=b->prev;
}
}

/* End of Display ****/

insertp()

{
NODE *temp,*t;
int p;
t=head;
temp=(NODE *)malloc(sizeof(NODE));
printf("Enter the data and position\n");
scanf("%d%d",&temp->data,&p);
while(p>1)
{
if(t->next==NULL)
{
printf("Number of nodes less than position\n");
return;
}
p--;
t=t->next;
}
temp->next=t->next;
temp->prev=t;
t->next=temp;
temp->next->prev=temp;
}
/* End of insert at position *****/

deletee()

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

{
NODE *temp,*t,*d;
int n;
temp=head;
printf("Enter the data to be delete?\n");
scanf("%d",&n);
if(temp->data==n)
{ d=temp;
temp=temp->next; /* if n is first node delete it*/
temp->prev=NULL;
head=temp;
free(d);
return;
}

while(temp->data!=n) /* traverse list until u get the element */


{
if(temp==NULL)
{ /* while traversing u encounter the end of list generate error*/
printf("%d is not present in list\n",n);
break;
}
t=temp;
temp=temp->next;
d=temp;
}
t->next=temp->next;
temp->next->prev=t;
free(d);
}

/* End of Deletee function *****/

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

12 /* Write Recursive C program for


a. Search an element on a given list of integers using the binary
search method.
b. Solving the tower of Hanoi problem.*/

#include<stdio.h>
void main()
{
int a[20],n,i,j,temp;
int low,high,k,R;
clrscr();
printf("Enter the number of elements\n");
scanf("%d",&n);
printf("Enter the elemets\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++)
{ for(j=0;j<n;j++)
{ if(a[i]<=a[j])
{
temp=a[i]; /* if elements are unsorted it sorts the elements*/
a[i]=a[j]; /* because binary search works for only sorted array*/
a[j]=temp;
}
}
}
printf("Enter the element to be search\n");
scanf("%d",&k);
low=0;
high=n-1;
R=bsearch(a,low,high,k);
if(R>=0)
printf("Search Success..... elemet found at %d",R+1);
else
printf("Element not Found\n");
getch();
}
/* End of main() *********** */

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

bsearch(int a[],int l,int h,int k)


{ int mid;
mid=(l+h)/2;
if(l<=h)
{ if(a[mid]==k) return mid;
if(k<a[mid]) bsearch(a,l,mid-1,k);
else
bsearch(a,mid+1,h,k);
}
else
return -1;
}
/* End of bsearch() ****************** */

b)
/* Program to solve Tower of hanoi problem */
#include<stdio.h>
main()
{ int n;
clrscr();
printf("Enter the number of discks\n");
scanf("%d",&n);
tower(n,'S','D','T');
getch();
}

/* End of main()****/

tower(int n,char s,char d,char t)


{
if(n>0)
{
tower(n-1,s,t,d);
printf("%d is moved from %c to %c\n",n,s,d);
tower(n-1,t,d,s);
}
return;
}
/* ***** End of display ***/
/* End of program */

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

13. /* Write a C program to sort a list of N strings using insertion sort algorithm. The
necessary data must be read from a sequential file.*/

#include<stdio.h>
main()
{
int i=0,j,k,m;
char fname[10],name[200][30],s[30];
FILE *fp;
clrscr();
printf("Enter the file name\n");
scanf("%s",fname);
fp=fopen(fname,"r");
if(fp==NULL)
{ printf("Can't open........................\n");
exit(0);
}
printf("The names in %s file are\n",fname);
for(;;)
{
fscanf(fp,"%s",s);
if(feof(fp)) /* reads the names from the file */
break;
strcpy(name[i++],s); /*store the name taken from the file int array*/
printf("%s ",s);
}
m=i;
printf("\nThe sorted order is \n");
for(j=0;j<m;j++)
{ strcpy(s,name[j]);
for(k=j-1; (k>=0&&strcmp(name[k],s)>0);k--)
{
strcpy(name[k+1],name[k]);
}
strcpy(name[k+1],s);
}
for(i=0;i<m;i++)
printf("%s\n",name[i]);
getch();
}

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

ALGORITHM for Linear and Binary Search

Algorithm for Linear Search

Step 1 : /* Read number of elements */


Read n
Step 2 : for I = 0 to n-1
Read A[i]
Step 3 : /*Read the key value to be searched */
Read key
Step 4 : /* Search key in Array A */
For i=0 to n-1
If A[i] = key then
Pos = i+1
Go to step 5
Else
Pos = -1
End if
End for
Step 5 : If pos = -1 then
Write “key value not found”
Else
Write “Key value found at position “ pos
End if
Step 6 : Stop

Algorithm for Binary Search

Step 1 : /* Read number of elements */


Read n
Step 2 : for I = 0 to n-1
Read A[i]
Step 3 : /*Read the key value to be searched */
Read key
Step 4 : lowerbound = 0,
Step 5 : Sort the array A
Step 6 : /* Search key in Sorted Array A */
While lowerbound < = upperbound
Mid = (lowerbound + upperbound)/2

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

If A[mid] = key then


Pos = i+1
Go to step 7
Else if A[mid] > key
Upperbound = mid -1
Else
Lowerbound = mid + 1
End if
End while
Pos = -1
Step 7 : If pos = -1 then
Write “key value not found”
Else
Write “Key value found at position “ pos
C code for Linear Search and Binary Search

#include<stdio.h>
#define max 20
void input(int *,int *,int *);
int lsearch(int *,int,int);
void bsort(int *,int);
int bsearch(int *,int,int);

void main()
{
int i,a[max],key,pos1=0,pos2=0,n;
clrscr();
for(;;)
{
clrscr();
printf("\n List of searching Techniques");
printf("\n 1. Linear Search");
printf("\n 2. Binary Search");
printf("\n Exit");
printf("\n Enter your choice");
fflush(stdin);
switch(getchar())
{
case '1':
input(a,&n,&key);

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

pos1= lsearch(a,n,key);
break;
case '2':
input(a,&n,&key);
bsort(a,n);
printf("\n Sorted array is:\n\n");
for(i=0;i<n;i++)
printf("%5d",a[i]);
pos2= bsearch(a,n,key);
break;
case '3':
exit(1);
default: printf("\n Envalid Choice");
}
if(pos1)

printf("\n key Found at position %d",pos1);


else if(pos2)
printf("\n key Found at position %d in Sorted Array",pos2);
else
printf("\n Key Not Found");
getch();
}
}
void input(int a[],int *n,int *key)
{
int i;
printf("\n Enter Size of array:");
scanf("%d",n);
printf("\n Enter Array element:");
for(i=0;i<*n;i++)
scanf("%d",&a[i]);
printf("\n Enter the searching key");
scanf("%d",key);
}

int lsearch(int a[],int n,int key)


{
int i;
for(i=0;i<n;i++)

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

if(a[i]==key)
return(i+1);

return(0);
}

void bsort(int a[],int n)


{
int i,j,temp;
for(i=0;i<n-1;i++)
for(j=0;j<n-1-i;j++)
if(a[j]>a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] =temp;
}
}

int bsearch(int a[],int n,int key)


{
int low,high,mid;
low=0;
high=n;
while(low<=high)
{
mid =(low+high)/2;
if(a[mid]==key)
return(mid+1);
if(a[mid]<key)
low =mid+1;
if(a[mid]>key)
high = mid-1;
}
return(0);
}

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

Algorithm to Create and Traverse a Binary Tree

Algorithm to Create a Binary Tree

Step 1 : Read the Root node value as root->info.


Step 2 : Read the next value as item.
Step 3 : If item < root->info then
While root->left != NULL
root = root->left
End while
Store item as left child.
Else
While root->right != NULL
root = root-> right
End while
Store item as right child.
Step 4: Repeat step 2 thru step 4 until EOF.

RECURSIVE ALGORITHM for Pre-order Tree Traversal

Step 1 : Write the Root node value.


Step 2 : Traverse the Left Sub-tree in Pre-order.
Step 3 : Traverse the Right Sub-tree in Pre-order.

RECURSIVE ALGORITHM for Post-order Tree Traversal

Step 1 : Traverse the Left Sub-tree in Post-order.


Step 2 : Traverse the Right Sub-tree in Post-order.
Step 3 : Write the Root node value.

RECURSIVE ALGORITHM for In-order Tree Traversal

Step 1 : Traverse the Left Sub-tree in In-order.


Step 2 : Write the Root node value.
Step 3 : Traverse the Right Sub-tree in In-order.

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

C – code for the Binary creation and Traversals

#include<stdio.h>
#include<conio.h>
#include<alloc.h>
struct bst
{
int info;
struct bst *right, *left;
};
typedef struct bst * NODEPTR;

void main()
{
int ch,item;
NODEPTR root=NULL;
for(;;)
{
clrscr();
printf("\nOperations on BST");
printf("\n-----------------");
printf("\n1. Create BST");
printf("\n2. Preorder traversal");
printf("\n3. Postorder traversal");
printf("\n4. Inorder traversal");
printf("\n5. Exit");
printf("\n\nEnter Your Choice: ");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("\nEnter the item to be inserted : ");
scanf("%d",&item);
root=create(root,item);
break;
case 2: printf("\nPreorder Traversal: ");
preorder(root);
break;
case 3: printf("\nPostorder Traversal: ");
postorder(root);
break;

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

case 4: printf("\nInorder Traversal: ");


inorder(root);
break;
case 5: exit(1);
default: printf("\nInvalid Choice");
}
printf("\n\nPress any key to continue....");
getch();
}
}

NODEPTR create(NODEPTR root, int item)


{
NODEPTR p;
if(root != NULL)
{
if(item < root->info)
root->left = create(root->left,item);
else
root->right = create(root->right,item);
return root;
}
else
{
p=(NODEPTR)malloc(sizeof(struct bst));
p->info=item;
p->left=p->right=NULL;
return p;
}
}

void preorder(NODEPTR root)


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

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

void postorder(NODEPTR root)


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

void inorder(NODEPTR root)


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

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

/* ALGORITHM FOR QUICK SORT*/


QUICK(A,N,LB,UB)
HERE A IS AN ARRAY OF N ELEMENT LB IS LOWER BOUND AND UB IS UPPER
BOUND ,
CHOOSE A ELEMENT P FROM SPECIFIC POSITION OF ARRAY LET P =A[0]
BY USING PARTITION FUNCTION WE WILL PARTITION ARRAY A SO THAT
ELEMENT A IS PLACED INTO POSITION J AND FOLLOWING CONDITION HOLDS
GOOD:

1. EACH OF THE ELEMENT IN POSITION 0 THROUGH J-1 IS LESS THAN OR


EQUAL TO P.
2. EACH OF THE ELEMENT IN POSITION J +1 THROUGH N-1 IS GREATER THAN
OR EQUAL TO P.

IF THE FORGOING PROCESS IS REPEATED WITH SUBARRAY A[0] AND A[J-1] AND
A[J+1] THROUGH A[N-1]
AND ANY SUBARRAY CREATED BY THE PROCESS IN SUCCESSIVE ITERATIONS
THE FINAL RESULT IS A SORTED FILE.

PARTITION(A,LB,UB)

THE OBJECT OF PARTITION IS TO ALLOW A SPECIFIC ELEMENT TO FIND ITS


PROPER POSITION WITH RESPECT TO OTHER IN THE SUBARRAY.
TWO POINTERS UP AND DOWN ARE INITIALIZED TO UPPER AND LOWER
BOUNDS OF SUBARRAY RESPECTIVELY
AT ANY POINT DURING EXECUTION EACH ELEMENT IN P POSITION ABOVE UP
IS GREATER THAN OR EQUAL TO P
AND EACH ELEMENT IN A POSITION BELOW DOWN IS LESS THAN OR EQUAL
TO A.THE TWO POINTERS UP AND DOWN
ARE MOVE TOWARDS EACH OTHER IN FOLLOWING FASHION.

STEP 1: REPEATEDLY INCREASE THE POINTER DOWN BY ONE POSITION UNTIL


A[DOWN]>A
STEP 2: REPEATEDLY DECREASE THE POINTER DOWN BY ONE POSITION UNTIL
A[UP]<=A
STEP 3: IF UP > DOWN INTERCHANGE A[DOWN] WITH A[UP].

THE PROCESS IS REPEATED UNTIL THE CONDITION IN STEP 3 FAILS AT WHICH


POINT A[UP] IS INTERCHANGED WITH A[LB],WHOSE FINAL POSITION WAS
SOUGHT AND J IS SET TO UP.

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

C code for Quick Sort Algorithm

#include<stdio.h>
#include<conio.h>

void quick(int x[],int lb,int ub)


{
int j;
if(lb<ub) /* array is sorted*/
{
j=partition(x,lb,ub);
/* partition element of the subarray such that one of the elements
possibly x[lb]) is now at x[j](j is an output parameter) and :
1. x[i]<=x[j] for lb<=i<j
2. x[i]>=x[j] for j<i<=ub
x[j] is now at its final position*/

quick(x,lb,j-1);
/* recursively sort the subarray between position lb aND J-1*/
quick(x,j+1,ub);
/* recursively sort the subarray between position J+1 aND ub*/
}
}

int partition(int x[],int lb,int ub)


{
int a,down,temp,up;
a=x[lb]; /* a is the element whose final position is sougth */
up=ub;
down=lb;
while(down<up)
{
while(x[down]<=a)
down++; /* move up the array */
while(x[up]>a)
up--; /* move down the array */
if(down<up)
{
temp=x[down];

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

x[down]=x[up];
x[up]=temp;
}
}
x[lb]=x[up];
x[up]=a;
return(up);
}

void main()
{
int n,i;
int x[100];
clrscr();
printf("\n Enter the number element");
scanf("%d",&n);
printf("\n Enter array element:");
for(i=0;i<n;i++)
scanf("%d",&x[i]);
quick(x,0,n-1);
printf("\n sorted array is:\n\n");
for(i=0;i<n;i++)
printf("%d",x[i]);
getch();
}

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

HEAP SORT
Heap sort is simply an implementation of the general selection sort using the input array
'A' as a heap representing a descending priority queue.
ALGORITHM for HEAP SORT (Ascending Order)

Step 1 : /* Read the size of the array */


Read n.
Step 2 : /* Read array elements */
for i -> 0 to n-1
Read A[i].
Step 3 : /* Create Descending Heap using procedure pq_insert */
for i -> 1 to n-1
pq_insert(A,i,A[i]);
Step 4 : /* Re-arrange the elements in the Heap using procedure pq_maxdel */
for i -> n-1 to 1 by -1
A[i] <- pq_maxdel(A,i+1);
Step 5 : /* Display the sorted array as output */
for i -> 0 to n-1
Write A[i].
Step 6 : Stop.

ALGORITHM for the Procedure pq_insert

procedure pq_insert(A,k,ele)

Step 1 : /* Assign son node index */


s <- k.
Step 2 : /* Calculation of father node index */
f <- (s-1)/2
Step 3 : /* Find the proper position of the inserted element in the Heap */
While s > 0 and A[f] < ele repeat Step 4 thru Step 6
Step 4 : /* Shift down the father node to its sons position */
A[s] <- A[f]
Step 5 : /* Set new value for son node index */
s <- f
Step 6 : /* Calculate new father node index */
f <- (s-1)/2
Step 7 : /* Store the element in the Heap */
A[s] <- ele
Step 8 : Return.

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

ALGORITHM for the Procedure pq_maxdel

procedure pq_maxdel(A,k+1)

Step 1 : /* Store root value in the Heap */


p <- A[0]
Step 2 : /* Call another procedure adjust to re-arrange Heap */
adjust(0,k-1);
Step 3 : /* Return the value */
Return p

ALGOTRITHM for the Procedure adjust

procedure adjust(root,k)

Step 1 : /* Store root value as father node index */


f <- root
Step 2 : /* Store the key value */
val <- A[k]
Step 3 : /* Calculate son node index using procedure largeson */
s <- largeson(f,k-1);
Step 4 : /* Re-arrange the Heap */
While s>=0 and val < A[s] repeat Step 5 thru Step Step 7
Step 5 : /* Change value in father node */
A[f] <- A[s]
Step 6 : /* Set new value for father node index */
f <- s
Step 7 : /* Calculate new son node index using procedure largeson */
s <- largeson(f,k-1)
Step 8 : /* Store the key value in Heap */
A[f] <- val
Step 9 : Return

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

ALGORITHM for the Procedure largeson

procedure largeson(p,m)

Step 1 : /* Calculate son node index */


s <- 2*p+1
Step 2 : /* Find out largest son index of the current father node */
if s+1 <= m and A[s] < A[s+1] then
s <- s+1
Step 3 : /* Check for Adjusted Heap boundary */
if s > m then
Return -1
else
Retrun s

C – program for Heap Sort

#include<stdio.h>
#include<math.h>
int a[31];

void main()
{
register int i;
int n,y;
while(1)
{
clrscr();
printf("\nEnter the number of elements in the Array\t:\t");
scanf("%d",&n);
printf("\n\nEnter the elements in the Array\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
clrscr();
printf("\nArray Before Sorting\n");
for(i=0;i<n;i++)
printf("%d ",a[i]);
for(i=1;i<n;i++)
pqins(i,a[i]);
printf("\n\nInitial Heap\n");

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

display(n,10);
getch();
for(i=n-1,y=30;i>0;i--,y+=20)
{
a[i]=pqmaxdel(i+1);
if(y>=50)
{
clrscr();
y=10;
}
printf("\nHeap After a[%d]=pqmaxdel(%d)",i,i+1);
display(n,y);
getch();
}
printf("\n\nArray After Sorting\n");
for(i=0;i<n;i++)
printf("%d ",a[i]);
printf("\n\n\nDo You Want to Continue?(Y/N) :\t");
fflush(stdin);
if(toupper(getchar())!='Y')
break;
}
}

void pqins(int k,int elt)


{
int s,f;
s=k;
f=(s-1)/2;
while(s>0&&a[f]<elt)
{
a[s]=a[f];
s=f;
f=(s-1)/2;
}
a[s]=elt;
}

int pqmaxdel(int k)
{

Dept. of M C A B M S College of Engineering, B’lore


MCA 26 Data structure Lab Manual page 2 of 2

int p;
p=a[0];
adjust(0,k-1);
return(p);
}
void adjust(int r,int k)
{
int f,s,key;
f=r;
key=a[k];
s=largeson(f,k-1);
while(s>=0&&a[s]>key)
{
a[f]=a[s];
f=s;
s=largeson(f,k-1);
}
a[f]=key;
}
int largeson(int p,int m)
{
int s;
s=2*p+1;
if(s+1<=m&&a[s]<a[s+1])
s=s+1;
if(s>m)
return -1;
return s;
}
void display(int n,int y)
{
int i,j,x,k,c=0;
for(i=0,k=40 ; ;i++,k/=2,y+=3)
for(j=0,x=k ;j<pow(2,i) ;j++,x+=80/pow(2,i))
{
gotoxy(x,y);
printf("%d",a[c++]);
if(c==n)
return;
}

Dept. of M C A B M S College of Engineering, B’lore