CS3311 - Data Structures Laboratory
CS3311 - Data Structures Laboratory
(Approved by AICTE, New Delhi and Affiliated to Anna University, Chennai & ISO 9001:2015 Certified
Institution)
Name :
Reg No :
Subject name :
Academic Year :
ARULMURUGAN COLLEGE OF ENGINEERING
(Approved by AICTE and Affiliated to Anna University)
THENNILAI, KARUR – 639 206.
PRACTICAL RECORD
Register Number
Name
Year / Sem
Degree / Branch
Certified that this is a bonafide record of work done by the above student
during the year 20 - 20
Ex. Staff
Date Name of the Experiment Marks Page No
No Signature
ARRAY IMPLEMENTATION OF STACK ADTS
EX NO:1(A)
AIM:
To write a C program to implement Stack operations such as push, pop and display using
array.
ALGORITHM:
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<process.h>
#define size 5
int item;
int s[10];
int top;
void display()
{
inti;
if(top==-1)
{
printf("\nstack is empty");
return;
}
printf("\nContent of stack is:\n");
for(i=0;i<=top;i++)
printf("%d\t",s[i]);
}
void push()
{
if(top==size-1)
{
printf("\nStack is full");
return;
}
printf("\nEnter item:\n");
scanf("%d",&item);
s[++top]=item;
}
void pop()
{
if(top==-1)
{
printf("\nstack is empty");
return;
}
printf("\nDeleted item is: %d",s[top]);
top--;
}
void main()
{
intch;
top=-1;
clrscr();
printf("\n1.push\t\t2.pop\n3.display\t4.exit\n");
do{
printf("\nEnter your choice:\n");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("Enter item:\n");
scanf("%d",&item);
push();
break;
case 2: pop();
break;
case 3: display();
break;
case 4: exit(0);
default: printf("\nWrong entry ! try again");
}}while(ch<=4);
getch();
}
OUTPUT:
1. Push 2.pop
3. Display 4.exit
Enter your choice:
1
Enter item:
100
Enter your choice:
1
Enter item:
200
Enter your choice:
1
Enter item:
300
Enter your choice:
2
Deleted item is: 300
Enter your choice:
3
Content of stack is:
100 200
Enter your choice: 4
RESULT:
AIM:
To write a C program to implement Queue operations such as enqueue, dequeue and
display using array.
ALGORITHM:
Step 1: Start the program.
Step 2: Initialize front=0; rear=-1.
Step 3: Enqueue operation moves a rear by one position and inserts a element at the rear.
Step 4: Dequeue operation deletes an element at the front of the list and moves the front by one
position
Step 5: Display operation displays all the element in the list.
Step 6: Stop.
PROGRAM:
#include<stdio.h>
#include<conio.h>
#define SIZE 5 /* Size of Queue */
int Q[SIZE],f=0,r=-1; /* Global declarations */
Qinsert(intelem)
{ /* Function for Insert operation */
if( Qfull())
printf("\n\n Overflow!!!!\n\n");
else
{
++r;
Q[r]=elem;
}
}
intQdelete()
{ /* Function for Delete operation */
intelem;
if(Qempty()){ printf("\n\nUnderflow!!!!\n\n");
return(-1); }
else
{
elem=Q[f];
f=f+1;
return(elem);
}}
int Qfull()
{ /* Function to Check Queue Full */
if(r==SIZE-1) return 1;
return 0;
}
intQempty()
{ /* Function to Check Queue Empty */
if(f> r) return 1;
return 0;
}
display()
{ /* Function to display status of Queue */
inti;
if(Qempty()) printf(" \n Empty Queue\n");
else
{
printf("Front->");
for(i=f;i<=r;i++)
printf("%d ",Q[i]);
printf("<-Rear");
}}
void main()
{ /* Main Program */
intopn,elem;
do
{
clrscr();
printf("\n ### Queue Operations using Arrays### \n\n");
printf("\n Press 1-Insert, 2-Delete,3-Display,4-Exit\n");
printf("\n Your option ? ");
scanf("%d",&opn);
switch(opn)
{
case 1: printf("\n\nRead the element to be Inserted ?");
scanf("%d",&elem);
Qinsert(elem);
break;
case 2: elem=Qdelete();
if( elem != -1)
printf("\n\nDeleted Element is %d \n",elem);
break;
case 3: printf("\n\nStatus of Queue\n\n");
display();
break;
case 4: printf("\n\n Terminating \n\n");
break;
default: printf("\n\nInvalid Option !!! Try Again !! \n\n");
break;
}
printf("\n\n\n\n Press a Key to Continue . . . ");
getch();
}while(opn != 4);
getch();
}
OUTPUT:
### Queue Operations using Arrays###
Press 1-Insert, 2-Delete,3-Display,4-Exit
Your option ? 1
Status of Queue
Front->200 300 <-Rear
Press a Key to Continue . . .
RESULT:
AIM:
ALGORITHM:
Step 1: Start the Program & Read the input data element
PROGRAM:
#include <stdio.h>
# define max 6
int queue[max]; // array declaration
int front=-1;
int rear=-1;
// function to insert an element in a circular queue
void enqueue(int element)
{
if(front==-1 && rear==-1) // condition to check queue is empty
{ front=0;
rear=0;
queue[rear]=element; }
else if((rear+1)%max==front) // condition to check queue is full
{ printf("Queue is overflow.."); }
else {
rear=(rear+1)%max; // rear is incremented
queue[rear]=element; // assigning a value to the queue at the rear posit
ion. }}
// function to delete the element from the queue
int dequeue()
{
if((front==-1) && (rear==-1)) // condition to check queue is empty
{ printf("\nQueue is underflow.."); }
else if(front==rear)
{
printf("\nThe dequeued element is %d", queue[front]);
front=-1;
rear=-1;
} else {
printf("\nThe dequeued element is %d", queue[front]);
front=(front+1)%max; } }
// function to display the elements of a queue
void display()
{
int i=front;
if(front==-1 && rear==-1)
{ printf("\n Queue is empty.."); }
else {
printf("\nElements in a Queue are :");
while(i<=rear)
{ printf("%d,", queue[i]);
i=(i+1)%max; } } }
int main()
{
int choice=1,x; // variables declaration
while(choice<4 && choice!=0) // while loop
{
printf("\n Press 1: Insert an element");
printf("\nPress 2: Delete an element");
printf("\nPress 3: Display the element");
printf("\nEnter your choice");
scanf("%d", &choice);
switch(choice)
{
case 1:
printf("Enter the element which is to be inserted");
scanf("%d", &x);
enqueue(x);
break;
case 2:
dequeue();
break;
case 3:
display(); }} return 0; }
OUTPUT:
RESULT:
Thus a C program for circular Queue using array was implemented successfully.
IMPLEMENTATION OF SINGLY LINKED LIST
EX NO : 2
AIM:
ALGORITHM:
Step 1: Start the Program & Read the input data element
Step 2: head and tail are two pointers, where head points to first node of linked list and tail points
the last node of the linked list.
Step 4: Last Node of the linked list contains NULL in the next part.
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
}List;
//Initialize List
void initList(List * lp)
{
lp->head = NULL;
lp->tail = NULL;
}
nNode->item = item;
nNode->next = NULL;
return nNode;
}
int item = 0;
if(lp->tail == NULL)
{
printf("\nList is Empty ...");
return -1;
}
else
{
temp = lp->head;
while(temp->next != lp->tail)
{ temp = temp->next;}
item = lp->tail->item;
lp->tail = temp;
lp->tail->next = NULL;
}
return item;
}
if(lp->head == NULL)
{
printf("\nList is Empty ...");
return -1;
}
else
{
item = lp->head->item;
lp->head = lp->head->next;
}
return item;
}
if(lp->head == NULL)
{
printf("\nEmpty List");
return;
}
node = lp->head;
printf("\nList: \n\n\t");
while(node != NULL)
{
printf("| %05d |",node->item);
node = node->next;
if(node !=NULL)
printf("--->");
}
printf("\n\n");
}
int item = 0;
lp = (List *) malloc(sizeof(List));
initList(lp);
addAtTail(lp,10);
addAtTail(lp,20);
addAtHead(lp,30);
addAtHead(lp,40);
printList(lp);
item = delFromTail(lp);
if(item >= 0)
printf("\nDeleted item is : %d",item);
printList(lp);
item = delFromHead(lp);
if(item >= 0)
printf("\nDeleted item is : %d",item);
printList(lp);
return 0;
}
OUTPUT:
List:
Deleted item is : 20
List:
Deleted item is : 40
List:
RESULT:
AIM:
To write a C program to implement Stack operations such as push, pop and display using
linked list.
ALGORITHM:
PROGRAM:
#include "stdio.h"
#include "stdlib.h"
#include "conio.h"
void pop();
void push(int value);
void display();
struct node
{
intdata;
struct node *link;
};
struct node *top=NULL,*temp;
void main()
{
int choice,data;
while(1) //infinite loop is used to insert/delete infinite number of elements in stack
{
printf("\n1.Push\n2.Pop\n3.Display\n4.Exit\n");
printf("\nEnterur choice:");
scanf("%d",&choice);
switch(choice)
{
case 1: //To push a new element into stack
printf("Enter a new element :");
scanf("%d",&data);
push(data);
break;
case 2: // pop the element from stack
pop();
break;
case 3: // Display the stack elements
display();
break;
case 4: // To exit
exit(0);
}}
getch();
//return 0;
}
void display()
{
temp=top;
if(temp==NULL)
{
printf("\nStack is empty\n");
}
printf("\n The Contents of the Stack are...");
while(temp!=NULL)
{
printf(" %d ->",temp->data);
temp=temp->link; } }
void push(int data)
{
temp=(struct node *)malloc(sizeof(struct node)); // creating a space for the new element.
temp->data=data;
temp->link=top;
top=temp;
display(); }
void pop()
{
if(top!=NULL)
{
printf("The poped element is %d",top->data);
top=top->link; }
else
{
printf("\nStack Underflow");
} display(); }
OUTPUT:
1. Push
2.Pop
3.Display
4.Exit
Enter ur choice:1
Enter a new element :10
The Contents of the Stack are... 10 ->
1.Push
2. Pop
3.Display
4.Exit
Enter ur choice:1
Enter a new element :20
The Contents of the Stack are... 20 -> 10 ->
1.Push
2.Pop
3.Display
4.Exit
Enter ur choice:1
Enter a new element :30
The Contents of the Stack are... 30 -> 20 -> 10 ->
1.Push
2.Pop
3.Display
4.Exit
Enter ur choice:2
The poped element is 30
The Contents of the Stack are... 20 -> 10 ->
1.Push
2.Pop
3.Display
4.Exit
Enter ur choice:3
The Contents of the Stack are... 20 -> 10 ->
1.Push
2.Pop
3.Display
4.Exit
Enter ur choice:4
RESULT:
Thus a C program for Stack using linked list was implemented successfully.
LINKED LIST IMPLEMENTATION OF LINEAR QUEUE ADTS
EX NO : 3(B)
AIM:
ALGORITHM:
PROGRAM:
#include<stdio.h>
#include<conio.h>
struct node
{
int info;
struct node *link;
}*front = NULL, *rear = NULL;
void insert();
voiddelet();
void display();
int item;
void main()
{
intch;
do
{
printf("\n\n1.\tEnqueue\n2.\tDequeue\n3.\tDisplay\n4.\tExit\n");
printf("\nEnter your choice: ");
scanf("%d", &ch);
switch(ch)
{
case 1:insert();
break;
case 2:delet();
break;
case 3:display();
break;
case 4:exit(0);
default:
printf("\n\nInvalid choice. Please try again...\n");
} } while(1);
getch(); }
void insert()
{
printf("\n\nEnter ITEM: ");
scanf("%d", &item);
if(rear == NULL)
{
rear = (struct node *)malloc(sizeof(struct node));
rear->info = item;
rear->link = NULL;
front = rear;
}
else
{
rear->link = (struct node *)malloc(sizeof(struct node));
rear = rear->link;
rear->info = item;
rear->link = NULL;
}}
Void delet()
{
struct node *ptr;
if(front == NULL)
printf("\n\nQueue is empty.\n");
else
{
ptr = front;
item = front->info;
front = front->link;
free(ptr);
printf("\nItem deleted: %d\n", item);
if(front == NULL)
rear = NULL;
}}
void display()
{
struct node *ptr = front;
if(rear == NULL)
printf("\n\nQueue is empty.\n");
else
{
printf("\n\n");
while(ptr != NULL)
{
printf("%d\t",ptr->info);
ptr = ptr->link;
} }}
OUTPUT:
1. Enqueue
2. Dequeue
3. Display
4. Exit
Enter your choice: 1
Enter ITEM: 12
1. Enqueue
2. Dequeue
3. Display
4. Exit
Enter your choice: 1
Enter ITEM: 15
1. Enqueue
2. Dequeue
3. Display
4. Exit
Enter your choice: 1
Enter ITEM: 20
1. Enqueue
2. Dequeue
3. Display
4. Exit
Enter your choice: 2
Item deleted: 12
1. Enqueue
2. Dequeue
3. Display
4. Exit
Enter your choice:3
15 20
1. Enqueue
2. Dequeue
3. Display
4. Exit
Enter your choice:4
RESULT:
Thus a C program for Queue using linked list was implemented successfully.
IMPLEMENTATION OF POLYNOMIAL MANIPULATION USING LINKED
EX NO : 4 LIST
AIM:-
To write a ‗C ' program for implementing addition and subtraction of two polynomials
using linked list.
ALGORITHM:-
PROGRAM :-
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef struct poly
{
int exp; //index
int coef; //coefficient
struct poly *next;
}PNode,*PLinklist;
/*Linked list initialization*/
int Init(PLinklist *head)
{
*head=(PLinklist)malloc(sizeof(PNode));
if(*head)
{
(*head)->next=NULL;
return 1;
}
else
return 0;
}
/*Creating linked list by tail interpolation*/
int CreateFromTail(PLinklist*head)
{
PNode *pTemp,*pHead;
int c; //Storage factor
int exp; //Storage index
int i=1 ; //Counter
pHead=*head;
scanf("%d,%d",&c,&exp);
while(c!=0)//When the coefficient is zero, end the input
{
pTemp=(PLinklist)malloc(sizeof(PNode));
if(pTemp)
{
pTemp->exp=exp; //Acceptance index
pTemp->coef=c; //Acceptance coefficient
pTemp->next=NULL;
pHead->next=pTemp;
pHead=pTemp;
scanf("%d,%d",&c,&exp);
}
else
return 0;
}
return 1;
}
/*Add two polynomials*/
void Polyadd(PLinklist LA,PLinklist LB)
{
PNode*LAI=LA->next; //Pointer LAI moves in polynomial A
PNode*LBI=LB->next;
PNode*temp; //Pointer temp saves the node to
be deleted
int sum=0; //Sum of preservation factors
/*Compare the exponential terms of the nodes referred to by LAI and
LBI*/
while(LAI&&LBI)
{
if(LAI->exp<LBI->exp){
LA->next=LAI;
LA=LA->next;
LAI=LAI->next;
}
else if(LAI->exp==LBI->exp)
{
sum=LAI->coef+LBI->coef;
if(sum)
{
LAI->coef=sum;
LA->next=LAI;
LA=LA->next;
LAI=LAI->next;
temp=LBI;
LBI=LBI->next;
free(temp);
}
else
{
temp=LAI;
LAI=LAI->next;
free(temp);
temp=LBI;
LBI=LBI->next;
free(temp);
}
}
else
{
LA->next=LBI;
LA=LA->next;
LBI=LBI->next;
}
}
if(LAI)
LA->next=LAI;
else
LA->next=LBI;
}
/*Subtraction of two polynomials*/
void Polysub(PLinklist LA,PLinklist LB)
{
PNode*LAI=LA->next; //Pointer LAI moves in polynomial A
PNode*LBI=LB->next;
PNode*temp; //Pointer temp saves the node to
be deleted
int difference=0; //Preservation factor
/*Compare the exponential terms of the nodes referred to by LAI and
LBI*/
while(LAI&&LBI)
{
if(LAI->exp<LBI->exp){
LA->next=LAI;
LA=LA->next;
LAI=LAI->next;
}
else if(LAI->exp==LBI->exp)
{
difference=LAI->coef-LBI->coef;
if(difference)
{
LAI->coef=difference;
LA->next=LAI;
LA=LA->next;
LAI=LAI->next;
temp=LBI;
LBI=LBI->next;
free(temp);
}
else
{
temp=LAI;
LAI=LAI->next;
free(temp);
temp=LBI;
LBI=LBI->next;
free(temp);
}
}
else
{
LA->next=LBI;
LA=LA->next;
LBI=LBI->next;
}
}
if(LAI)
LA->next=LAI;
else
LA->next=LBI;
}
void Print(PLinklist head)
{
head=head->next;
while(head)
{
if(head->exp)
printf("(%dx^%d)",head->coef,head->exp);
else
printf("%d",head->coef);
if(head->next)
printf("+");
else
break;
head=head->next;
}
}
int main(void)
{
PLinklist LA;
PLinklist LB;
Init(&LA);
Init(&LB);
printf("Please enter the coefficient of the first
polynomial,index,Enter 0,0 End input\n");
CreateFromTail(&LA);
printf("Please enter the coefficient of the second
polynomial,index,Enter 0,0 End input\n");
CreateFromTail(&LB);
Print(LA);
printf("\n");
Print(LB);
printf("\n");
int i;
if(1==i){
Polyadd(LA,LB);
printf("The result of adding two polynomials:\n");
Print(LA);
printf("\n");
}
else if(0==i){
Polysub(LA,LB);
printf("The result of subtracting two polynomials:\n");
Print(LA);
printf("\n");
}
else
printf("Please enter the correct characters");
return 0;
}
OUTPUT:
Enter polynomial 1 :
Enter the number of terms : 2
Enter coeficient for term 1 : 2
Enter exponent for term 1 : 2
Enter coeficient for term 2 : 3
Enter exponent for term 2 : 4
Enter polynomial 2 :
Enter the number of terms : 5
Enter coeficient for term 1 : 4
Enter exponent for term 1 : 3
Enter coeficient for term 2 : 2
Enter exponent for term 2 : 1
Enter coeficient for term 3 : 2
Enter exponent for term 3 : 3
Enter coeficient for term 4 : 4
Enter exponent for term 4 : 5
Enter coeficient for term 5 : 6
Enter exponent for term 5 : 3
0x^2) + (2.0x^1)
RESULT :
Thus the C program for the concept of addition & subtraction of two polynomials using
list was implemented successfully.
IMPLEMETATION OF EVALUATING POSTFIX EXPRESSION – INFIX TO
EX NO : 05 POSTFIX CONVERSION.
AIM:-
To write a ‗C ' program to implement & evaluating the concept of infix to postfix
conversion.
ALGORITHM:-
PROGRAM :-
#include<stdio.h>
#include<ctype.h>
char stack[100];
int top = -1;
void push(char x)
{
stack[++top] = x;
}
char pop()
{
if(top == -1)
return -1;
else
return stack[top--];
}
int priority(char x)
{
if(x == '(')
return 0;
if(x == '+' || x == '-')
return 1;
if(x == '*' || x == '/')
return 2;
return 0;
}
int main()
{
char exp[100];
char *e, x;
printf("Enter the expression : ");
scanf("%s",exp);
printf("\n");
e = exp;
while(*e != '\0')
{
if(isalnum(*e))
printf("%c ",*e);
else if(*e == '(')
push(*e);
else if(*e == ')')
{
while((x = pop()) != '(')
printf("%c ", x);
}
else
{
while(priority(stack[top]) >= priority(*e))
printf("%c ",pop());
push(*e);
}
e++;
}
while(top != -1)
{
printf("%c ",pop());
}
return 0;
}
OUTPUT:
a b c * +
a b + c * d a - +
RESULT :
Thus the C program for the concept of infix to postfix was converted and implemented
implemented successfully.
IMPLEMETATION OF BINARY SEARCH TREES
EX NO : 06
AIM:-
To write a ‗C ' program to implement binary search tree.
ALGORITHM:-
PROGRAM :-
OUTPUT:-
Main Menu
1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindM ax
7.Inorder
8.Preorder
9.Postorder
10.Exit
Enter ur choice :2
Enter the data:20
10 20
BINARY SEARCH TREE
Main Menu
1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindM ax
7.Inorder
8.Preorder
9.Postorder
10.Exit
Enter ur choice :2
Enter the data:30
10 20 30
RESULT :
Thus the C program for the concept of binary search tree was implemented
successfully.
IMPLEMENTATION OF AVL TREES
EX NO : 07
AIM :
To write a C program to implement AVL trees.
ALGORITHM :
PROGRAM :
#include<stdio.h>
typedef struct node
{
int data;
struct node *left,*right;
int ht;
}node;
node *insert(node *,int);
node *Delete(node *,int);
void preorder(node *);
void inorder(node *);
int height( node *);
node *rotateright(node *);
node *rotateleft(node *);
node *RR(node *);
node *LL(node *);
node *LR(node *);
node *RL(node *);
int BF(node *);
int main()
{
node *root=NULL;
int x,n,i,op;
do
{
printf("\n1)Create:");
printf("\n2)Insert:");
printf("\n3)Delete:");
printf("\n4)Print:");
printf("\n5)Quit:");
printf("\n\nEnter Your Choice:");
scanf("%d",&op);
switch(op)
{
case 1: printf("\nEnter no. of elements:");
scanf("%d",&n);
printf("\nEnter tree data:");
root=NULL;
for(i=0;i<n;i++)
{
scanf("%d",&x);
root=insert(root,x);
}
break;
case 2: printf("\nEnter a data:");
scanf("%d",&x);
root=insert(root,x);
break;
case 3: printf("\nEnter a data:");
scanf("%d",&x);
root=Delete(root,x);
break;
case 4: printf("\nPreorder sequence:\n");
preorder(root);
printf("\n\nInorder sequence:\n");
inorder(root);
printf("\n");
break;
}
}while(op!=5);
return 0;
}
node * insert(node *T,int x)
{
if(T==NULL)
{
T=(node*)malloc(sizeof(node));
T->data=x;
T->left=NULL;
T->right=NULL;
}
else
if(x > T->data) // insert in right subtree
{
T->right=insert(T->right,x);
if(BF(T)==-2)
if(x>T->right->data)
T=RR(T);
else
T=RL(T);
}
else
if(x<T->data)
{
T->left=insert(T->left,x);
if(BF(T)==2)
if(x < T->left->data)
T=LL(T);
else
T=LR(T);
}
T->ht=height(T);
return(T);
}
node * Delete(node *T,int x)
{
node *p;
if(T==NULL)
{
return NULL;
}
else
if(x > T->data) // insert in right subtree
{
T->right=Delete(T->right,x);
if(BF(T)==2)
if(BF(T->left)>=0)
T=LL(T);
else
T=LR(T);
}
else
if(x<T->data)
{
T->left=Delete(T->left,x);
if(BF(T)==-2) //Rebalance during windup
if(BF(T->right)<=0)
T=RR(T);
else
T=RL(T);
}
else
{
//data to be deleted is found
if(T->right!=NULL)
{ //delete its inorder succesor
p=T->right;
while(p->left!= NULL)
p=p->left;
T->data=p->data;
T->right=Delete(T->right,p->data);
if(BF(T)==2)//Rebalance during windup
if(BF(T->left)>=0)
T=LL(T);
else
T=LR(T);\
}
else
return(T->left);
}
T->ht=height(T);
return(T);
}
int height(node *T)
{
int lh,rh;
if(T==NULL)
return(0);
if(T->left==NULL)
lh=0;
else
lh=1+T->left->ht;
if(T->right==NULL)
rh=0;
else
rh=1+T->right->ht;
if(lh>rh)
return(lh);
return(rh);
}
node * rotateright(node *x)
{
node *y;
y=x->left;
x->left=y->right;
y->right=x;
x->ht=height(x);
y->ht=height(y);
return(y);
}
node * rotateleft(node *x)
{
node *y;
y=x->right;
x->right=y->left;
y->left=x;
x->ht=height(x);
y->ht=height(y);
return(y);
}
node * RR(node *T)
{
T=rotateleft(T);
return(T);
}
node * LL(node *T)
{
T=rotateright(T);
return(T);
}
node * LR(node *T)
{
T->left=rotateleft(T->left);
T=rotateright(T);
return(T);
}
node * RL(node *T)
{
T->right=rotateright(T->right);
T=rotateleft(T);
return(T);
}
int BF(node *T)
{
int lh,rh;
if(T==NULL)
return(0);
if(T->left==NULL)
lh=0;
else
lh=1+T->left->ht;
if(T->right==NULL)
rh=0;
else
rh=1+T->right->ht;
return(lh-rh);
}
void preorder(node *T)
{
if(T!=NULL)
{
printf("%d(Bf=%d)",T->data,BF(T));
preorder(T->left);
preorder(T->right);
}}
void inorder(node *T)
{
if(T!=NULL)
{
inorder(T->left);
printf("%d(Bf=%d)",T->data,BF(T));
inorder(T->right);
}
}
OUTPUT :
1) Create:
2) Insert:
3) Delete:
4) Print:
5) Quit:
Enter Your Choice:1
Enter no. of elements:4
Enter tree data:7 12 4 9
1)Create:
2) Insert:
3) Delete:
4) Print:
5) Quit:
Enter Your Choice:4
Preorder-sequence:
7(Bf=-1)4(Bf=0)12(Bf=1)9(Bf=0)
Inorder-sequence:
4(Bf=0)7(Bf=-1)9(Bf=0)12(Bf=1)
1) Create:
2) Insert:
3) Delete:
4) Print:
5) Quit:
Enter Your Choice:3
Enter a data:7
1)Create:
2) Insert:
3) Delete:
4) Print:
5) Quit:
Enter Your Choice:4
Preorder-sequence:
9(Bf=0)4(Bf=0)12(Bf=0)
Inorder-sequence:
4(Bf=0)9(Bf=0)12(Bf=0)
1) Create:
2) Insert:
3) Delete:
4) Print:
5) Quit:
Enter Your Choice:5
RESULT :
Thus the C program for the concept of AVL trees was implemented successfully.
IMPLEMENTATION OF HEAPS USING PRIORITY QUEUES
EX NO : 08
AIM :
To write a C program to implement the heaps using priority queues.
ALGORITHM :
PROGRAM :
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define MAX 10
Int arr[MAX];
int n;
void insert(int num)
{
if(n<MAX)
{
arr[n]=num;
n++;
}
else
printf(―\n array is full‖);
}
void makeheap()
{
for(int i=1;i<n;i++)
{
int val=arr[i];
int j=I;
int f=(j-1)/2;
while(j>0&&arr[f]<val)
{
arr[j]=arr[f];
j=f;
f=(j-1)/2;
}
arr[j]=val;
}
}
void display()
{
printf(―\n‖);
for(int i=0;i<n;i++)
printf(―%d‖,arr[i]);
}
int main()
{
insert(14);
insert(12);
insert(9);
insert(8);
insert(7);
insert(10);
insert(18);
printf(―\n the elements are‖);
display();
makeheap();
printf(―\n heapfied‖);
display();
return 0;
}
OUTPUT :
RESULT :
Thus the C program for the concept of heap using priority queues was
implemented successfully.
IMPLEMENTAION OF DIJKSTRA’S ALGORITHM
EX NO : 9
AIM:
To Implement the concept of Dijkstra‘s Algorithm
ALGORITHM:
PROGRAM:
#include <limits.h>
#include <stdio.h>
#define V 9
int minDistance(int dist[], bool sptSet[]) {
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++)
if (sptSet[v] == false && dist[v] <= min)
min = dist[v], min_index = v ;
return min_index; }
int printSolution(int dist[], int n) {
printf("Vertex Distance from Source\n");
for (int i = 0; i < V; i++)
printf("%d \t %d\n", i, dist[i]); }
void dijkstra(int graph[V][V], int src) {
int dist[V];
bool sptSet[V];
for (int i = 0; i < V; i++)
dist[i] = INT_MAX, sptSet[i] = false;
dist[src] = 0;
for (int count = 0; count < V - 1; count++) {
int u = minDistance(dist, sptSet);
sptSet[u] = true;
for (int v = 0; v < V; v++)
if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX && dist[u] + graph[u][v] < dist[v])
dist[v] = dist[u] + graph[u][v]; }
printSolution(dist, V); }
int main() {
int graph[V][V] = { { 0, 6, 0, 0, 0, 0, 0, 8, 0 },
{ 6, 0, 8, 0, 0, 0, 0, 13, 0 },
{ 0, 8, 0, 7, 0, 6, 0, 0, 2 },
{ 0, 0, 7, 0, 9, 14, 0, 0, 0 },
{ 0, 0, 0, 9, 0, 10, 0, 0, 0 },
{ 0, 0, 6, 14, 10, 0, 2, 0, 0 },
{ 0, 0, 0, 0, 0, 2, 0, 1, 6 },
{ 8, 13, 0, 0, 0, 0, 1, 0, 7 },
{ 0, 0, 2, 0, 0, 0, 6, 7, 0 } };
dijkstra(graph, 0);
return 0; }
Output
Vertex Distance from Source
00
16
2 14
3 21
4 21
5 11
69
78
8 15
RESULT :
Thus the C program for the concept of Dijkstra‘s Algorithm was implemented
successfully.
IMPLEMENTAION OF PRIM’S ALGORITHM
EX NO : 10
AIM:
To implement the concept of Prim‘s Algorithm
ALGORITHM:
Step 1: Start the program & Read the input nodes. Initially node is empty.
Step 2: Create edge list of given graph, with their weights.
Step 3: Draw all nodes to create skeleton for spanning tree.
Step 4: Select an edge with lowest weight and add it to skeleton and delete edge from edge list.
Step 5: Add other edges. While adding an edge take care that the one end of the edge should
always be in the skeleton tree and its cost should be minimum.
Step 6: Repeat step 5 until n-1 edges are added.
Step 7: Return & Stop the Program.
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
#define infinity 9999
#define MAX 20
int G[MAX][MAX],spanning[MAX][MAX],n;
int prims();
int main()
{
int i,j,total_cost;
printf("Enter no. of vertices:");
scanf("%d",&n);
printf("\nEnter the adjacency matrix:\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
total_cost=prims();
printf("\nspanning tree matrix:\n");
for(i=0;i<n;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("%d\t",spanning[i][j]); }
printf("\n\nTotal cost of spanning tree=%d",total_cost);
return 0; }
int prims()
{
int cost[MAX][MAX];
int u,v,min_distance,distance[MAX],from[MAX];
int visited[MAX],no_of_edges,i,min_cost,j;
//create cost[][] matrix,spanning[][]
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
if(G[i][j]==0)
cost[i][j]=infinity;
else
cost[i][j]=G[i][j];
spanning[i][j]=0; }
//initialise visited[],distance[] and from[]
distance[0]=0;
visited[0]=1;
for(i=1;i<n;i++)
{
distance[i]=cost[0][i];
from[i]=0;
visited[i]=0; }
min_cost=0; //cost of spanning tree
no_of_edges=n-1; //no. of edges to be added
while(no_of_edges>0)
{
//find the vertex at minimum distance from the tree
min_distance=infinity;
for(i=1;i<n;i++)
if(visited[i]==0&&distance[i]<min_distance)
{ v=i;
min_distance=distance[i]; }
u=from[v];
//insert the edge in spanning tree
spanning[u][v]=distance[v];
spanning[v][u]=distance[v];
no_of_edges--;
visited[v]=1;
//updated the distance[] array
for(i=1;i<n;i++)
if(visited[i]==0&&cost[i][v]<distance[i])
{ distance[i]=cost[i][v];
from[i]=v; }
min_cost=min_cost+cost[u][v]; }
return(min_cost); }
OUTPUT:
0 3 1 0 0 0
3 0 0 0 3 0
1 0 0 0 0 4
0 0 0 0 0 2
0 3 0 0 0 0
0 0 4 2 0 0
RESULT :
Thus the C program for the concept of prim‘s Algorithm was implemented
successfully.
IMPLEMENTAION OF LINEAR SEARCH
EX NO : 11(A)
AIM :
To Write a C program to implement the concept of linear search algorithms.
ALGORITHM :
PROGRAM:
#include<stdio.h>
#include<conio.h>
void main() {
int arr[20];
int i,size,sech;
printf("\n\t-- Linear Search --\n\n");
printf("Enter total no. of elements : ");
scanf("%d",&size);
for(i=0; i<size; i++) {
printf("Enter %d element : ",i+1);
scanf("%d",&arr[i]); }
printf("Enter the element to be searched: ");
scanf("%d",&sech);
for(i=0; i<size; i++) {
if(sech==arr[i]) {
printf("Element exits in the list at position : %d",i+1);
break; } } getch(); }
OUTPUT:
RESULT :
Thus the C program for the concept of prim‘s Algorithm was implemented
successfully.
EX NO : 11(B) IMPLEMENTAION OF BINARY SEARCH
AIM :
To Write a C program to implement the concept of Binary search algorithms.
ALGORITHM :
Step 1: Start the program & Read the input Parameters inital_value , end_value
Step 2: Find the middle element of array. using ,
middle = initial_value + end_value / 2 ;
Step 3: If middle = element, return ‗element found‘ and index.
Step 4: if middle > element, call the function with end_value = middle - 1 .
Step 5: if middle < element, call the function with start_value = middle + 1 .
Step 6: Exit & Stop the program.
PROGRAM:
#include <stdio.h>
int iterativeBinarySearch(int array[], int start_index, int end_index, int element){
while (start_index <= end_index){
int middle = start_index + (end_index- start_index )/2;
if (array[middle] == element)
return middle;
if (array[middle] < element)
start_index = middle + 1;
else
end_index = middle - 1;
}
return -1;
}
int main(void){
int array[] = {1, 4, 7, 9, 16, 56, 70};
int n = 7;
int element = 16;
int found_index = iterativeBinarySearch(array, 0, n-1, element);
if(found_index == -1 ) {
printf("Element not found in the array ");
}
else {
printf("Element found at index : %d",found_index);
}
return 0;
}
OUTPUT:
Element found at index: 3
RESULT :
Thus the C program for the concept of Binary search Algorithm was implemented
successfully.
IMPLEMENTAION OF INSERTION SORTING
EX NO : 12 (A)
AIM :
To Write a C program to implement the concept of Insertion sorting Algorithms.
ALGORITHM :
PROGRAM :
#include<stdio.h>
#iclude<conio.h>
void main()
{
int A[10], n, I;
void Insert_sort(int A[10], int n);
clrscr();
printf(―\n\t\t Insertion sort:‖);
printf(―\n How many elements are there?‖);
scanf(―%d‖,&n);
printf(―\n Enter the elements\n‖);
for(i=0;i<n;i++)
scanf(―%d‖,&A[i]);
Insert_sort(A,n);
getch();
}
void Insert_sort(int A[10], int n)
{
int I,j,temp;
for(i=1;i<=n;i++)
{
temp=A[i];
i=i-1;
while((j>=0)&&(A[j]>temp))
{
A[j+1]=A[j];
i=j-1;
}
A[j+1]=temp;
}
printf(―\n the sorted list of elements is..\n‖)l
for(i=0;i<n;i++)
printf(―\n%d‖, A[i]);
}
OUTPUT:
Insertion sort
How many elements are there? 5
Ener the elements
3020104050
The sorted list of elements is…
1020304050
RESULT :
Thus the C program for the concept of Insertion sorting Algorithm was
implemented successfully.
EX NO : 12 (B) IMPLEMENTAION OF SELECTION SORTING
AIM :
To Write a C program to implement the concept of selection sorting Algorithms.
ALGORITHM :
PROGRAM:
#include <stdio.h>
int main() {
int arr[10]={6,12,0,18,11,99,55,45,34,2};
int n=10;
int i, j, position, swap;
for (i = 0; i < (n - 1); i++) {
position = i;
for (j = i + 1; j < n; j++) {
if (arr[position] > arr[j])
position = j; }
if (position != i) {
swap = arr[i];
arr[i] = arr[position];
arr[position] = swap; } }
for (i = 0; i < n; i++)
printf("%d\t", arr[i]);
return 0; }
OUTPUT:
0 2 6 11 12 18 34 45 55 99
RESULT :
Thus the C program for the concept of Selection sorting Algorithm was
implemented successfully.
EX NO : 13 IMPLEMENTAION OF MERGE SORTING
AIM :
To Write a C program to implement the concept of Merge sorting Algorithms.
ALGORITHM :
PROGRAM:
#include<stdio.h>
#include<conio.h>
void merge(int [],int ,int ,int );
void part(int [],int ,int );
void main(){
int arr[30];
int i,size;
printf("\n\t------- Merge sorting method ------- \n\n");
printf("Enter total no. of elements : ");
scanf("%d",&size);
for(i=0; i<size; i++){
printf("Enter %d element : ",i+1);
scanf("%d",&arr[i]);
}
part(arr,0,size-1);
printf("\n\t------- Merge sorted elements ------- \n\n");
for(i=0; i<size; i++)
printf("%d ",arr[i]);
getch();
}
void part(int arr[],int min,int max){
int mid;
if(min<max){
mid=(min+max)/2;
part(arr,min,mid);
part(arr,mid+1,max);
merge(arr,min,mid,max);}}
void merge(int arr[],int min,int mid,int max){
int tmp[30];
int i,j,k,m;
j=min;
m=mid+1;
for(i=min; j<=mid && m<=max ; i++){
if(arr[j]<=arr[m]){
tmp[i]=arr[j];
j++; }
else{
tmp[i]=arr[m];
m++; } }
if(j>mid){
for(k=m; k<=max; k++){
tmp[i]=arr[k];
i++; } }
else{
for(k=j; k<=mid; k++){
tmp[i]=arr[k];
i++; } }
for(k=min; k<=max; k++)
arr[k]=tmp[k]; }
OUTPUT:
11 13 35 43 48 75 99 100 155
RESULT :
Thus the C program for the concept of Merge sorting algorithms was
implemented successfully.
IMPLEMENTAION OF OPEN ADDRESSING ( LINEAR PROBING AND
EX NO : 14
QUADRATIC PROBING )
AIM :
To Write a C program to implement the concept of open Addressing using linear and
Quadratic probing method.
ALGORITHM :
Step 1: Start the program & Read the input Parameters. Create an array of structure (i.e a hash
table).
Step 2. Take a key and a value to be stored in hash table as input.
Step 3. Corresponding to the key, an index will be generated i.e every key is stored in a
particular array index.
Step 4. Using the generated index, access the data located in that array index.
Step 5. In case of absence of data, create one and insert the data item (key and value) into it and
increment the size of hash table.
Step 6. In case the data exists, probe through the subsequent elements (looping back if necessary)
for free space to insert new data item. (Note: This probing will continue until we reach the same
element again (from where we began probing)
Step 7. To display all the elements of hash table, element at each index is accessed (via for loop).
Step 8. To remove a key from hash table, we will first calculate its index and delete it if key
matches, else probe through elements until we find key or an empty space where not a single
data has been entered (means data does not exist in the hash table).
Step 9. Exit & Stop the program
PROGRAM:
#include <stdio.h>
#include <conio.h>
int tsize;
//-------LINEAR PROBING-------
int rehashl(int key)
{
int i ;
i = (key+1)%tsize ;
return i ;
}
//-------QUADRATIC PROBING-------
int rehashq(int key, int j)
{
int i ;
i = (key+(j*j))%tsize ;
return i ;
}
void main()
{
int key,arr[20],hash[20],i,n,s,op,j,k ;
clrscr() ;
printf ("Enter the size of the hash table: ");
scanf ("%d",&tsize);
for (i=0;i<tsize;i++)
hash[i]=-1 ;
do
{
printf("\n\n1.Linear Probing\n2.Quadratic Probing \n3.Exit \nEnter
your option: ");
scanf("%d",&op);
switch(op)
{
case 1:
for (i=0;i<tsize;i++)
hash[i]=-1 ;
for(k=0;k<n;k++)
{
key=arr[k] ;
i = hasht(key);
while (hash[i]!=-1)
{
i = rehashl(i);
}
hash[i]=key ;
}
printf("\nThe elements in the array are: ");
for (i=0;i<tsize;i++)
{
printf("\n Element at position %d: %d",i,hash[i]);
}
break ;
case 2:
for (i=0;i<tsize;i++)
hash[i]=-1 ;
for(k=0;k<n;k++)
{
j=1;
key=arr[k] ;
i = hasht(key);
while (hash[i]!=-1)
{
i = rehashq(i,j);
j++ ;
}
hash[i]=key;
}
printf("\nThe elements in the array are: ");
for (i=0;i<tsize;i++)
{
printf("\n Element at position %d: %d",i,hash[i];
} break; }
}while(op!=3);
getch() ; }
OUTPUT:
1.Linear Probing
2.Quadratic Probing
3.Exit
Enter your option: 1
1.Linear Probing
2.Quadratic Probing
3.Exit
Enter your option: 2
1.Linear Probing
2.Quadratic Probing
3.Exit
Enter your option: 3
RESULT :
Thus the C program for the concept of open Addressing using linear probing and
Quadratic probing technique was implemented successfully.