0% found this document useful (0 votes)
32 views

CS3311 - Data Structures Laboratory

DS lab manual

Uploaded by

hgthtyhy5
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

CS3311 - Data Structures Laboratory

DS lab manual

Uploaded by

hgthtyhy5
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

ARULMURUGAN COLLEGE OF ENGINEERING

(Approved by AICTE, New Delhi and Affiliated to Anna University, Chennai & ISO 9001:2015 Certified
Institution)

THENNILAI, KARUR - 639 206.

DEPARTMENT OF COMPUTER SCIENCE


ENGINEERING

CS3311 - DATA STRUCTURES LABORATORY

III YEAR / V SEMESTER

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

Subject Code & Name

Certified that this is a bonafide record of work done by the above student
during the year 20 - 20

Staff in-charge Head of the Department

Submitted for the University Practical Examination held on

Internal Examiner External Examiner


INDEX

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:

Step 1: Start the program


Step2: Initially top = -1;
Step 3: push operation increases top by one and writes pushed element to storage[top];
Step 4: pop operation checks that top is not equal to -1 and decreases top variableby 1;
Step 5: display operation checks that top is not equal to -1 and returns storage[top];
Step 6: Stop.

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:

Thus a C program for Stack using array was implemented successfully.


ARRAY IMPLEMENTATION OF QUEUE ADTS
EX NO:1(B)

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

Read the element to be Inserted ?100


Press a Key to Continue . . .
### Queue Operations using Arrays###
Press 1-Insert, 2-Delete,3-Display,4-Exit
Your option ? 1

Read the element to be Inserted ?200


Press a Key to Continue . . .
### Queue Operations using Arrays###
Press 1-Insert, 2-Delete,3-Display,4-Exit
Your option ? 1

Read the element to be Inserted ?300


Press a Key to Continue . . .
### Queue Operations using Arrays###
Press 1-Insert, 2-Delete,3-Display,4-Exit
Your option ? 2

Deleted Element is 100


Press a Key to Continue . . .
### Queue Operations using Arrays###
Press 1-Insert, 2-Delete,3-Display,4-Exit
Your option ? 3

Status of Queue
Front->200 300 <-Rear
Press a Key to Continue . . .

RESULT:

Thus a C program for Queue using array was implemented successfully.


EX NO : 1(C) ARRAY IMPLEMENTATION OF CIRCULAR QUEUE ADTs.

AIM:

To write a C program to implement the array implementation of circular queue ADTs/.

ALGORITHM:

Step 1: Start the Program & Read the input data element

Step 2: Two pointers FRONT and REAR


FRONT track the first element of the queue
REAR track the last elements of the queue
initially, set value of FRONT and REAR to -1

Step 3: Enqueue Operation:


check if the queue is full
for the first element, set value of FRONT to 0
circularly increase the REAR index by 1 (i.e. if the rear reaches the end, next it would be at
the start of the queue)
add the new element in the position pointed to by REAR

Step 4: Dequeue Operation:


check if the queue is empty
return the value pointed by FRONT
circularly increase the FRONT index by 1
for the last element, reset the values

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:

To write a C program to implement the Singly linked list.

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 3: A Node contains two parts


item - item contains data item (it may be a number, string or any object like
structure).
next - next contains address of the next node.

Step 4: Last Node of the linked list contains NULL in the next part.

PROGRAM:
#include <stdio.h>
#include <stdlib.h>

//Self referential structure to create node.


typedef struct tmp
{
int item;
struct tmp * next;
}Node;

//structure for create linked list.


typedef struct
{
Node * head;
Node * tail;

}List;

//Initialize List
void initList(List * lp)
{
lp->head = NULL;
lp->tail = NULL;
}

//Create node and return reference of it.


Node * createNode(int item)
{
Node * nNode;

nNode = (Node *) malloc(sizeof(Node));

nNode->item = item;
nNode->next = NULL;

return nNode;
}

//Add new item at the end of list.


void addAtTail(List * lp,int item)
{
Node * node;
node = createNode(item);

//if list is empty.


if(lp->head == NULL)
{
lp->head = node;
lp->tail = node;
}
else
{
lp->tail->next = node;
lp->tail = lp->tail->next;
}
}

//Delete item from the end of list.


