Csbs Dsa Lab
Csbs Dsa Lab
ISO 9001:2015 Certified Institution, Accredited by NBA (BME, CSE, ECE, EEE, IT & MECH),
Accredited by NAAC with ‘A’ Grade (3.49 / 4 scale)
#42, Avadi - Vel Tech Road, Avadi, Chennai- 600062, Tamil Nadu, India.
NAME :
REGISTER NO :
ROLLNO :
YEAR : I
SEMESTER : II
Vision
➢ To impart world class quality education in the field of Business Systems with computer orientation through
sustained research and produce technical manpower with good managerial behavior to compete the global
standards.
Mission
➢ To provide effective teaching & learning in the field of business systems and to promote innovative thinking for
design and development of business products to fulfill the global demands and standards
➢ To impart practical exposure by practice with recent trends in industry and to provide an opportunity to develop
software products for inter-disciplinary business problems
➢ To provide value based Technical education for empowering graduates through lifelong learning and socially
responsible.
Approved by AICTE, Affiliated to Anna University, Chennai.
ISO 9001:2015 Certified Institution, Accredited by NBA (BME, CSE, ECE, EEE, IT & MECH),
Accredited by NAAC with ‘A’ Grade (3.49 / 4 scale)
#42, Avadi - Vel Tech Road, Avadi, Chennai- 600062, Tamil Nadu, India.
CERTIFICATE
Submitted for the End Semester Practical Examination held on ......... at VEL TECH MULTI
TECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE, No.42, AVADI –
VEL TECHROAD, AVADI, CHENNAI- 600062.
Signature of Examiners
Date:………………
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
Train the graduates with the potential of strong knowledge in the respective
PEO1 field and to create innovative multidisciplinary solutions for challenges in
the society
Groom the engineers to understand, analyse different nature of data and use
PEO2 Machine Learning techniques to develop software systems with varying
complexity for data intensive applications
PSO1 To impart theoretical knowledge in the respective field along with recent
industrial tools and techniques to solve societal problems
Apply the core competency obtained in the field of Machine Learning for
PSO2
analysis, design and development of computing systems for multi-
disciplinary problems
Problem Analysis: Identify, formulate, review research literature and analyze complex
PO2 engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences.
Design / Development of solutions: Design solutions for complex engineering problems and
PO3 design system components or processes that meet specified needs with appropriate consideration
for public health and safety, cultural, societal, and environmental considerations.
Conduct Investigations of Complex Problems: Use research-based knowledge and research
PO4 methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.
Modern tool usage: Create, select, and apply appropriate techniques, resources, and
PO5 modern engineering and IT tools including prediction and modeling to complex engineering
activities with an understanding of the limitations.
The Engineer and Society: Apply reasoning informed by the contextual knowledge to assess
PO6 societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to
the professional engineering practice.
Environment and sustainability: Understand the impact of the professional engineering
PO7 solutions in societal and environmental contexts, and demonstrate the knowledge of, and need
for sustainable development.
Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
PO8 norms of the engineering practice.
Individual and team work: Function effectively as an individual, and as a member or leader
PO9 in diverse teams, and in multidisciplinary settings.
PO12 Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
COURSE OUTCOME:
Course
CO Statements
Outcome
CO1 Implement Linear data structure algorithms including Queues and lists
Course
PSO1
PSO2
PSO3
PO10
PO11
PO12
PO 1
PO 2
PO 3
PO 4
PO 5
PO 6
PO 7
PO 8
PO 9
Outcome
- 2 - 2 -
CO1 3 3 2 2 - - - 3 2 2
- 2 - 1 -
CO2 3 3 2 2 - - - 3 2 2
- 2 - 2 -
CO3 3 3 2 2 - - - 3 2 2
-
CO 3 3 2 2 - - - - 2 - 2 3 2 2
S.NO FACULTY
DATE LIST OF EXPERIMENTS PAGE
SIGN
NO
1 ARRAY IMPLEMENTATION OF STACK, QUEUE
AND CIRCULAR QUEUE ADTS
2 IMPLEMENTATION OF SINGLY LINKED LIST
3 LINKED LIST IMPLEMENTATION OF STACK AND
LINEAR QUEUE ADTS
4 IMPLEMENTATION OF POLYNOMIAL
MANIPULATION USING LINKED LIST
5 IMPLEMENTATION OF CIRCULAR QUEUE
6 IMPLEMENTATION OF EVALUATING POSTFIX
EXPRESSIONS, INFIX TO POSTFIX CONVERSION
7 IMPLEMENTATION OF BINARY SEARCH TREES
8 IMPLEMENTATION OF AVL TREES
9 IMPLEMENTATION OF HEAPS USING PRIORITY
QUEUES
10 IMPLEMENTATION OF DIJKSTRA’S ALGORITHM
11 IMPLEMENTATION OF PRIM’S ALGORITHM
12 IMPLEMENTATION OF LINEAR SEARCH AND
BINARY SEARCH
13 IMPLEMENTATION OF INSERTION SORT AND
SELECTION SORT
14 IMPLEMENTATION OF MERGE SORT
15 IMPLEMENTATION OF OPEN ADDRESSING
(LINEAR PROBING AND QUADRATIC PROBING)
6
EX.NO: 1a ARRAY IMPLEMENTATION OF STACK
DATE:
AIM:
ALGORITHM :
Step1:Start
Step 2: Define a array stack of size max = 5
Step 3: Initialize top = -1
Step 4: Display a menu listing stack operations Step 5: Accept choice
Step 6: If choice = 1then
Step 7: If top < max -1
Step 8: Increment top
Step 11: If choice = 2 then
Step 13: If top < 0 then Print Stack
Step 14: Else , Display current top element
Step 15: Decrement top
Step 16: If choice = 3 then , Display stack elements starting from top
Step 17: Stop
PROGRAM :
#include<stdio.>
#include<conio.>
#define max 5
static int stack[max];
int top = -1;
void push(int x)
{
stack[++top] = x;
}
int pop()
{
return (stack[top--]);
}
void view()
{
int i;
if (top < 0)
printf("\n Stack Empty \n");
else
{
printf("\n Top-->");
for(i=top; i>=0; i--)
{
printf("%4d", stack[i]);
}
printf("\n");
}
}
7
Void main()
{
int ch=0, val;
clrscr();
while(ch != 4)
{
printf("\n STACK OPERATION \n");
printf("1.PUSH ");
printf("2.POP ");
printf("3.VIEW ");
printf("4.QUIT \n");
printf("Enter Choice : ");
scanf("%d", &ch);
switch(ch)
{
case 1:
if(top < max-1)
{
printf("\nEnter Stack element");
scanf("%d", &val);
push(val);
}
else
printf("\nStackOverflow\n");
break;
case 2:
if(top < 0)
printf("\n Stack Underflow \n");
else
{
val = pop();
printf("\n Popped element is %d\n", val);
}
break;
case 3:
view();
break;
case 4:
exit(0);
default:
printf("\n Invalid Choice \n");
}
}
}
8
OUTPUT :
STACK OPERATION
1.PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice : 1
Enter Stack element : 12
STACK OPERATION
1.PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice : 1
Enter Stack element : 23
STACK OPERATION
1.PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice : 1
Enter Stack element : 34
STACK OPERATION
1.PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice : 1
Enter Stack element : 45
STACK OPERATION
1.PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice : 3
Top--> 45 34 23
12
STACK OPERATION
1.PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice : 2
Popped element is
45 STACK
OPERATION
1.PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice :
3 Top--> 34
23 12
STACK OPERATION
1.PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice : 4
RESULT:
Thus push and pop operations of a stack was demonstrated using array
9
EX.NO: 1b ARRAY IMPLEMENTATION OF QUEUE
DATE:
AIM :
ALGORITHM :
Step 1: Start
Step 2: Define a array queue of size max = 5
Step 3: Initialize front = rear = –1
Step 4: Display a menu listing queue operations
Step 5: Accept choice
Step 6: If choice = 1 then
Step 7: If rear < max -1 Increment rear
Step 8: Store element at current position of rear Step 9: Else , Print Queue Full
Step 10:If choice = 2 then
Step 11: If front = –1 then , Print Queue empty
Step 12: Else, Display current front element
Step 13: Increment front
Step 14: If choice = 3 then , Display queue elements starting from front to rear.
Step 15: Stop
PROGRAM :
#include<stdio.>
#include<conio.>
#define max 5
static intqueue[max];
int front = -1;
int rear = -1;
void insert(int x)
{
queue[++rear] = x;
if (front == -1)
front = 0;
}
int remove()
{
int val;
val = queue[front];
if (front==rear &&rear==max)
front = rear = -1;
else
front+;
return (val);
10
}
void view()
{
int i;
if (front == -1)
printf("\n Queue Empty\n");
else
{
printf("\n Front-->");
for(i=front; i<=rear; i++)
printf("%4d", queue[i]);
printf(" <--Rear\n");
}
}
main()
{
int ch= 0,val;
clrscr();
while(ch != 4)
{
printf("\n QUEUE OPERATION \n");
printf("1.INSERT ");
printf("2.DELETE ");
printf("3.VIEW ");
printf("4.QUIT\n");
printf("Enter Choice : ");
scanf("%d", &ch);
switch(ch)
{
case 1:
if(rear < max-1)
{
printf("\n Enter element to be inserted : ");
scanf("%d", &val);
insert(val);
}
else
printf("\n Queue Full \n");
break;
case 2:
if(front == -1)
printf("\n Queue Empty\n");
else
{
val = remove();
printf("\n Element deleted : %d \n", val);
}
break;
11
case 3:
view();
break;
case 4:
exit(0);
defaul:
printf("\n Invalid Choice \n");
}
}
}
OUTPUT :
QUEUE OPERATION
1.INSERT 2.DELETE 3.VIEW 4.QUIT
Enter Choice : 1
Enter element to be inserted :
12 QUEUE OPERATION
1.INSERT 2.DELETE 3.VIEW 4.QUIT
Enter Choice : 1
Enter element to be inserted :
23 QUEUE OPERATION
1.INSERT 2.DELETE 3.VIEW 4.QUIT
Enter Choice : 1
Enter element to be inserted :
34 QUEUE OPERATION
1.INSERT 2.DELETE 3.VIEW 4.QUIT
Enter Choice : 1
Enter element to be inserted :
45 QUEUE OPERATION
1.INSERT 2.DELETE 3.VIEW 4.QUIT
Enter Choice : 1
Enter element to be inserted :
56 QUEUE OPERATION
1.INSERT 2.DELETE 3.VIEW 4.QUIT
Enter Choice : 1
Queue Full
QUEUE OPERATION
1.INSERT 2.DELETE 3.VIEW 4.QUIT
Enter Choice : 3
Front--> 12 23 34 45 56 <--Rear
RESULT:
Thus insert and delete operations of a queue was demonstrated using array
12
EX.NO: 1c ARRAY IMPLEMENTATION OF CIRCULAR QUEUE ADT.
DATE:
AIM :
ALGORITHM :
Step 1: Start
Step 2: Define a array queue of size max = 5
Step 3: Initialize front = rear = –1
Step 4: Display a menu listing queue operations
Step 5: Accept choice
Step 6: If choice = 1 then
Step 7: If rear < max -1 Increment rear
Step 8: Store element at current position of rear
Step 9: Else , Print Queue Full
Step 10:If choice = 2 then
Step 11: If front = –1 then , Print Queue empty
Step 12: Else, Display current front element
Step 13: Increment front
Step 14: If choice = 3 then , Display queue elements starting from front to rear.
Step 15: Stop
PROGRAM :
#include<stdio.h>
#define capacity 6
int queue[capacity];
int front = -1, rear = -1;
int checkFull ()
{
if ((front == rear + 1) || (front == 0 && rear == capacity - 1))
{
return 1;
}
return 0;
}
int checkEmpty ()
{
if (front == -1)
{
return 1;
}
return 0;
}
void enqueue (int value)
{
if (checkFull ())
printf ("Overflow condition\n");
else
13
{
if (front == -1)
front = 0;
rear = (rear + 1) % capacity;
queue[rear] = value;
printf ("%d was enqueued to circular queue\n", value);
}
}
int dequeue ()
{
int variable;
if (checkEmpty ())
{
printf ("Underflow condition\n");
return -1;
}
else
{
variable = queue[front];
if (front == rear)
{
front = rear = -1;
}
else
{
front = (front + 1) % capacity;
}
printf ("%d was dequeued from circular queue\n", variable);
return 1;
}
}
void print ()
{
int i;
if (checkEmpty ())
printf ("Nothing to dequeue\n");
else
{
printf ("\nThe queue looks like: \n");
for (i = front; i != rear; i = (i + 1) % capacity)
{
printf ("%d ", queue[i]);
}
printf ("%d \n\n", queue[i]);
}
}
int main ()
{
dequeue ();
enqueue (15);
enqueue (20);
enqueue (25);
enqueue (30);
enqueue(35);
print ();
14
dequeue ();
dequeue ();
print ();
enqueue (40);
enqueue (45);
enqueue (50);
enqueue (55);
print ();
return 0;
}
OUTPUT:
Underflow condition
15 was enqueued to circular queue
20 was enqueued to circular queue
25 was enqueued to circular queue
30 was enqueued to circular queue
35 was enqueued to circular queue
The queue looks like:
15 20 25 30 35
15 was dequeued from circular queue
20 was dequeued from circular queue
The queue looks like:
25 30 35
40 was enqueued to circular queue
45 was enqueued to circular queue
50 was enqueued to circular queue
Overflow condition
The queue looks like:
25 30 35 40 45 50
RESULT:
Thus insert and delete operations of a circular queue was demonstrated using array
15
EX.NO: 2 IMPLEMENTATION OF SINGLY LINKED LIST
DATE:
AIM:
To define a singly linked list node and perform operations such as insertions and
deletions dynamically.
ALGORITHM :
Step 1: Start
Step 2: Define single linked list node as self referential structure
Step 3: Create Head node with label = -1 and next = NULL using
Step 4: Display menu on list operation
Step 5: Accept user choice
Step 6: If choice = 1 then , Locate node after which insertion is to be done
Step 7: Create a new node and get data part
Step 8: Insert the new node at appropriate position by manipulating address
Step 9: Else if choice = 2 ,Get node's data to be deleted.
Step 10: Locate the node and delink the node
Step 11: Rearrange the links
Step 12: Else , Traverse the list from Head node to node which points to null
Step 13: Stop
PROGRAM :
#include <stdio.h>
#include <conio.h>
#include <process.h>
#include <alloc.h>
#include <string.h>
struct node
{
int label;
struct node *next;
};
main()
{
int ch, fou=0; int k;
struct node *h, *temp, *head, *h1;
head = (struct node*) malloc(sizeof(struct node));
head->label = -1;
head->next = NULL; while(-1)
{
clrscr();
printf("\n\n SINGLY LINKED LIST OPERATIONS \n");
printf("1->Add "); printf("2->Delete "); printf("3->View "); printf("4->Exit \n");
printf("Enter your choice : ");
scanf("%d", &ch); switch(ch)
{
16
case 1:
printf("\n Enter label after which to add : ");
scanf("%d", &k);
h = head;
fou = 0;
if (h->label == k)
fou = 1;
while(h->next != NULL)
{
if (h->label == k)
{
fou=1; break;
}
h = h->next;
}
if (h->label == k)
fou = 1;
if (fou != 1)
printf("Node not found\n");
else
{
temp=(struct node *)(malloc(sizeof(struct node)));
printf("Enter label for new node : ");
scanf("%d" , &temp->label);
temp->next = h->next;
h->next = temp;
}
break;
case 2:
printf("Enter label of node to be deleted\n");
scanf("%d", &k);
fou = 0;
h = h1 = head;
while (h->next != NULL)
{
h = h->next;
if (h->label == k)
{
fou = 1;
break;
}
}
if (fou == 0)
printf("Sorry Node not found\n");
else
{
while (h1->next !=h)
h1 = h1->next;
h1->next = h->next;
free(h);
printf("Node deleted successfully \n");
}
break;
case 3:
17
printf("\n\n HEAD -> ");
h=head;
while (h->next != NULL)
{
h = h->next;
printf("%d -> ",h->label);
}
printf("NULL"); break;
case 4:
exit(0);
}
}
}
OUTPUT:
RESULT:
18
EX.NO: 3a LINKED LIST IMPLEMENTATION OF STACK
DATE:
AIM:
ALGORITHM:
Step 1: Start
Step 2: Define a singly linked list node for stack
Step 3: Create Head node
Step 4: Display a menu listing stack operations
Step 5: Accept choice
Step 6: If choice = 1 then ,Create a new node with data
Step 7: Make new node point to first node
Step 8: Make head node point to new node
Step 9: If choice = 2 then
Step 10: Make temp node point to first node
Step 11: Make head node point to next of temp node
Step 12: Release memory
Step 13: If choice = 3 then , Display stack elements starting from head node till null
Step 14: Stop
PROGRAM:
#include <stdio.h>
#include <conio.h>
#include <process.h>
#include <alloc.h>
struct node
{
int label;
struct node *next;
};
main()
{
int ch = 0;
int k;
struct node *h, *temp, *head;
head = (struct node*) malloc(sizeof(struct node));
head->next = NULL;
while(1)
{
printf("\n Stack using Linked List \n");
printf("1->Push ");
printf("2->Pop ");
printf("3->View ");
printf("4->Exit \n");
printf("Enter your choice : ");
scanf("%d", &ch);
19
switch(ch)
{
case 1:
temp=(struct node *)(malloc(sizeof(struct node)));
printf("Enter label for new node : ");
scanf("%d", &temp->label);
h = head;
temp->next = h->next;
h->next = temp;
break;
case 2:
h = head->next;
head->next = h->next;
printf("Node %s deleted\n", h->label);
free(h);
break;
case 3:
printf("\n HEAD -> ");
h = head;
while(h->next != NULL)
{
h = h->next;
printf("%d -> ",h->label);
}
printf("NULL \n"); break;
case 4:
exit(0);
}
}
}
OUTPUT:
RESULT:
Thus push and pop operations of a stack was demonstrated using linked list
20
EX.NO: 3b LINKED LIST IMPLEMENTATION OF QUEUE
DATE:
AIM:
ALGORITHM:
Step 1: Start
Step 2: Define a singly linked list node for stack
Step 3: Create Head node
Step 4: Display a menu listing stack operations
Step 5: Accept choice
Step 6: If choice = 1 then , Create a new node with data
Step 7: Make new node point to first node
Step 8: Make head node point to new node
Step 9: If choice = 2 then , Make temp node point to first node
Step 10: Make head node point to next of temp node
Step 11: Release memory
Step 12: If choice = 3 then , Display stack elements starting from head node till null
Step 13: Stop
PROGRAM :
#include <stdio.h>
#include <conio.h>
#include <process.h>
#include <alloc.h>
struct node
{
int label;
struct node *next;
};
Void main()
{
int ch=0;
int k;
struct node *h, *temp, *head;
head = (struct node*) malloc(sizeof(struct node));
head->next = NULL;
while(1)
{
printf("\n Queue using Linked List \n");
printf("1->Insert ");
printf("2->Delete ");
printf("3->View ");
printf("4->Exit \n");
printf("Enter your choice : ");
scanf("%d", &ch);
switch(ch)
21
{
case 1:
temp=(struct node *)(malloc(sizeof(struct node)));
printf("Enter label for new node : ");
scanf("%d", &temp->label);
h = head;
while (h->next != NULL)
h = h->next;
h->next = temp;
temp->next = NULL;
break;
case 2:
h = head->next;
head->next = h->next;
printf("Node deleted \n");
free(h);
break;
case 3:
printf("\n\nHEAD -> ");
h=head;
while (h->next!=NULL)
{
h = h->next;
printf("%d -> ",h->label);
}
printf("NULL \n"); break;
case 4:
exit(0);
}
}
}
OUTPUT :
RESULT:
Thus enqueue and dequeue operations of a queue was demonstrated using linked list
22
EX.NO: 4 IMPLEMENTATION OF POLYNOMIAL MANIPULATION USING LINKED LIST
DATE:
AIM:
To store a polynomial using linked list. Also, perform addition and subtraction on two polynomial
ALGORITHM:
Step 1: Start
Step 2: Let p and q be the two polynomials represented by linked lists while p and q are
. not null, repeat step3.
Step 3: If powers of the two terms are equal then
Step 4: If the terms do not cancel then Insert the sum of the terms into the sum
Polynomial Advance p Advance q
Step 5: Else if the power of the first polynomial> power of second Then Insert the term
from first polynomial into sum polynomial Advance p
Step 6: Else insert the term from second polynomial into sum polynomial Advance q
Step 7: Copy the remaining terms from the non empty polynomial into the sum
polynomial.
Step 8: step 7 is to be processed till the end of the polynomials has not been reached.
Step 9: stop
PROGRAM:
#include <stdio.h>
#include <conio.h>
#include <malloc.h>
struct node
{
int num;
int coeff;
struct node *next;
};
struct node *start1 = NULL;
struct node *start2 = NULL;
struct node *start3 = NULL;
struct node *start4 = NULL;
struct node *last3 = NULL;
struct node *create_poly(struct node *);
struct node *display_poly(struct node *);
struct node *add_poly(struct node *, struct node *, struct node *);
struct node *sub_poly(struct node *, struct node *, struct node *);
struct node *add_node(struct node *, int, int);
int main()
{
int option;
clrscr();
do
23
{
printf("\n******* MAIN MENU *******");
printf("\n 1. Enter the rst polynomial");
printf("\n 2. Display the rst polynomial");
printf("\n 3. Enter the second polynomial");
printf("\n 4. Display the second polynomial");
printf("\n 5. Add the polynomials");
printf("\n 6. Display the result");
printf("\n 7. Subtract the polynomials");
27
OUTPUT :
RESULT:
28
EX.NO: 5 IMPLEMENTATION OF CIRCULAR QUEUE
DATE:
AIM:
ALGORITHM:
Step 1: Start
Step 2: Define a singly linked list node for stack
Step 3: Create Head node
Step 4: Display a menu listing stack operations
Step 5: Accept choice
Step 6: If choice = 1 then ,Create a new node with data
Step 7: Make new node point to first node
Step 8: Make head node point to new node
Step 9: If choice = 2 then, Make temp node point to first node
Step 10: Make head node point to next of temp node
Step 11: Release memory
Step 12: If choice = 3 then , Display stack elements starting from head node till null
Step 13: Stop
PROGRAM :
#include<stdio.h>
#include<stdlib.h>
struct node
{
int info;
struct node *link;
}*rear=NULL;
void insert(int item);
int del();
void display();
int isEmpty();
int peek();
int main()
{
int choice,item;
while(1)
{
printf("\n1.Insert\n");
printf("2.Delete\n");
printf("3.Peek\n");
printf("4.Display\n");
printf("5.Quit\n");
printf("\nEnter your choice : ");
scanf("%d",&choice);
switch(choice)
{
29
case 1:
printf("\nEnter the element for insertion : ");
scanf("%d",&item);
insert(item);
break;
case 2:
printf("\nDeleted element is %d\n",del());
break;
case 3:
printf("\nItem at the front of queue is %d\n",peek());
break;
case 4:
display();
break;
case 5:
exit(1);
default:
printf("\nWrong choice\n");
}
}
}
void insert(int item)
{
struct node *tmp;
tmp=(struct node *)malloc(sizeof(struct node));
tmp->info=item;
if(tmp==NULL)
{
printf("\nMemory not available\n");
return;
}
if( isEmpty() )
{
rear=tmp;
tmp->link=rear;
}
else
{
tmp->link=rear->link;
rear->link=tmp;
rear=tmp;
}
}
del()
{
int item;
struct node *tmp;
if( isEmpty() )
{
printf("\nQueue underflow\n");
exit(1);
}
if(rear->link==rear)
{
30
tmp=rear;
rear=NULL;
}
else
{
tmp=rear->link;
rear->link=rear->link->link;
}
item=tmp->info;
free(tmp);
return item;
}
int peek()
{
if( isEmpty() )
{
printf("\nQueue underflow\n");
exit(1);
}
return rear->link->info;
}
int isEmpty()
{
if( rear == NULL )
return 1;
else
return 0;
}
void display()
{
struct node *p;
if(isEmpty())
{
printf("\nQueue is empty\n");
return;
}
printf("\nQueue is :\n");
p=rear->link;
do
{
printf("%d ",p->info);
p=p->link;
}
while(p!=rear->link);
printf("\n");
}
31
OUTPUT:
1. Insert
2. Delete
3. Peek
4. Display
5. Quit
Enter your choice : 1
Enter the element for insertion : 1
1. Insert
2. Delete
3. Peek
4. Display
5. Quit
Enter your choice : 1
Enter the element for insertion : 2
1. Insert
2. Delete
3. Peek
4. Display
5. Quit
Enter your choice : 1
Enter the element for insertion : 3
1. Insert
2. Delete
3. Peek
4. Display
5. Quit
Enter your choice : 4
Queue is :
123
1. Insert
2. Delete
3. Peek
4. Display
5. Quit
Enter your choice : 2
Deleted element is 1
1. Insert
2. Delete
3. Peek
4. Display
5. Quit
Enter your choice : 3
Item at the front of queue is 2
32
1. Insert
2. Delete
3. Peek
4. Display
5. Quit
Enter your choice : 2
Deleted element is 2
1. Insert
2. Delete
3. Peek
4. Display
5. Quit
Enter your choice : 4
Queue is :3
RESULT:
Thus insert and delete operations of a circular queue was demonstrated using array
33
EX.NO: 6a IMPLEMENTATION OF EVALUATING POSTFIX EXPRESSIONS
DATE:
AIM:
ALGORITHM:
Step 1: Start
Step 2: Define a array stack of size max = 20
Step 3: Initialize top = -1
Step 4: Read the postfix expression character-by-character
Step 5: If character is an operand push it onto the stack
Step 6: If character is an operator
Step 7: Pop topmost two elements from stack.
Step 8: Apply operator on the elements and push the result onto the stack, Eventually
only result will be in the stack at end of the expression.
Step 9: Pop the result and print it.
Step 10:stop
PROGRAM :
#include <stdio.h>
#include <conio.h>
struct stack
{
int top;
float a[50];
}s;
main()
{
char pf[50];
float d1,d2,d3;
int i;
clrscr();
s.top = -1;
printf("\n\n Enter the postfix expression: ");
gets(pf);
for(i=0; pf[i]!='\0'; i++)
{
switch(pf[i])
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
34
case '9':
s.a[++s.top] = pf[i]-'0';
break;
case '+':
d1 = s.a[s.top--];
d2 = s.a[s.top--];
s.a[++s.top] = d1 + d2;
break;
case '-':
d2 = s.a[s.top--];
d1 = s.a[s.top--];
s.a[++s.top] = d1 - d2;
break;
case '*':
d2 = s.a[s.top--];
d1 = s.a[s.top--]; s.a[++s.top] = d1*d2;
break;
case '/':
d2 = s.a[s.top--];
d1 = s.a[s.top--]; s.a[++s.top] = d1 / d2;
break;
}
}
printf("\n Expression value is %5.2f", s.a[s.top]);
getch();
}
OUTPUT :
RESULT:
35
EX.NO: 6b IMPLEMENTATION OF INFIX TO POSTFIX CONVERSION
DATE:
AIM:
ALGORITHM:
Step 1: Start
Step 2: Define a array stack of size max = 20
Step 3: Initialize top = -1
Step 4: Read the infix expression character-by-character
Step 5: If character is an operand print it
Step 6: If character is an operator
Step 7: Compare the operator‟s priority with the stack[top] operator.
Step 8: If the stack [top] operator has higher or equal priority than the inputoperator, Pop
it from the stack and print it.
Step 9: Else Push the input operator onto the stack
Step 10: If character is a left parenthesis, then push it onto the stack.
Step 11: If the character is a right parenthesis, pop all the operators from the stack
andprint it until a left parenthesis is encountered. Do not print the parenthesis.
Step 12: Stop.
PROGRAM :
#include <stdio.h>
#include <conio.h>
#include <string.h>
#define MAX 20
int top = -1;
char stack[MAX];
char pop();
void push(char item);
int prcd(char symbol)
{
switch(symbol)
{
case '+':
case '-':
return 2;
break;
case '*':
case '/':
return 4;
break;
case '^':
case '$':
return 6;
break;
case '(':
case ')':
36
case '#':
return 1;
break;
}
}
int isoperator(char symbol)
{
switch(symbol)
{
case '+':
case '-':
case '*':
case '/':
case '^':
case '$':
case '(':
case ')':
return 1;
break;
default:
return 0;
}
}
void convertip(char infix[],char postfix[])
{
int i,symbol,j = 0;
stack[++top] = '#';
for(i=0;i<strlen(infix);i++)
{
symbol = infix[i];
if(isoperator(symbol) == 0)
{
postfix[j] = symbol;
j++;
}
else
{
if(symbol == '(')
push(symbol);
else if(symbol == ')')
{
while(stack[top] != '(')
{
postfix[j] = pop(); j++;
}
pop();
}
else
{
if(prcd(symbol) > prcd(stack[top]))
push(symbol);
else
{
while(prcd(symbol) <= prcd(stack[top]))
37
{
postfix[j] = pop();
j++;
}
push(symbol);
}
}
}
}
while(stack[top] != '#')
{
postfix[j] = pop();
j++;
}
postfix[j] = '\0';
}
main()
{
char infix[20],postfix[20];
clrscr();
printf("Enter the valid infix string: ");
gets(infix);
convertip(infix, postfix);
printf("The corresponding postfix string is: ");
puts(postfix);
getch();
}
void push(char item)
{
top++;
stack[top] = item;
}
char pop()
{
char a;
a = stack[top];
top--;
return a;
}
OUTPUT:
RESULT:
Thus the given infix expression was converted into postfix form using stack
38
EX.NO: 7 IMPLEMENTATION BINARY SEARCH TREE
DATE:
AIM:
ALGORITHM :
Step 1: Start
Step 2: Call insert to insert an element into binary search tree.
Step 3: Get the element to be inserted.
Step 4: Find the position in the tree where the element to be inserted by checking the
elements in the tree by traversing from the root.
Step 5: If the element to be inserted is less than the element in the current node in the
tree then traverse left subtree
Step 6: If the element to be inserted is greater than the element in the current node in the
tree then traverse right subtree
Step 7: Insert the element if there is no further move
Step 8: Call delete to delete an element from binary search tree.
Step 9: Get the element to be deleted.
Step 10: Find the node in the tree that contain the element.
Step 11: Delete the node an rearrange the left and right siblings if any present for the
deleted node
Step 12: Call findmax to find the element with maximum value in binary search tree
Step 13: Traverse the tree from the root.
Step 14: Find the rightmost leaf node of the entire tree and return it
Step 15: If the tree is empty return null.
Step 16: Call findmin to find the element with minimum value in binary search tree
Step 17: Traverse the tree from the root.
Step 18: Find the leftmost leaf node of the entire tree and return it
Step 19: If the tree is empty return null.
Step 20: Call find to check the presence of the element in the binary search tree
Step 21: Traverse the tree from the root.
Step 22: Check whether the element to searched matches with element of the current
node.f match occurs return it.
Step 23: Otherwise if the element is less than that of the element of the current node then
search the leaf subtree
Step 24: Else search right subtree. Makeempty function Make the root of the tree to
point to null.
Step 25: Call display to display the elements of the binary search tree
Step 26: Call makeempty to delete the entire tree.
Step 27: Stop
PROGRAM :
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
struct searchtree
{
int element;
39
struct searchtree *left,*right;
}*root;
typedef struct searchtree *node;
typedef int ElementType;
node insert(ElementType, node);
node delete(ElementType, node);
void makeempty();
node findmin(node);
node findmax(node);
node find(ElementType, node);
void display(node, int);
void main()
{
int ch;
ElementType a;
node temp;
makeempty();
while(1)
{
printf("\n1. Insert\n2. Delete\n3. Find\n4. Find min\n5. Find max\n6.Display\n7.
Exit\nEnter Your Choice : ");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("Enter an element : ");
scanf("%d", &a);
root = insert(a, root);
break;
case 2:
printf("\nEnter the element to delete : ");
scanf("%d",&a);
root = delete(a, root);
break;
case 3:
printf("\nEnter the element to search : ");
scanf("%d",&a);
temp = find(a, root);
if (temp != NULL)
printf("Element found");
else
printf("Element not found");
break;
case 4:
temp = findmin(root);
if(temp==NULL)
printf("\nEmpty tree");
else
printf("\nMinimum element : %d", temp->element);
break;
case 5:
temp = findmax(root);
if(temp==NULL)
40
printf("\nEmpty tree");
else
printf("\nMaximum element : %d", temp->element);
break;
case 6:
if(root==NULL)
printf("\nEmpty tree");
else
display(root, 1);
break;
case 7:
exit(0);
default:
printf("Invalid Choice");
}
}
}
node insert(ElementType x,node t)
{
if(t==NULL)
{
t = (node)malloc(sizeof(node));
t->element = x;
t->left = t->right = NULL;
}
else
{
if(x < t->element)
t->left = insert(x, t->left);
else
if(x > t->element)t->right = insert(x, t->right);
}
return t;
}
node delete(ElementType x,node t)
{
node temp;
if(t == NULL)
printf("\nElement not found");
else
{
if(x < t->element)
t->left = delete(x, t->left);
else if(x > t->element)
t->right = delete(x, t->right);
else
{
if(t->left && t->right)
{
temp = findmin(t->right);
t->element = temp->element;
t->right = delete(t->element,t->right);
}
else if(t->left == NULL)
41
{
temp = t; t=t->right;
free (temp);
}
else
{
temp = t; t=t->left;
free (temp);
}
}
}
return t;
}
void makeempty()
{
root = NULL;
}
node findmin(node temp)
{
if(temp == NULL || temp->left == NULL)
return temp;
return findmin(temp->left);
}
node findmax(node temp)
{
if(temp==NULL || temp->right==NULL)
return temp;
return findmax(temp->right);
}
node find(ElementType x, node t)
{
if(t==NULL)
return NULL;
if(x<t->element)
return find(x,t->left);
if(x>t->element)
return find(x,t->right);
return t;
}
void display(node t,int level)
{
int i;
if(t)
{
display(t->right, level+1);
printf(“ \n”);
for(i=0;i<level;i++)
printf(" ");
printf("%d", t->element);
display(t->left, level+1);
}
}
42
OUTPUT:
1. Insert
2. Delete
3. Find
4. Find Min
5. Find Max
6. Display
7. Exit
Enter your Choice : 1
Enter an element : 10
1. Insert
2. Delete
3. Find
4. Find Min
5. Find Max
6. Display
7. Exit
Enter your Choice : 139
Enter an element : 20
1. Insert
2. Delete
3. Find
4. Find Min
5. Find Max
6. Display
7. Exit
Enter your Choice : 1
Enter an element : 5
1. Insert
2. Delete
3. Find
4. Find Min
5. Find Max
6. Display
7. Exit
Enter your Choice : 4
The smallest Number is
5
1. Insert
2. Delete
3. Find
4. Find Min
5. Find Max
6. Display
7. Exit
Enter your Choice :
3 Enter an element :
100 Element not
Found
1. Insert
2. Delete
43
3. Find
4. Find Min
5. Find Max
6. Display
7. Exit
Enter your Choice : 2
Enter an element : 20
1. Insert
2. Delete
3. Find
4. Find Min
5. Find Max
6. Display
7. Exit40
Enter your Choice : 6
20
10
RESULT:
Step 1: Start
Step 2: A binary search tree x is called an AVL tree,
Step 3: if , b(x.key) ∈ {−1, 0, 1}, and
Step 4: x.leftChild and x.rightChild are both AVL trees. = the height balance of every
node must be -1, 0, or 1
Step 5: insert/delete via standard algorithms
Step 6: after insert/delete: load balance b(node) might be changed to +2 or −2 for certain
nodes
Step 7: re-balance load after each step
Step 8: Insert operation may cause balance factor to become 2 or –2 for some node
Step 9: only nodes on the path from insertion point to root node have possibly changed
in height
Step 10: So after the Insert, go back up to the root node by node, updating heights
Step 11:If a new balance factor (the difference hleft – hright ) is 2 or –2, adjust tree by
rotation around the node
Step 12: Let the node that needs rebalancing be α.
Step 13:There are 4 cases, Outside Cases (require single rotation) :
Step 14: Insertion into left subtree of left child of α.
Step 15: Insertion into right subtree of right child of α.
Step 16: Inside Cases (require double rotation) :
Step 17: Insertion into right subtree of left child of α.
Step 18: Insertion into left subtree of right child of α.
Step 19: The rebalancing is performed through four separate rotation algorithms.
Step 20: You can either keep the height or just the difference in height.
Step 21: This has to be modified on the path of insertion even if you don‟t perform
rotations
Step 22: Once you have performed a rotation (single or double) you won‟t need to go
back up the tree
Step 23:Stop
PROGRAM :
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int key;
struct Node *left; struct Node *right;
int height;
};
int max(int a, int b);
int height(struct Node *N)
{
if (N == NULL)
45
return 0;
return N->height;
}
int max(int a, int b)
{
return (a > b)? a : b;
}
struct Node* newNode(int key)
{
struct Node* node = (struct Node*) malloc(sizeof(struct Node));
node->key = key;
node->left = NULL;
node->right = NULL;
node->height = 1;
return(node);
}
struct Node *rightRotate(struct Node *y)
{
struct Node *x = y->left;
struct Node *T2 = x->right;
x->right = y;
y->left = T2;
y->height = max(height(y->left), height(y->right))+1;
x->height = max(height(x->left), height(x->right))+1;
return x;
}.
struct Node *leftRotate(struct Node *x)
{
struct Node *y = x->right;
struct Node *T2 = y->left;
y->left = x;
x->right = T2;
// Update heights
x->height = max(height(x->left), height(x->right))+1;
y->height = max(height(y->left), height(y->right))+1;
return y;
}
int getBalance(struct Node *N)
{
if (N == NULL)
return 0;
return height(N->left) - height(N->right);
}
struct Node* insert(struct Node* node, int key)
{
if (node == NULL)
return(newNode(key)); if (key < node->key)
node->left = insert(node->left, key);
else if (key > node->key)
node->right = insert(node->right, key);
else
return node;
node->height = 1 + max(height(node->left), height(node->right));
46
int balance = getBalance(node);
if (balance > 1 && key < node->left->key)
return rightRotate(node);
if (balance < -1 && key > node->right->key)
return leftRotate(node);
if (balance > 1 && key > node->left->key)
{
node->left = leftRotate(node->left);
return rightRotate(node);
}
if (balance < -1 && key < node->right->key)
{
node->right = rightRotate(node->right);
return leftRotate(node);
}
return node;
}
void preOrder(struct Node *root)
{
if(root != NULL)
{
printf("%d ", root->key);
preOrder(root->left);
preOrder(root->right);
}
}
int main()
{
struct Node *root = NULL;
root = insert(root, 10);
root = insert(root, 20);
root = insert(root, 30);
root = insert(root, 40);
root = insert(root, 50);
root = insert(root, 25);
printf("Preorder traversal of the constructed AVL" " tree is \n");
preOrder(root);
return 0;
}
OUTPUT :
ALGORITHM:
Step 1: Start.
Step 2: Priority queue is a type of queue in which every element has a key associated to
it and the queue returns the element according to these keys, unlike the traditional
queue which works on first come first serve basis.
Step3:Thus, a max-priority queue returns the element with maximum key first whereas,
a min-priority queue returns the element with the smallest key first. max-priority
queue and min-priority queue
Step 4:Priority queues are used in many algorithms like Huffman Codes, Prim' . .
algorithm, etc.
It is also used in scheduling processes for a computer, etc.
Step 5:Heaps are great for implementing a priority queue because of the largest and
smallest element at the root of the tree for a max-heap and a min heap
respectively. We use a max-heap for a max-priority queue and a min-heap for a
min-priority queue.
Step 6:There are mainly 4 operations we want from a priority queue:
1. Insert → To insert a new element in the queue.
2. Maximum/Minimum → To get the maximum and the minimum element from
the max-priority queue and min-priority queue respectively.
3. Extract Maximum/Minimum → To remove and return the maximum and the
minimum element from the max-priority queue and min-priority queue
respectively.
4. Increase/Decrease key → To increase or decrease key of any element in the
Queue.
Step 7:A priority queue stores its data in a specific order according to the keys of the
elements.So, inserting a new data must go in a place according to the specified
order. This is what the insert operation does.
Step 8:The entire point of the priority queue is to get the data according the key of the
data and the Maximum/Minimum and Extract Maximum/Minimum does this for
us.
Step 9:We know that the maximum (or minimum) element of a priority queue is at the
root of the max-heap (or min-heap). So, we just need to return the element at the
root of the heap.
Step 10:This is like the pop of a queue, we return the element as well as delete it from
the heap.So, we have to return and delete the root of a heap. Firstly, we store the
value of the root in a variable to return it later from the function and then we just
make the root equal tothe last element of the heap. Now the root is equal to the
last element of the heap, we delete the last element easily by reducing the size of
the heap by 1.
Step 11:Doing this, we have disturbed the heap property of the root but we have not
touched any ofits children, so they are still heaps. So, we can call Heapify on the
root to make the tree a heap again.
Step 12: Stop.
48
PROGRAM :
#include <stdio.h>
int tree_array_size = 20;
int heap_size = 0;
const int INF = 100000;
void swap( int *a, int *b )
{
int t;
t = *a;
*a = *b;
*b = t;
}
int get_right_child(int A[], int index)
{
if((((2*index)+1) < tree_array_size) && (index >= 1))
return (2*index)+1;
return -1;
}
int get_left_child(int A[], int index)
{
if(((2*index) < tree_array_size) && (index >= 1))
return 2*index;
return -1;
}
int get_parent(int A[], int index)
{
if ((index > 1) && (index < tree_array_size))
{
return index/2;
}
return -1;
}
void max_heapify(int A[], int index)
{
int left_child_index = get_left_child(A, index);
int right_child_index = get_right_child(A, index);
int largest = index;
if ((left_child_index <= heap_size) && (left_child_index>0))
{
if (A[left_child_index] > A[largest])
{
largest = left_child_index;
}
}
if ((right_child_index <= heap_size && (right_child_index>0)))
{
if (A[right_child_index] > A[largest])
{
largest = right_child_index;
}
}
49
if (largest != index)
{
swap(&A[index], &A[largest]);
max_heapify(A, largest);
}
}
void build_max_heap(int A[])
{
int i;
for(i=heap_size/2; i>=1; i--)
{
max_heapify(A, i);
}
}
int maximum(int A[])
{
return A[1];
}
int extract_max(int A[])
{
int maxm = A[1];
A[1] = A[heap_size];
heap_size--;
max_heapify(A, 1);
return maxm;
}
void increase_key(int A[], int index, int key)
{
A[index] = key;
while((index>1) && (A[get_parent(A, index)] < A[index]))
{
swap(&A[index], &A[get_parent(A, index)]);
index = get_parent(A, index);
}
}
void decrease_key(int A[], int index, int key)
{
A[index] = key;
max_heapify(A, index);
}
void insert(int A[], int key)
{
heap_size++;
A[heap_size] = -1*INF;
increase_key(A, heap_size, key);
}
void print_heap(int A[])
{
int i;
for(i=1; i<=heap_size; i++)
{
printf("%d\n",A[i]);
}
printf("\n");
50
}
int main()
{
int A[tree_array_size];
insert(A, 20);
insert(A, 15);
insert(A, 8);
insert(A, 10);
insert(A, 5);
insert(A, 7);
insert(A, 6);
insert(A, 2);
insert(A, 9);
insert(A, 1);
print_heap(A);
increase_key(A, 5, 22);
print_heap(A);
decrease_key(A, 1, 13);
print_heap(A);
printf("%d\n\n", maximum(A));
printf("%d\n\n", extract_max(A));
print_heap(A);
printf("%d\n", extract_max(A));
printf("%d\n", extract_max(A));
printf("%d\n", extract_max(A));
printf("%d\n", extract_max(A));
printf("%d\n", extract_max(A));
printf("%d\n", extract_max(A));
printf("%d\n", extract_max(A));
printf("%d\n", extract_max(A));
printf("%d\n", extract_max(A));
return 0;
}
OUTPUT
RESULT:
51
EX.NO: 10 IMPLEMENTATION OF DIJKSTRA’S ALGORITHM
DATE:
AIM:
write a c program to implement dijkstra’s algorithm.
ALGORITHM :
Step 1: Start
Step 2: Initialize distances from the source vertex to all other vertices as infinity (or a
large value).
Step 3: Set the distance from the source vertex to itself as 0.
Step 4:Pick the vertex with the minimum distance from the set of vertices not yet
processed.
Step 5: Mark the picked vertex as processed.
Step 6: Update the distances of the adjacent vertices to the picked vertex if the new
distance is smaller than the current distance.
Step 7: Dijkstra's algorithm has a time complexity of O(V^2) for adjacency matrix
representation and O((V + E) log V) for adjacency list representation, where V is
the number of vertices and E is the number of edges in the graph.
Step 8: Stop
PROGRAM :
#include <stdio.h>
#include <stdbool.h>
#include <limits.h>
#define V 6
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;
}
void printSolution(int dist[])
{
printf("Vertex \t Distance from Source\n");
for (int i = 0; i < V; i++)
printf("%d \t\t %d\n", i, dist[i]);
}
void dijkstra(int graph[V][V], int src)
52
{
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);
}
int main() {
int graph[V][V] = {
{0, 4, 0, 0, 0, 0},
{4, 0, 8, 0, 0, 0},
{0, 8, 0, 7, 0, 4},
{0, 0, 7, 0, 9, 14},
{0, 0, 0, 9, 0, 10},
{0, 0, 4, 14, 10, 0}
};
dijkstra(graph, 0);
return 0;
}
OUTPUT :
RESULT:
53
EX.NO: 11 IMPLEMENTATION OF PRIM’S ALGORITHM
DATE:
AIM:
Write a c program to implement prim’s algorithm.
ALGORITHM:
Step 1: Start.
Step 2: Create an array parent[] to store the constructed MST.
Step 3: Create an array key[] to store the key values used to pick the minimum weight
edge in the cut.
Step 4: Create a boolean array mstSet[] to represent the set of vertices not yet included
in the MST.
Step 5: Initialize all key[] values as INFINITE, mstSet[] values as false, and parent[]
values as -1.
Step 6: Choose any vertex as the starting vertex and set its key value to 0, indicating that
it's the starting point of the MST.
Step 7: Pick the vertex u with the minimum key value from the set of vertices not yet
included in the MST.
Step 8: Add u to the MST set (mstSet[u] = true).
Step 9: Update the key value and parent index of all adjacent vertices of u if the weight
of the edge u-v is smaller than the current key value of v.
Step 10: The MST will contain V - 1 edges, where V is the number of vertices in the
graph.
Step 11: Print the constructed MST, which includes the edges and their weights.
Step 12: Prim's algorithm has a time complexity of O(V^2) using an adjacency matrix
and O(E log V)using an adjacency list, where V is the number of vertices and E
is the number of edges in the graph
Step 13: Stop.
PROGRAM:
#include <stdio.h>
#include <stdbool.h>
#include <limits.h>
#define V 5
int minKey(int key[], bool mstSet[])
{
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++)
if (mstSet[v] == false && key[v] < min)
min = key[v], min_index = v;
return min_index;
}
void printMST(int parent[], int graph[V][V])
{
printf("Edge \tWeight\n");
54
for (int i = 1; i < V; i++)
printf("%d - %d \t%d \n", parent[i], i, graph[i][parent[i]]);
}
void primMST(int graph[V][V])
{
int parent[V];
int key[V];
bool mstSet[V];
for (int i = 0; i < V; i++)
key[i] = INT_MAX, mstSet[i] = false;
key[0] = 0;
parent[0] = -1;
for (int count = 0; count < V - 1; count++)
{
int u = minKey(key, mstSet);
mstSet[u] = true;
for (int v = 0; v < V; v++)
if (graph[u][v] && mstSet[v] == false && graph[u][v] < key[v])
parent[v] = u;
key[v] = graph[u][v];
}
printMST(parent, graph);
}
int main() {
int graph[V][V] = {
{0, 2, 0, 6, 0},
{2, 0, 3, 8, 5},
{0, 3, 0, 0, 7},
{6, 8, 0, 0, 9},
{0, 5, 7, 9, 0}
};
primMST(graph);
return 0;
}
OUTPUT :
Edge Weigh
t
1-0 2
2-1 3
3-2 0
4-0 6
RESULT:
55
EX.NO:12a LINEAR SEARCH
DATE:
AIM:
ALGORITHM :
Step 1: Start
Step 2: Read number of array elements n
Step 3: Read array elements Ai, i = 0,1,2,…n–1
Step 4: Read search value
Step 5: Assign 0 to found
Step 6: Check each array element against search
Step 7: If Ai = search then found = 1 Print "Element found" Print position i Stop
Step 8: If found = 0 then ,print "Element not found"
Step 9: Stop
PROGRAM:
#include <stdio.h>
#include <conio.h>
void main()
{
int a[50],i, n, val, found;
clrscr();
printf("Enter number of elements : ");
scanf("%d", &n);
printf("Enter Array Elements : \n");
for(i=0; i<n; i++)
scanf("%d", &a[i]);
printf("Enter element to locate : ");
scanf("%d", &val);
found = 0;
for(i=0; i<n; i++)
{
if (a[i] == val)
{
printf("Element found at position %d", i);
found = 1;
break;
}
}
if (found == 0)
printf("\n Element not found");
getch();
}
56
OUTPUT :
RESULT:
Thus an array was linearly searched for an element's existence
57
EX.NO:12b BINARY SEARCH
DATE:
AIM :
Step 1: Start
Step 2: Read number of array elements, say n
Step 3: Create an array arr consisting n sorted elements
Step 4: Get element, say key to be located
Step 5: Assign 0 to lower and n to upper
Step 6: While (lower < upper)
a. Determine middle element mid = (upper+lower)/2
b. If key = arr[mid] then
i. Print mid
ii. Stop
c. Else if key > arr[mid] then
i. lower = mid + 1
d. else
i. upper = mid – 1
Step 7:. Print "Element not found"
Step 8: Stop
PROGRAM :
#include <stdio.h>
void main()
{
int a[50],i, n, upper, lower, mid, val, found, att=0;
printf("Enter array size : ");
scanf("%d", &n);
for(i=0; i<n; i++)
a[i] = 2 * i;
printf("\n Elements in Sorted Order \n");
for(i=0; i<n; i++)
printf("%4d", a[i]);
printf("\n Enter element to locate : "); s
canf("%d", &val);
upper = n;
lower = 0;
found = -1;
while (lower <= upper)
{
mid = (upper + lower)/2;
att++;
if (a[mid] == val)
{
printf("Found at index %d in %d attempts", mid, att);
found = 1;
58
break;
}
else if(a[mid] > val) upper = mid - 1;
else
lower = mid + 1;
}
if (found == -1)
printf("Element not found");
}
OUTPUT:
RESULT:
59
EX.NO:13a INSERTION SORT
AIM:
ALGORITHM:
Step 1: Start
Step 2 Read number of array elements n
Step 3: Read array elements Ai
Step 4: Outer index i varies from second element to last element
Step 5: Inner index j is used to compare elements to left of outer index
Step 6: Insert the element into the appropriate position.
Step 7: Display the array elements after each pass
Step 8: Display the sorted array elements.
Step 9: Stop.
PROGRAM:
void main()
{
int i, j, k, n, temp, a[20], p=0;
printf("Enter total elements: ");
scanf("%d",&n);
printf("Enter array elements: ");
for(i=0; i<n; i++)
scanf("%d", &a[i]);
for(i=1; i<n; i++)
{
temp = a[i]; j = i - 1;
while((temp<a[j]) && (j>=0))
{
a[j+1] = a[j];
j = j - 1;
}
a[j+1] = temp;
p++;
printf("\n After Pass %d: ", p);
for(k=0; k<n; k++)
printf(" %d", a[k]);
}
printf("\n Sorted List : ");
for(i=0; i<n; i++)
printf(" %d", a[i]);
}
60
OUTPUT :
Enter total elements: 666
Enter array elements: 34 8 64 51 32 21
After Pass 1: 8 34 64 51 32 21
After Pass 2: 8 34 64 51 32 21
After Pass 3: 8 34 51 64 32 21
After Pass 4: 8 32 34 51 64 21
After Pass 5: 8 21 32 34 51 64
Sorted List : 8 21 32 34 51 64
RESULT:
61
EX.NO:13b SELECTION SORT
DATE:
AIM:
ALGORITHM:
Step 1: Start
Step 2 Read number of array elements n
Step 3: Read array elements Ai
Step 4: Outer index i varies from second element to last element
Step 5: Inner index j is used to compare elements to left of outer index
Step 6: Insert the element into the appropriate position.
Step 7: Display the array elements after each pass
Step 8: Display the sorted array elements.
Step 9: Stop.
PROGRAM:
#include<stdio.h>
#include<conio.h>
void Selectionsort(int[],int);
void main()
{
int x[20],i,n; clrscr();
printf("\n Enter the no of element to be sorted:");
scanf("%d",&n);
printf("\n Enter %d elements:",n);
for(i=0;i0;i--)
{
large=a[0];
pos=0;
for(j=1;j<=i;j++)
{
if (a[i]>large)
{
large=a[j];
pos=j;
}}
a[pos]=a[i];
a[i]=large;
}
}
62
OUTPUT:
RESULT:
63
EX.NO:14 MERGE SORT
DATE:
AIM:
ALGORITHM:
Step 1: Start
Step 2: Read number of array elements n
Step 3: Read array elements Ai
Step 4: Divide the array into sub-arrays with a set of elements
Step 5: Recursively sort the sub-arrays
Step 6: Display both sorted sub-arrays
Step 7: Merge the sorted sub-arrays onto a single sorted array.
Step 8: Display the merge sorted array elements
Step 9: Stop
PROGRAM :
#include<stdio.h>
#include <conio.h>
void merge(int [],int ,int ,int );
void part(int [],int ,int );
int size;
main()
{
int i, arr[30];
printf("Enter total no. of elements : ");
scanf("%d", &size);
printf("Enter array elements :");
for(i=0; i<size; i++)
scanf("%d", &arr[i]);
part(arr, 0, size-1);
printf("\n Merge sorted list : ");
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);
}
if (max-min == (size/2)-1)
{
printf("\n Half sorted list : ");
64
for(i=min; i<=max; i++)
printf("%d ", arr[i]);
}
}
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 :
RESULT :
Thus array elements was sorted using merge sort's divide and conquer method.
65
EX.NO:15a IMPLEMENTATION OF OPEN ADDRESSING (LINEAR PROBING )
DATE:
AIM:
write a c program to show implementation of open addressing (Linear probing).
ALGORITHM:
Step 1: Start
Step 2:Initialization:
Initialize the hash Array with a fixed size.Initialize all elements of the hash Array
to a special value indicating an empty slot.
Step 3:Hash Function:
Calculate the hash value of a key using a suitable hashing algorithm.
Step 4: Insertion:
Compute the hash value of the key.If the calculated index in the hash Array is
empty, insert the key-value pair at that index. If the index is occupied due to a
collision, probe linearly until an empty slot is found.Insert the key-value pair into
the first empty slot found during probing.
Step 5:Search:
Compute the hash value of the key.Start at the calculated index and probe linearly
until an empty slot is found or the key is found. If the key is found, return the
corresponding value.If an empty slot is encountered during probing or the entire
table is probed, the key is not present in the hash table.
Step 6: Deletion:
Search for the key using the search algorithm.If the key is found, mark the
corresponding slot as deleted Step 7:
Handling Load Factor and Rehashing (Optional):
Monitor the load factor (ratio of the number of elements to the size of the hash
table). If the load factor exceeds a certain threshold, rehash the table.
Step 8: Stop
PROGRAM :
initialize hashArray
initialize HashItem
structure
hashFunction(key):
return hash value of the key
insert(key, value):
hashIndex = hashFunction(key)
while hashArray[hashIndex] is not empty and hashArray[hashIndex].key is
not key: hashIndex = (hashIndex + 1) % SIZE
hashArray[hashIndex] = new HashItem(key,
value) search(key):
hashIndex = hashFunction(key)
66
while hashArray[hashIndex] is not
empty: if hashArray[hashIndex].key is
key:
return
hashArray[hashIndex].value
hashIndex = (hashIndex + 1) %
SIZE return null // Key not found
delete(key):
hashIndex = hashFunction(key)
while hashArray[hashIndex] is not empty:
if hashArray[hashIndex].key is key:
hashArray[hashIndex] = null // Mark as
deleted return
hashIndex = (hashIndex + 1) % SIZE
OUTPUT :
(42, 80)
Element found:
97 Element not
found
RESULT:
Thus this output successfully demonstrates the basic functionality of the open addressing
(linear probing) implementation in C, showing insertion, search, and deletion operations on a hash
table.
67
EX.NO:15b IMPLEMENTATION OF OPEN ADDRESSING ( QUADRATIC PROBING)
DATE:
AIM:
write a c program to show implementation of open addressing (quadratic probing).
ALGORITHM:
Step 1: Start
Step 2: Initialization:
Initialize the hash Array with a fixed size.Initialize all elements of the hash Array
to a special value indicating an empty slot.
Step 3:Hash Function:
Calculate the hash value of a key using a suitable hashing algorithm.
Step 4:Quadratic Probing:
Quadratic probing uses a quadratic function to compute the next index to probe
in the hash table. The quadratic function is typically of the form (index + i*i) %
SIZE, where i is the probe sequence number.
Step 5:Insertion:
Compute the hash value of the key.If the calculated index in the hash Array is
empty, insert the key-value pair at that index. If the index is occupied due to a
collision, probe quadratically until an empty slot is found. Insert the key-value
pair into the first empty slot found during probing.
Step 6:Search:
Compute the hash value of the key.Start at the calculated index and probe
quadratically until an empty slot is found or the key is found. If the key is
found, return the corresponding value.If an empty slot is encountered during
probing or the entire table is probed, the key is not present in the hash table.
Step 7: Deletion:
Search for the key using the search algorithm.If the key is found, mark the
corresponding slot as deleted (usually by setting it to NULL or some sentinel
value).
Step 8 :Handling Load Factor and Rehashing (Optional):
Monitor the load factor (ratio of the number of elements to the size of the hash
table).If the load factor exceeds a certain threshold, rehash the table (create a
new table with a larger size, recalculate hash values, and reinsert all elements).
Step 9: Stop
PROGRAM :
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
typedef struct
{
int key; int data;
68
} HashItem;
HashItem *hashArray[SIZE];
HashItem *dummyItem;
HashItem *item;
int hashCode(int key)
{
return key % SIZE;
}
int quadraticProbe(int index, int i)
{
return (index + i*i) % SIZE;
}
HashItem *search(int key)
{
int hashIndex = hashCode(key);
int i = 0;
while (hashArray[hashIndex] != NULL)
{
if (hashArray[hashIndex]->key == key) { return hashArray[hashIndex];
} i++;
hashIndex = quadraticProbe(hashIndex, i);
}
return NULL;
}
void insert(int key, int data) {
HashItem *item = (HashItem*) malloc(sizeof(HashItem));
item->key = key;
item->data = data;
int hashIndex = hashCode(key);
int i = 0;
while (hashArray[hashIndex] != NULL && hashArray[hashIndex]->key != -1)
{
i++;
hashIndex = quadraticProbe(hashIndex, i);
}
hashArray[hashIndex] = item;
}
HashItem *delete(HashItem *item)
{
int key = item->key;
int hashIndex = hashCode(key);
int i = 0;
while (hashArray[hashIndex] != NULL)
{
if (hashArray[hashIndex]->key == key)
69
{
HashItem *temp = hashArray[hashIndex]; hashArray[hashIndex] = dummyItem;
return temp;
} i++;
hashIndex = quadraticProbe(hashIndex, i);
}
return NULL;
}
void display()
{
int i;
for (i = 0; i < SIZE; i++)
{
if (hashArray[i] != NULL)
printf("(%d, %d)\n", hashArray[i]->key, hashArray[i]->data);
else
printf(" ~~ ");
}
printf("\n");
}
int main() {
dummyItem = (HashItem*) malloc(sizeof(HashItem));
dummyItem->key = -1;
dummyItem->data = -1;
insert(1, 20);
insert(2, 70);
insert(42, 80);
insert(4, 25);
insert(12, 44);
insert(14, 32);
insert(17, 11);
insert(13, 78);
insert(37, 97);
display();
item = search(37);
if (item != NULL)
{
printf("Element found: %d\n", item->data);
}
Else
{
printf("Element not found\n");
}
delete(item);
70
item = search(37);
if (item != NULL) {
printf("Element found: %d\n", item->data);
}
Else
{
printf("Element not found\n");
}
return 0;
}
OUTPUT :
(42, 80)
Element found:
97 Element not
found
RESULT :
Thus, this output successfully demonstrates the basic functionality of the hash table
implemented with open addressing using quadratic probing. It showcases insertion, searching, and
deletion operations, along with handling collisions and probing through the table
71
72
73
74