int delFromTail(List * lp)
{
Node * temp;
int i = 0;

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

//Add new item at begning of the list.


void addAtHead(List * lp,int item)
{
Node * node;
node = createNode(item);

//if list is empty.


if(lp->head == NULL)
{
lp->head = node;
lp->tail = node;
}
else
{
node->next = lp->head;
lp->head = node;
}
}

//Delete item from Start of list.


int delFromHead(List * lp)
{
int item = 0;

if(lp->head == NULL)
{
printf("\nList is Empty ...");
return -1;
}
else
{
item = lp->head->item;
lp->head = lp->head->next;
}
return item;
}

//To print list from start to end of the list.


void printList(List *lp)
{
Node * node;

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

//Main function to execute program.


int main()
{
List *lp;

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:

| 00040 |--->| 00030 |--->| 00010 |--->| 00020 |

Deleted item is : 20
List:

| 00040 |--->| 00030 |--->| 00010 |

Deleted item is : 40
List:

| 00030 |--->| 00010 |

RESULT:

Thus a C program for Singly linked list was implemented successfully.


LINKED LIST IMPLEMENTATION OF STACK ADTS
EX NO : 3(A)

AIM:

To write a C program to implement Stack operations such as push, pop and display using
linked list.

ALGORITHM:

Step 1: Start the program


Step 2: push operation inserts an element at the front.
Step 4: pop operation deletes an element at the front of the list;
Step 5: display operation displays all the elements in the list.
Step 6: Stop the program

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:

To write a C program to implement Queue operations such as enqueue, dequeue and


display using linked list.

ALGORITHM:

Step 1: Start program


Step 2: enqueue operation inserts an element at the rear of the list.
Step 4: dequeue operation deletes an element at the front of the list.
Step 5: display operation display all the element in the list.
Step 6: Stop the program

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

Step 1: Start the program


Step 2: Declare all the variables in the polynomial
Step 3: Enter the first polynomial
Step 4: Enter the second polynomial
Step 5: Polyadd() is used to realize the addition algorithm of two polynomials;
Step 6: Polysub() is used to realize the subtraction of two polynomials;
Step 7: To print the addition & subtraction of polynomial
Step 8: Stop the program.

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;

printf("(Please enter 1 for addition polynomial and 0 for subtraction


polynomial)\n");
scanf("%d",&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

Polynomial 1 is : (3.0x^4) + (2.0x^2)

Polynomial 2 is : (4.0x^5) + (4.0x^3) + (2.0x^3) + (6.0x^3) + (2.0x^1)

Added polynomial is : (4.0x^5) + (3.0x^4) + (4.0x^3) + (2.0x^3) + (6.0x^3) + (2.

0x^2) + (2.0x^1)

Subtraction polynomial is : (12.0x^9) - (12.0x^7) - (6.0x^7) - (18.0x^7) - (8.0x^

7) - (6.0x^5) - (8.0x^5) - (4.0x^5) - (12.0x^5) - (4.0x^3)

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

Step 1: Start the process.


Step 2: Initialize and declare variables.
Step 3: Construct the Tree
Step 4: Data values are given which we call a key and abinary search tree
Step 5: To search for the key in the given binary search tree, start with the root node and
Compare the key with the data value of the root node. If they match, return the
root pointer.
Step 6: If the key is less than the data value of the root node, repeat the process by using
the left subtree.
Step 7: Otherwise, repeat the same process with the right sub tree until either a match is
found or the subtree under consideration becomes an empty tree.
Step 8: Stop the process.

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:

Enter the expression : a+b*c

a b c * +

Enter the expression : (a+b)*c+(d-a)

a b + c * d a - +

Enter the expression : ((4+8)(6-5))/((3-2)(2+2))


4 8 + 6 5 - 3 2 - 2 2 + /

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

Step 1: Start the process.


Step 2: Initialize and declare variables.
Step 3: Construct the Tree
Step 4: Data values are given which we call a key and abinary search tree
Step 5: To search for the key in the given binary search tree, start with the root node and
Compare the key with the data value of the root node. If they match, return the
root pointer.
Step 6: If the key is less than the data value of the root node, repeat the process by using
the left subtree.
Step 7: Otherwise, repeat the same process with the right sub tree until either a match is
found or the subtree under consideration becomes an empty tree.
Step 8: Stop the process.

PROGRAM :-

#include <stdio .h>


#include<conio.h>
#include<process.h>
#include<malloc.h>
struct tree
int data;
sruct tree *lchild;
struct tree * rchild:
}*t,*temp;
int element,-
void inorder struct tree *i;
void preorder struct tree *l ;
void postorder struct tree *r ;
sruct tree * create(struct tree ‗2 int);
struct tree * find(struct tree *, int);
struct tree * insert(struct tree *, int);
struct tree * del(struct tree *, int);
struct tree * findmin(struct tree *l);
struct tree * findmax(struct tree * r);
void main[)
{
int Ch;
do
{
printf("\n\t\t\tBlNARY SEARCH TREE");
printf("\nMain Menu\n");
printf("\n1.Create\n2.lnsert\n3.Delete\n4.Find\n5.FindMin\n6.FindMax");
printf("\n7.Inorder\n8.Preorder\n9.Postorder\n10.Exit\n"];
printf(‖\nEnter ur choice :");
scanf("%d‖,&ch);
switch(ch)
{
case 1:printf("\nEnter the data: " );
scanf(―%d―,&elernent);
t=create(t,element);
inorder();
break;
case 2:printf( ―\nEnter the data: " );
scanf(―%d‖,&element);
t=insert(t,element);
inorder();
break;
case 3: printf(―\nEnter the data: " ),
scanf("%d―,&element);
t=del(t,element):
inorder();
break;
case 4: printf(―\nEnter the data: " );
scahf{"%d―,&elernent];
temp=find(t,element);
if(temp->data==element]
printf(―Element %d is at %td‖,element,ternp);
else
printft―\nElement is not found");
break,
case 5: temp=findmin(t);
printf(―mM ax element=% d‖ ,ternp->data) ;
break;
case 6: temp=findmax(t);
printft―\nMax element=%d",ternp- >data);
break;
case 7: inorder();
break;
case 8: preorder();
break;
case 9: postorder();
break;
case 10: exit();
}while{ch<=10):
struct tree * create(struct tree *t, int element)
{
t=(struct tree *)malloc(sizeof(struct tree);
t- >data=elernent;
t- >lchild=NULL;
t- >rchild=NU L L ;
return t;
}
struct tree * find(struct tree *t, int element)
{
If(t==NU L L )
return NULL;
if(element<t- >data)
return find(t->lchild elernent);
else
if ( element>t- >data)
return find(t->rchild.elernent);
else
return t;
struct tree *findmin(struct tree *t)
{
if {t==NU L L )
return NULL;
else
if(t—>lchild==NULL)
return t;
else
return(findrnin(t- >lchild)
}
}
struct tree *findmaxt (struct tree *t)
{
if(t! =NULL)
{
while(t—>rchild =NULL)
t=t->rchild;
}
return t;
}
struct tree *insert (struct tree *t,int element)
{
if(t==NULL)
{
t=(struct tree *)rnalloc(sizeof{struct head);
t- >data =element;
t->lchild=NULL:
t~ >rchild=NULL;
return t;
}
else
{
if { element<t- >data)
{
t- >lchild=insert(t- >lchild,element) ;
else
if (element>t- >data)
{
t- >rchild=insert(t- >rchild,elernent);
else
if (element==t- >data)
{
printf(― element already present" );
return t;
}
struct tree * del(struct tree *t, int element)
{
if (t==NU L L )
printf(‖elernent not found\n");
else
if (element<t- >data)
t- >lchild=del[t~ >lchild,element);
else
if { element->t~ >data)
t- >rchild=del(t- >rchild,elernent) ;
else
if(t- >lchild&&t— >rchild)
{
temp=findmin(t~ >lchild};
t- >data=temp~ >data:
t- >rchild=del(t- >r‗child,t- >data);
else
temp=t;
if(t->lchild==NULL)
t=t- >rchild;
else
if(t- >rChild==NULL)
t=t- >lchild;
free(temp) ;
return E;
void inorder(struct tree * t)
{
if (t==NULL )
return;
else
{
Inorder(t >1 Child) ,-
printf("\t%d",t— >data);
inorder(t- >rchild);
}
}
void preorder(struct tree * t)
{
if {t==NULL )
return:
else
{
printf("\t%d",t->data};
preorder(t- >lchild) ;
preorder(t- >rchild) ;
} void postorder(struct tree *t) {
if{t==NULL)
return;
else
{
postorder(t->lchild};
postorder(t- >rchild}:
printf("\t%d",t->data);
}}

OUTPUT:-

BINARY SEARCH TREE


Main Menu
1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit
Enter ur choice :1
Enter the data: 10
10

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

BINARY SEARCH TREE


Main Menu
1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindM ax
7.1norder
8.Preorder
9.Postorder
10.Exit
Enter ur choice :2
Enter the data:25
10 20 25 30

BINARY SEARCH TREE


Main Menu
1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
B.Preorder
9.Postorder
10.Exit
Enter ur choice :4
Enter the data:25
Element 25 is at 2216

BINA RY SEA RCH 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 :5
Max element=10

BINARY SEARCH TREE


Main Menu
1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit
Enter ur choice :6
Max element=30

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
10 20 25 30

BINARY SEARCH TREE


Main Menu
1.Create
2.1nsert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit
Enter ur choice :8
10 20 30 25
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 :9
25 30 20 10

BINARY SEARCH TREE


Main Menu
1.Create
2.Insert
3.Delete
4.Find
5.FindMin
6.FindMax
7.Inorder
8.Preorder
9.Postorder
10.Exit
Enter ur choice :3
Enter the data: 10
20 25 30

BINARY SEARCH TREE


Main Menu
1.Create
2 .Insert
3.Delete
4.Find
5.FindMin
6.FindM ax
7.inorder
8.Preortder
9.Postorder
10.Exit
Enter ur choice :10

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 :

Step 1: Start the program


Step 2: Declare all the variables that are used for tree
Step 3: The height of the two child subtree of any node differ by at most one.
Step 4: If they differ by more than one, re-balancing is done
Step 5: Step 3 and Step 4 is the property of tree
Step 6: Stop the program

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 :

Step 1 : Start the program.


Step 2 : Define the function insert, which will be used for insert the element
Step 3: Create make heap to create and check the variable
Step 4 : Display the element
Step 5 : Stop the program

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 :

The Elements are…


14 12 9 8 7 10 18
Heapified
18 12 14 8 7 9 10

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:

Step 1: Star the program.


Step 2: Read the input vertices & all the vertices in graph. Initially visited_ vertices is zero.
Step 3: Create a set short Path to store vertices that come in the way of the shortest path tree.
Step 4: Initialize all distance values as INFINITE and assign distance values as 0 for source
vertex so that it is picked first.
Step 5: Loop until all vertices of the graph are in the short Path.
Step 6: Stop the program.

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:

Enter no. of vertices:6


Enter the adjacency matrix:
03160 0
30503 0
15056 4
60500 2
03600 6
00426 0

spanning tree matrix:

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

Total cost of spanning tree=13

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 :

Step 1: Start the program.


Step 2: Declare all the variables to perform the operations
Step 3: To implement the algorithm for linear search
Step 4: Stop the program

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:

Enter total no. of elements : 5


Enter 1 element : 10
Enter 2 element : 4
Enter 3 element : 2
Enter 4 element : 17
Enter 5 element : 100
Enter the element to be searched: 17
Element exits in the list at position : 4

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 :

Step1: Start the program & Read the input Parameters.


Step 2: If it is the first element, it is already sorted. return 1;
Step 3: Pick next element
Step 4: Compare with all elements in the sorted sub-list
Step 5: Shift all the elements in the sorted sub-list that is greater than the
value to be sorted
Step 6: Insert the value
Step 7: Repeat until list is sorted
Step 8: Exit & Stop the program.

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 :

Step1: Start the program & Read the input Parameters.


Step 2: Set minimum to the first location.
Step 3: Swap the minimum element in the array.
Step 4: Assign the second element as min. & Repeat until list is sorted
Step 5: Exit & Stop the program.

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 :

Step1: Start the program & Read the input Parameters.


Step 2: Find the middle index of the array.
Middle = 1 + (last – first)/2
Step 3: Divide the array from the middle.
Step 4: Call merge sort for the first half of the array
MergeSort(array, first, middle)
Step 5: Merge the two sorted halves into a single sorted array.
Step 6: Call merge sort for the second half of the array.
MergeSort(array, middle+1, last)
Step 7: Exit & Stop the program.

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:

------- Merge sorting method -------

Enter total no. of elements : 9


Enter 1 element : 100
Enter 2 element : 99
Enter 3 element : 75
Enter 4 element : 155
Enter 5 element : 11
Enter 6 element : 43
Enter 7 element : 13
Enter 8 element : 35
Enter 9 element : 48

------- Merge sorted elements -------

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:

/* HASHING - LINEAR AND QUADRATIC PROBING */

#include <stdio.h>
#include <conio.h>
int tsize;

int hasht(int key)


{
int i ;
i = key%tsize ;
return i;
}

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

printf ("\nEnter the number of elements: ");


scanf ("%d",&n);

for (i=0;i<tsize;i++)
hash[i]=-1 ;

printf ("Enter Elements: ");


for (i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}

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:

Enter the size of the hash table: 10

Enter the number of elements: 8


Enter Elements: 72 27 36 24 63 81 92 101

1.Linear Probing
2.Quadratic Probing
3.Exit
Enter your option: 1

The elements in the array are:


Element at position 0: -1
Element at position 1: 81
Element at position 2: 72
Element at position 3: 63
Element at position 4: 24
Element at position 5: 92
Element at position 6: 36
Element at position 7: 27
Element at position 8: 101
Element at position 9: -1

1.Linear Probing
2.Quadratic Probing
3.Exit
Enter your option: 2

The elements in the array are:


Element at position 0: -1
Element at position 1: 81
Element at position 2: 72
Element at position 3: 63
Element at position 4: 24
Element at position 5: 101
Element at position 6: 36
Element at position 7: 27
Element at position 8: 92
Element at position 9: -1

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.

You might also like