0% found this document useful (0 votes)
74 views87 pages

DS Final Record WORD

The document is a lab manual for the CS3311 Data Structures Laboratory course, detailing various experiments related to data structures such as stacks, queues, linked lists, and trees. Each experiment includes an aim, algorithm, program code, and output results. It is prepared and verified by faculty members of the Computer Science and Engineering department.

Uploaded by

samprince0724
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
74 views87 pages

DS Final Record WORD

The document is a lab manual for the CS3311 Data Structures Laboratory course, detailing various experiments related to data structures such as stacks, queues, linked lists, and trees. Each experiment includes an aim, algorithm, program code, and output results. It is prepared and verified by faculty members of the Computer Science and Engineering department.

Uploaded by

samprince0724
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 87

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

LAB MANUAL

COURSE :CS3311 DATA STRUCTURES LABORATORY

YEAR/SEM :II/III CSE

Prepared By Verified By Approved By


Mrs.M.P.Sujatha, Mrs.M.P.Sujatha Dr.Balaji Madhavan
AP/CSE AP/CSE HOD/CSE
Mrs.G.Veni,
AP/CSE
Mr.Suresh Kumar
AP/CSE
INDEX

Exp Date of Page


Experiment Title Signature
No Experiment No.

1.a Array implementation of Stack

1.b Array implementation of Queue

1.c Array implementation of Circular Queue

2. Implementation of Singly Linked List

3.a Linked list implementation of Stack

3.b Linked list implementation of linear queue


ADTS

4. Implementation of polynomial
manipulation Using linked list

5.a Implementation of evaluating Infix to


Postfix conversion

5.b Implementation of Evaluating Postfix


Expression

6. Implementation of Binary Search Trees

7. Implementation of AVL Trees

8. Implementation of Heaps using Priority


queues.

9. Implementation of Dijkstra’s Algorithm

10. Implementation of Prim’s algorithm

11.a Implementation of Linear Search

11.b Implementation of Binary Search

12.a Implementation of Insertion Sort

12.b Implementation of selection sort


13 Implementation of Merge sort

14 Implementation of open Addressing


(Linear probing and Quadratic Probing)
Ex. No. 1a Stack - Array Implementation

Date:

Aim
To implement stack operations using array.

Algorithm
1. Start
2. Define a array stack of size max = 5
3. Initialize top = -1
4. Display a menu listing stack operations
5. Accept choice
6. If choice = 1 then
If top < max -1
Increment top
Store element at current position of top
Else
Print Stack overflow
Else If choice = 2 then
If top < 0 then
Print Stack underflow
Else
Display current top
element Decrement top
Else If choice = 3 then
Display stack elements starting from top
7. Stop
Program

#include <stdio.h>
#include <stdlib.h> // Include for exit function
#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("\nStack Empty\n");
}
else
{
printf("\nTop -->");
for (i = top; i >= 0; i--)
{
printf("%4d", stack[i]);
}
printf("\n");
}
}

int main()
{ // Corrected the return type of main
int ch = 0, val;
while (ch != 4) {
printf("\nSTACK OPERATION\n");
printf("1. PUSH\n");
printf("2. POP\n");
printf("3. VIEW\n");
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("\nStack Overflow\n");
}
break;
case 2:
if (top < 0)
{
printf("\nStack Underflow\n");
}
else {
val = pop();
printf("\nPopped element is %d\n", val);
}
break;
case 3:
view();
break;
case 4:
exit(0);
default:
printf("\nInvalid Choice\n");
}
}

return 0; // Return statement for main


}
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 the operations of a stack were implemented using arrays.
Ex. No. 1b Queue - Array Implementation

Date:

Aim
To implement queue operations using array.

Algorithm
1. Start
2. Define a array queue of size max = 5
3. Initialize front = rear = –1
4. Display a menu listing queue operations
5. Accept choice
6. If choice = 1
then If rear <
max -1
Increment rear
Store element at current position of rear
Else
Print Queue Full
Else If choice = 2
then If front = –1
then
Print Queue empty
Else
Display current front element
Increment front
Else If choice = 3 then
Display queue elements starting from front to rear.
7. Stop
Program

#include <stdio.h>
#include <stdlib.h> // Include for exit function
#define MAX 5

static int queue[MAX];


int front = -1;
int rear = -1;

void insert(int x) {
if (rear < MAX - 1) { // Check for queue overflow before inserting
queue[++rear] = x;
if (front == -1) // Set front to 0 when first element is inserted
front = 0;
} else {
printf("\nQueue Full\n");
}
}

int Remove() {
int val;
if (front == -1) { // Check for queue underflow
printf("\nQueue Empty\n");
return -1; // Return an error value
}
val = queue[front];
if (front == rear) { // If this was the last element
front = rear = -1; // Reset the queue
} else {
front++;
}
return val;
}

void view() {
int i;
if (front == -1) {
printf("\nQueue Empty\n");
} else {
printf("\nFront --> ");
for (i = front; i <= rear; i++) {
printf("%4d", queue[i]);
}
printf(" <-- Rear\n");
}
}

int main() { // Corrected the return type of main


int ch = 0, val;
while (ch != 4) {
printf("\nQUEUE OPERATION\n");
printf("1. INSERT\n");
printf("2. DELETE\n");
printf("3. VIEW\n");

printf("4. QUIT\n");
printf("Enter Choice: ");

scanf("%d", &ch);

switch (ch)
{
case 1:
printf("\nEnter element to be inserted: ");
scanf("%d", &val);
insert(val);
break;
case 2:
val = Remove();
if (val != -1) { // Check if removal was successful
printf("\nElement deleted: %d\n", val);
break;
case 3:
view();
break;
case 4:
exit(0);
default:
printf("\nInvalid Choice\n");
}
}

return 0; // Return statement for main


}
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 operation of queue was demonstrated using arrays.
Ex. No. 1c Circular Queue - Array Implementation

Date:

Aim

To implement circular queue operations using array.

Algorithm
1. Start
2. Initialize the variable like a[size], rear= -1 and front = 0
3. Front variable is used to get the front item from the queue.
4. Rear variable is used to get the last item from the queue.
5. Enqueue element is always inserted at rear position.
6. Check whether queue is full-check((rear == size-1 && front==0) ||(rear==front-
1)
7. If it is full then display Queue is full.If queue is not then, check
(rear==Size-1 && front!=0) if it is true then set rear=0 and insert element.
8. Dequeue element delete the element at the front position.
9. Check whether queue is Empty means check (front==-1)
10. Check if(front==rear)if it is true then set front=rear=-1 else check
if(front==size-1),if it is true then set front=0 and return the element.
11. End the Program.
Program

/*Circular queue operations using Arrays*/

#include <stdio.h>

#define MAX 5

int cqueue_arr[MAX];

int front = -1;

int rear = -1;

void insert(int item) {

if ((front == 0 && rear == MAX - 1) || (front == rear + 1))

printf("Queue Overflow\n");

return;

if (front == -1) // If queue is empty

front = 0;

rear = 0;

} else // Circular increment of rear

rear = (rear + 1) % MAX;

cqueue_arr[rear] = item;

void del()

if (front == -1)
{

printf("Queue Underflow\n");

return;

printf("Element deleted from queue is: %d\n",cqueue_arr[front]);

if (front == rear) // Queue has only one element

front = -1;

rear = -1;

} else {

// Circular increment of front

front = (front + 1) % MAX;

void display() {

if (front == -1) {

printf("Queue is empty\n");

return;

printf("Queue elements:\n");

int i = front;

while (1) {

printf("%d ", cqueue_arr[i]);

if (i == rear) {

break;

i = (i + 1) % MAX; // Circular increment


}

printf("\n");

/* Begin of main */

int main() {

int choice, item;

do {

printf("1. Insert\n");

printf("2. Delete\n");

printf("3. Display\n");

printf("4. Quit\n");

printf("Enter your choice: ");

scanf("%d", &choice);

switch (choice) {

case 1:

printf("Input the element for insertion in queue: ");

scanf("%d", &item);

insert(item);

break;

case 2:

del();

break;

case 3:

display();

break;

case 4:

break;
default:

printf("Wrong choice\n");

} while (choice != 4);

return 0;

Output

Result

Thus insert and delete operation of circular queue was demonstrated using arrays.
Ex. No. 2 Singly Linked List

Date:

Aim
To define a singly linked list node and perform operations such as insertions
and deletions dynamically.

Algorithm
1. Start
2. Define single linked list node as self referential structure
3. Create Head node with label = -1 and next = NULL using
4. Display menu on list operation
5. Accept user choice
6. If choice = 1 then
Locate node after which insertion is to be
done Create a new node and get data part
Insert new node at appropriate position by manipulating
address Else if choice = 2
Get node's data to be deleted.
Locate the node and delink the
node Rearrange the links
Else
Traverse the list from Head node to node which points to null
7. Stop
Program

/* Single Linked List */

#include <stdio.h>
#include <stdlib.h> // Use stdlib for malloc and free
#include <string.h>

struct node {
int label;
struct node *next;
};

void addNode(struct node *head, int k, int newLabel);


void deleteNode(struct node *head, int k);
void viewList(struct node *head);

int main() {
int ch, k, newLabel;
struct node *head;

// Head node construction


head = (struct node *)malloc(sizeof(struct node));
head->label = -1; // Using -1 as a sentinel value for the head
head->next = NULL;

while (1) { // Use a valid condition for the loop


printf("\n\nSINGLY LINKED LIST OPERATIONS \n");
printf("1 -> Add\n");
printf("2 -> Delete\n");
printf("3 -> View\n");
printf("4 -> Exit\n");
printf("Enter your choice: ");
scanf("%d", &ch);

switch (ch) {
case 1: // Add a node
printf("\nEnter label after which to add: ");
scanf("%d", &k);
printf("Enter label for new node: ");
scanf("%d", &newLabel);
addNode(head, k, newLabel);
break;

case 2: // Delete a node


printf("Enter label of node to be deleted: ");
scanf("%d", &k);
deleteNode(head, k);
break;
case 3: // View the list
viewList(head);
break;

case 4: // Exit
free(head); // Free allocated memory for head
exit(0);

default:
printf("Invalid choice, please try again.\n");
}
}
}

void addNode(struct node *head, int k, int newLabel) {


struct node *h = head, *temp;
int fou = 0;

while (h->next != NULL) {


if (h->label == k) {
fou = 1;
break;
}
h = h->next;
}

if (fou == 0 && h->label != k) {


printf("Node not found\n");
return;
}

temp = (struct node *)malloc(sizeof(struct node));


temp->label = newLabel;
temp->next = h->next;
h->next = temp;
printf("Node added successfully\n");
}

void deleteNode(struct node *head, int k) {


struct node *h = head, *h1 = NULL;
int fou = 0;

while (h->next != NULL) {


h1 = h; // Store the previous node
h = h->next;
if (h->label == k) {
fou = 1;
break;
}
}
if (fou == 0) {
printf("Sorry, node not found\n");
return;
}

h1->next = h->next; // Link the previous node to the next node


free(h); // Free the memory of the node to be deleted
printf("Node deleted successfully\n");
}

void viewList(struct node *head)


{
struct node *h = head->next; // Skip the head node
printf("\nHEAD -> ");
while (h != NULL)
{
printf("%d -> ", h->label);
h = h->next;
}
printf("NULL\n");
}

Output

SINGLY LINKED LIST OPERATIONS


1->Add 2->Delete 3->View 4->Exit Enter
your choice : 1
Enter label after which new node is to be added : -1 Enter label for
new node : 23

SINGLY LINKED LIST OPERATIONS


1->Add 2->Delete 3->View 4->Exit Enter
your choice : 1
Enter label after which new node is to be added : 23 Enter label for
new node : 67

SINGLY LINKED LIST OPERATIONS


1- >Add 2->Delete 3->View 4->Exit Enter
your choice : 3
HEAD -> 23 -> 67 -> NULL

Result
Thus the operations on single linked list were performed.
Ex. No. 3a Stack Using Linked List
Date:

Aim
To implement stack operations using linked list.

Algorithm
1. Start
2. Define a singly linked list node for stack
3. Create Head node
4. Display a menu listing stack operations
5. Accept choice
6. If choice = 1 then
Create a new node with data
Make new node point to first
node Make head node point to
new node
Else If choice = 2 then
Make temp node point to first node
Make head node point to next of temp
node Release memory
Else If choice = 3 then
Display stack elements starting from head node till null
7. Stop
Program

#include <stdio.h>
#include <stdlib.h> // Use stdlib.h instead of alloc.h and conio.h

struct node
{
int label;
struct node *next;
};

int main()
{
int ch = 0;
struct node *h, *temp, *head;

/* Head node construction */


head = (struct node*) malloc(sizeof(struct node));
if (head == NULL) { // Check if memory allocation was successful
printf("Memory allocation failed!\n");
return 1;
}
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);

switch (ch) {
case 1:
/* Create a new node */
temp = (struct node*) malloc(sizeof(struct node));
if (temp == NULL) { // Check if memory allocation was successful
printf("Memory allocation failed!\n");
return 1;
}
printf("Enter label for new node: ");
scanf("%d", &temp->label);
temp->next = head->next; // Insert at the beginning
head->next = temp; // Update head to point to new node
break;
case 2:
/* Pop the first node */
if (head->next == NULL) { // Check if the stack is empty
printf("Stack is empty! Cannot pop.\n");
break;
}
h = head->next; // Get the node to pop
head->next = h->next; // Update head to point to the next node
printf("Node %d deleted\n", h->label); // Use %d for integer
free(h); // Free the memory
break;

case 3:
printf("\n HEAD -> ");
h = head->next; // Start from the first actual node
/* Loop till last node */
while (h != NULL) {
printf("%d -> ", h->label);
h = h->next; // Move to the next node
}
printf("NULL \n");
break;

case 4:
// Free the remaining nodes before exiting
while (head->next != NULL) {
h = head->next;
head->next = h->next;
free(h);
}
free(head); // Free the head node
exit(0);

default:
printf("Invalid choice! Please try again.\n");
}
}
return 0; // Return 0 for successful execution
}
Output

Stack using Linked List


1->Push 2->Pop 3->View 4->Exit Enter
your choice : 1
Enter label for new node : 23 New
node added

Stack using Linked List


1->Push 2->Pop 3->View 4->Exit Enter
your choice : 1
Enter label for new node : 34

Stack using Linked List


1- >Push 2->Pop 3->View 4->Exit Enter
your choice : 3
HEAD -> 34 -> 23 -> NULL

Result
Thus push and pop operations of a stack was demonstrated using linked list.
Ex. No. 3b Queue Using Linked List
Date:

Aim
To implement queue operations using linked list.

Algorithm

1. Start
2. Define a singly linked list node for stack
3. Create Head node
4. Display a menu listing stack operations
5. Accept choice
6. If choice = 1 then
Create a new node with data
Make new node point to first
node Make head node point to
new node
Else If choice = 2 then
Make temp node point to first node
Make head node point to next of temp
node Release memory
Else If choice = 3 then
Display stack elements starting from head node till null
7. Stop
Program

/* Queue using Single Linked List */ #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 node construction */


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)
{
case 1:
/* Create a new node */
temp=(struct node *)(malloc(sizeof(struct node))); printf("Enter
label for new node : "); scanf("%d", &temp->label);

/* Reorganize the links */ h =


head;
while (h->next != NULL) h =
h->next;
h->next = temp; temp-
>next = NULL; break;
case 2:
/* Delink the first node */ 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

Queue using Linked List


1->Insert 2->Delete 3->View 4->Exit Enter your
choice : 1
Enter label for new node : 12

Queue using Linked List


1->Insert 2->Delete 3->View 4->Exit Enter your
choice : 1
Enter label for new node : 23

Queue using Linked List


1- >Insert2->Delete 3->View 4->Exit Enter
your choice : 3
HEAD -> 12 -> 23 -> NULL

Result
Thus insert and delete operations of a queue was demonstrated using linked
list.
Ex. No. 4 Polynomial Addition
Date:

Aim
To add any two given polynomial using linked lists.

Algorithm
1. Create a structure for polynomial with exp and coeffterms.
2. Read the coefficient and exponent of given two polynomials p and q.
3. While p and q are not null, repeat step 4.
If powers of the two terms are equal then
Insert the sum of the terms into the sum
Polynomial Advance p and q
Else if the power of the first polynomial> power of second
then Insert the term from first polynomial into sum
polynomial Advance p
Else
Insert the term from second polynomial into sum polynomial
Advance q
4. Copy the remaining terms from the non empty polynomial into
the sum polynomial
5. Stop
Program

/* Polynomial Addition */

/* Add two polynomials */

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

struct link
{
int coeff; int
pow;
struct link *next;
};
struct link *poly1=NULL,*poly2=NULL,*poly=NULL;

void create(struct link *node)


{
char ch;
do
{
printf("\nEnter coefficient: ");
scanf("%d", &node->coeff);
printf("Enter exponent: "); scanf("%d",
&node->pow);
node->next = (struct link*)malloc(sizeof(struct link));
node = node->next;
node->next = NULL;
printf("\n continue(y/n): ");
fflush(stdin);
ch=getch();
} while(ch=='y' || ch=='Y');
}

void show(struct link *node)


{
while(node->next!=NULL)
{
printf("%dx^%d", node->coeff, node->pow);
node=node->next;
if(node->next!=NULL)
printf(" + ");
}
}
void polyadd(struct link *poly1, struct link *poly2, struct link *poly)
{

while(poly1->next && poly2->next)


{
if(poly1->pow > poly2->pow)
{
poly->pow = poly1->pow;
poly->coeff = poly1->coeff; poly1
= poly1->next;
}
else if(poly1->pow < poly2->pow)
{
poly->pow = poly2->pow; poly-
>coeff = poly2->coeff;
poly2 = poly2->next;
}
else
{
poly->pow = poly1->pow;
poly->coeff = poly1->coeff + poly2->coeff;
poly1 = poly1->next;
poly2 = poly2->next;
}
poly->next=(struct link *)malloc(sizeof(struct link));
poly=poly->next;
poly->next=NULL;
}
while(poly1->next || poly2->next)
{
if(poly1->next)
{
poly->pow = poly1->pow;
poly->coeff = poly1->coeff;
poly1 = poly1->next;
}
if(poly2->next)
{
poly->pow = poly2->pow;
poly->coeff = poly2->coeff;
poly2 = poly2->next;
}
poly->next = (struct link *)malloc(sizeof(struct link));
poly = poly->next;
poly->next = NULL;
}
}
main()
{
poly1 = (struct link *)malloc(sizeof(struct link));
poly2 = (struct link *)malloc(sizeof(struct link));
poly = (struct link *)malloc(sizeof(struct link));
printf("Enter 1st Polynomial:");
create(poly1);
printf("\nEnter 2nd Polynomial:");
create(poly2);
printf("\nPoly1: ");
show(poly1); printf("\
nPoly2: "); show(poly2);
polyadd(poly1, poly2, poly); printf("\
nAdded Polynomial: ");
show(poly);
}

Output

Enter 1st Polynomial:


Enter coefficient: 5
Enter exponent: 2
continue(y/n): y
Enter coefficient: 4
Enter exponent: 1
continue(y/n): y
Enter coefficient: 2
Enter exponent: 0
continue(y/n): n

Enter 2nd Polynomial:


Enter coefficient: 5
Enter exponent: 1
continue(y/n): y
Enter coefficient: 5
Enter exponent: 0
continue(y/n): n

Poly1: 5x^2 + 4x^1 + 2x^0


Poly2: 5x^1 + 5x^0
Added Polynomial: 5x^2 + 9x^1 + 7x^0

Result
Thus the two given polynomials were added using lists.
Ex. No. 5a Infix To Postfix Conversion

Date:

Aim
To convert infix expression to its postfix form using stack operations.

Algorithm
1. Start
2. Define a array stack of size max = 20
3. Initialize top = -1
4. Read the infix expressioncharacter-by-
character If character is an operand
printit
If character is an operator
Compare the operator’s priority with the stack[top] operator.
If the stack [top] has higher/equal priority than the input
operator, Pop it from the stack and print it.
Else
Push the input operator onto the stack
If character is a left parenthesis, then push it onto the stack.
If character is a right parenthesis, pop all operators from stack
and print it until a left parenthesis is encountered. Do not print the
parenthesis.
If character = $ then Pop out all operators, Print them and Stop
.
Program

#include <stdio.h>
#include <string.h>
#define MAX 20

int top = -1;


char stack[MAX];

void push(char item);


char pop();
int prcd(char symbol);
int isoperator(char symbol);
void convertip(char infix[], char postfix[]);

int prcd(char symbol)


{
switch (symbol)
{
case '+':
case '-':
return 2;
case '*':
case '/':
return 4;
case '^':
case '$':
return 6;
case '(':
return 1;
case ')':
return 1; // Should return a precedence value for closing parenthesis
default:
return 0; // Return 0 for unrecognized symbols
}
}

int isoperator(char symbol)


{
switch (symbol)
{
case '+':
case '-':
case '*':
case '/':
case '^':
case '$':
case '(':
case ')':
return 1;
default:
return 0;
}
}
void convertip(char infix[], char postfix[])

{
int i, symbol, j = 0;
stack[++top] = '#'; // Initialize stack with a bottom marker

for (i = 0; i < strlen(infix); i++)


{
symbol = infix[i];
if (isoperator(symbol) == 0)
{
postfix[j++] = symbol; // Add operand to postfix
}
else
{
if (symbol == '(')
{
push(symbol); // Push '(' onto stack
}
else if (symbol == ')')
{
while (top != -1 && stack[top] != '(')
{
postfix[j++] = pop(); // Pop until '('
}
if (top != -1) pop(); // Pop the '(' from the stack
}

else
{
while (top != -1 && prcd(symbol) <= prcd(stack[top]))
{
postfix[j++] = pop(); // Pop operators from stack
}
push(symbol); // Push the current operator onto the stack
}
}
}

while (top != -1 && stack[top] != '#')


{
postfix[j++] = pop(); // Pop remaining operators
}
postfix[j] = '\0'; // Null-terminate the postfix string
}

int main()
{
char infix[20], postfix[20];
printf("Enter the valid infix string: ");
fgets(infix, sizeof(infix), stdin);
infix[strcspn(infix, "\n")] = 0; // Remove newline character if present
convertip(infix, postfix);
printf("The corresponding postfix string is: %s\n", postfix);
return 0; // Return 0 for successful execution
}
void push(char item)
{
if (top < MAX - 1) { // Check for stack overflow
stack[++top] = item;
}
else
{
printf("Stack overflow! Cannot push %c\n", item);
}
}

char pop() {
if (top != -1)
{ // Check for stack underflow
return stack[top--];
}
else
{
printf("Stack underflow! Cannot pop.\n");
return '\0'; // Return null character on underflow
}
}

Output

Enter the valid infix string: (a+b*c)/(d$e) The


corresponding postfix string is: abc*+de$/

Enter the valid infix string: a*b+c*d/e


The corresponding postfix string is: ab*cd*e/+

Enter the valid infix string: a+b*c+(d*e+f)*g


The corresponding postfix string is: abc*+de*f+g*+

Result
Thus the given infix expression was converted into postfix form using stack.
Ex. No. 5b Postfix Expression Evaluation

Date:

Aim
To evaluate the given postfix expression using stack operations.

Algorithm
1. Start
2. Define a array stack of size max = 20
3. Initialize top = -1
4. Read the postfix expression character-by-character
If character is an operand push it onto the
stack If character is an operator
Pop topmost two elements from stack.
Apply operator on the elements and push the result onto the
stack,
5. Eventually only result will be in the stack at end of the expression.
6. Pop the result and print it.
7. Stop
Program

/* Evaluation of Postfix expression using stack */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX 50 // For isdigit function

// Define a constant for the stack size struct stack


{
int top;
struct float a[MAX]; // Use a member for top within the stack
};
void push(struct stack *s, float value)
{
if (s->top < MAX - 1)
{
s->a[++(s->top)] = value; // Check for stack overflow
}
else
{
printf("Stack overflow! Cannot push %.2f\n", value);
}
}
float pop(struct stack *s)
{
if (s->top != -1)
{
// Check for stack underflow
return s->a[(s->top)--];
}
else
{
printf("Stack underflow! Cannot pop.\n");
return 0; // Return 0 on underflow
}
}
int main()
{
struct stack s; s.top = -1; // Initialize top to -1
char pf[50];
float d1, d2; int i;
printf("\n\nEnter the postfix expression: ");
fgets(pf, sizeof(pf), stdin); // Use fgets to read input
pf[strcspn(pf, "\n")] = 0;
for (i = 0; pf[i] != '\0'; i++)
{
if (isdigit(pf[i])) // Check if the character is a digit
{
push(&s, pf[i] - '0'); // Push the numeric value onto the stack
}
else
{
switch (pf[i])
{
case '+': d2 = pop(&s);
d1 = pop(&s);
push(&s, d1 + d2);
break;
case '-': d2 = pop(&s);
d1 = pop(&s);
push(&s, d1 - d2);
break;
case '*': d2 = pop(&s);
d1 = pop(&s);
push(&s, d1 * d2);
break;
case '/': d2 = pop(&s);
d1 = pop(&s);
if (d2 != 0) // Check for division by zero
{
push(&s, d1 / d2);
}
else
{
printf("Error: Division by zero.\n");
return 1; // Exit with error code

}
break;
default:
printf("Error: Invalid character '%c' in expression.\n", pf[i]);
return 1; // Exit with error code for invalid character
}
}
}
printf("\nExpression value is %.2f\n", s.a[s.top]); // Output the result
return 0; // Return 0 for successful execution

Output

Enter the postfix expression: 6523+8*+3+*


Expression value is 288.00

Result
Thus the given postfix expression was evaluated using stack.
Ex. No. 6 Binary Search Tree

Date:

Aim
To insert and delete nodes in a binary search tree.

Algorithm
1. Create a structure with key and 2 pointer variable left and right.
2. Read the node to be inserted.
If(root==NULL)
root=node
else if (root->key<node-
>key) root-
>right=NULL
else
Root->left=node
3. For
Deletion
if it is a leaf node
Remove immediately
Remove pointer between del node &
child if it is having one child
Remove link between del
node&child Link delnode is child with
delnodes parent
If it is a node with a children
Find min value in right subtree
4. Stop Copy min value to delnode
place Delete the duplicate
Program

/* Binary Search Tree */

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

struct node
{
int key;
struct node *left;
struct node *right;
};

struct node *newNode(int item)


{
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}

void inorder(struct node *root)


{
if (root != NULL)
{
inorder(root->left); printf("%d ",
root->key); inorder(root->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
node->right = insert(node->right, key); return
node;
}

struct node * minValueNode(struct node* node)


{
struct node* current = node; while
(current->left != NULL)
current = current->left; return
current;
}
struct node* deleteNode(struct node* root, int key)
{
struct node *temp; if
(root == NULL) return
root;
if (key < root->key)
root->left = deleteNode(root->left, key); else if (key
> root->key)
root->right = deleteNode(root->right, key); else
{
if (root->left == NULL)
{
temp = root->right;
free(root);
return temp;
}
else if (root->right == NULL)
{
temp = root->left;
free(root); return
temp;
}
temp = minValueNode(root->right);
root->key = temp->key;
root->right = deleteNode(root->right, temp->key);
}
return root;
}

main()
{
struct node *root = NULL; root
= insert(root, 50); root =
insert(root, 30); root =
insert(root, 20); root =
insert(root, 40); root =
insert(root, 70); root =
insert(root, 60); root =
insert(root, 80);
printf("Inorder traversal of the given tree \n"); inorder(root);
printf("\nDelete 20\n"); root =
deleteNode(root, 20);
printf("Inorder traversal of the modified tree \n"); inorder(root);
printf("\nDelete 30\n"); root =
deleteNode(root, 30);
printf("Inorder traversal of the modified tree \n"); inorder(root);
printf("\nDelete 50\n");
root = deleteNode(root, 50);
printf("Inorder traversal of the modified tree \n"); inorder(root);
}

Output

Inorder traversal of the given tree 20 30 40


50 60 70 80
Delete 20
Inorder traversal of the modified tree 30 40 50
60 70 80
Delete 30
Inorder traversal of the modified tree 40 50 60
70 80
Delete 50
Inorder traversal of the modified tree 40 60 70
80

Result
Thus nodes were inserted and deleted from a binary search tree.
Ex. No. 7 AVL Trees

Date:

Aim
To perform insertion operation on an AVL tree and to maintain balance
factor.

Algorithm
1. Start
2. Perform standard BST insert for w
3. Starting from w, travel up and find the first unbalanced node. Let z be
the first unbalanced node, y be the child of z that comes on the path
from w to z and x be the grandchild of z that comes on the path from w
to z.
4. Re-balance the tree by performing appropriate rotations on the subtree
rooted with z. There can be 4 possible cases that needs to be handled as
x, y and z can be arranged in 4 ways.
a) y is left child of z and x is left child of y (Left Left Case)
b) y is left child of z and x is right child of y (Left Right Case)
c) y is right child of z and x is right child of y (Right Right Case)
d) y is right child of z and x is left child of y (Right Left Case)
5. Stop
Program

/* AVL Tree */
#include <stdio.h>
#include <stdlib.h>
#define CHANGED 0 // For malloc and free
#define BALANCED 1
typedef struct bnode
{
int data, bfactor;
struct bnode *left;
struct bnode *right;
}
node;
int height;
void displaymenu()
{
printf("\nBasic Operations in AVL tree");
printf("\n0.Display menu list");
printf("\n1.Insert a node in AVL tree");
printf("\n2.View AVL tree");
printf("\n3.Exit");
}
node* getnode()
{
node *newnode = (node*)malloc(sizeof(node));
if (newnode == NULL)
{ printf("Memory allocation failed\n");
exit(1);
}
return newnode;
}
void copynode(node *r, int data)
{
r->data = data;
r->left = NULL;
r->right = NULL;
r->bfactor = 0;
}
void releasenode(node *p)
{
if (p != NULL)
{
releasenode(p->left);
releasenode(p->right);
free(p);
}
}
node* searchnode(node *root, int data)
{
if (root == NULL || root->data == data)
return root;
if (data < root->data)
return searchnode(root->left, data);
else
return searchnode(root->right, data);
}
void lefttoleft(node **pptr, node **aptr)
{
node *p = *pptr;
node *a = *aptr;
printf("\nLeft to Left AVL rotation");
p->left = a->right;
a->right = p;
if (a->bfactor == 0)
{
p->bfactor = 1;
a->bfactor = -1;
height = BALANCED;
}
else
{
p->bfactor = 0;
a->bfactor = 0;
}
*pptr = a;
}
void lefttoright(node **pptr, node **aptr, node **bptr)
{
node *p = *pptr;
node *a = *aptr;
node *b = *bptr;
printf("\nLeft to Right AVL rotation");
b = a->right;
a->right = b->left;
b->left = a;
p->left = b->right;
b->right = p;
if (b->bfactor == 1)
{
p->bfactor = -1;
}
else
{
p->bfactor = 0;
}
if (b->bfactor == -1)
{
a->bfactor = 0;
}
else
{
a->bfactor = 1;
}
b->bfactor = 0;
*pptr = b;
}
void righttoright(node **pptr, node **aptr)
{
*a = *aptr;
printf("\nRight to Right AVL rotation");
p->right = a->left;
a->left = p;
if (a->bfactor == 0)
{
p->bfactor = -1;
a->bfactor = 1;
height = BALANCED;
}
else
{
p->bfactor = 0;
a->bfactor = 0;
}
*pptr = a;
}
void righttoleft(node **pptr, node **aptr, node **bptr)
{
node *p = *pptr;
node *a = *aptr;
node *b = *bptr;
printf("\nRight to Left AVL rotation");
b = a->left;
a->left = b->right;
b->right = a;
p->right = b->left;
b->left = p;
if (b->bfactor == -1)
{
p->bfactor = 1;
}
else
{
p->bfactor = 0;
}
if (b->bfactor == 1)
{
a->bfactor = 0;
}
else
{
a->bfactor = -1;
}
b->bfactor = 0;
*pptr = b;
}
void inorder(node *root)
{
if (root == NULL)
return;
inorder(root->left);
printf("\n%4d", root->data);
inorder(root->right);
}
void view(node *root, int level)
{
int k;
if (root == NULL)
return;
view(root->right, level + 1);
printf("\n");
for (k = 0; k < level; k++)
printf(" ");
printf("%d", root->data);
view(root->left, level + 1);
}
node* insertnode(int data, node *p)
{
node *a, *b;
if (p == NULL)
{
p = getnode();
copynode(p, data);
height = CHANGED; return p;
}
if (data < p->data)
{
p->left = insertnode(data, p->left);
if (height == CHANGED)
{
switch (p->bfactor)
{
case -1:
p->bfactor = 0;
height = BALANCED;
break;
case 0:
p->bfactor = 1;
break;
case 1:
a = p->left;
if (a->bfactor == 1)
{
lefttoleft(&p, &a);
}

else
{
lefttoright(&p, &a, &b);
}
height = BALANCED;
break;
}
}
}
else if (data > p->data)
{
p->right = insertnode(data, p->right);
if (height == CHANGED)
{
switch (p->bfactor)
{
case 1:
p->bfactor = 0;
height = BALANCED;
break;
case 0:
p->bfactor = -1;
break;
case -1:
a = p->right;
if (a->bfactor == -1)
{
righttoright(&p, &a);
}
else
{
righttoleft(&p, &a, &b);
}
height = BALANCED;
break;
}
}
}
return p;
}
int main()
{
int data, ch;
char choice = 'y';
node *root = NULL;
displaymenu();
while (choice == 'y' || choice == 'Y')
{
printf("\nEnter your choice: ");
scanf("%d", &ch);

switch (ch)
{
case 0:
displaymenu();
break;
case 1:
printf("Enter the value to be inserted: ");
scanf("%d", &data);
if (searchnode(root, data) == NULL)
{
root = insertnode(data, root);
}
else
{
printf("\nData already exists");
}
break;
case 2: if (root == NULL)
{
printf("\nAVL tree is empty");
}
else
{
printf("\nInorder traversal of AVL tree:");
inorder(root);
printf("\nAVL tree is:");
view(root, 1);
}
break;
case 3: releasenode(root);
exit(0);
default:
printf("\nInvalid choice. Please try again.");
}
printf("\nDo you want to continue (y/n)? ");
scanf(" %c", &choice);
}
return 0;
}
Output

Basic Operations in AVL tree


0.Display menu list
1.Insert a node in AVL tree
2.View AVL tree
3.Exit
Enter your choice: 1
Enter the value to be inserted 1

Enter your choice: 1


Enter the value to 2
be inserted

Enter your choice: 1


3
Enter the value to be inserted

Right to Right AVL rotation

Enter your choice: 1


4
Enter the value to be inserted

Enter your choice: 1


5
Enter the value to be inserted
Right to Right AVL rotation
Enter your choice: 1
Enter the value to be inserted 6

Right to Right AVL rotation Enter

your choice: 1
Enter the value to be inserted 7 Right

to Right AVL rotation

Enter your choice: 1


Enter the value to be inserted 8

Enter your choice: 2


Inorder traversal of AVL tree 1
2
3
4
5
6
7
8
AVL tree is
8
7
6
5
4
3
2
1
Enter your choice: 3

Result
Thus rotations were performed as a result of insertions to AVL Tree.
Ex.NO:8 Implementation of Priority Queue Using Heaps

Date:

Aim
To write a C program to implement Priority Queue using Binary Heaps.
Algorithm
1. Initialize all necessary variables and functions.
2. Read the choices
3. For insertion, read the element to be inserted.
4. If root is NULL,assign the given element as root.
5.If the element is equal to the root, print Duplicate value.
6.Else if element value is less than the root value insert element at the
leftroot
7.Else insert right side of the root.
8. For deletion, get the priority for maximum or minimum.
9. If maximum, it deletes the root and rearranges the tree.
10. If minimum, it deletes the leaf.
11. End of the program.
Program

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

enum { FALSE = 0, TRUE = -1 };

struct Node
{
struct Node *Previous;
int Data;
struct Node *Next;
};

struct Node *head = NULL;


struct Node *ptr = NULL;
static int NumOfNodes = 0;

int PriorityQueue(void);
int Maximum(void);
int Minimum(void);
void Insert(int DT);
int Delete(int DataDel);
void Display(void);
int Search(int DataSearch);

int main()
{
int choice;
int DT;

PriorityQueue();

while (1) {

printf("\nEnter your Choice:");


printf("\n1.Insert\n2.Display\n3.Delete\n4.Search\n5.Exit\n");
scanf("%d", &choice);
switch (choice)
{
case 1:
printf("\nEnter a data to enter Queue: ");
scanf("%d", &DT);
Insert(DT);
break;
case 2:
Display();
break;
case 3:
{
int choice, DataDel;
printf("\nEnter your choice:");
printf("\n1.Maximum Priority queue\n2.Minimum priority Queue\n");
scanf("%d", &choice);
switch (choice) {
case 1:
DataDel = Maximum();
if (Delete(DataDel))
printf("\n%d is deleted\n", DataDel);
else
printf("\nError deleting %d\n", DataDel);
break;
case 2:
DataDel = Minimum();
if (Delete(DataDel))
printf("\n%d is deleted\n", DataDel);
else
printf("\nError deleting %d\n", DataDel);
break;
default:
printf("\nSorry, not a correct choice\n");
}
break;
}
case 4:
printf("\nEnter a data to Search in Queue: ");
scanf("%d", &DT);
if (Search(DT) != FALSE)
printf("\n%d is present in queue", DT);
else
printf("\n%d is not present in queue", DT);
break;
case 5:
exit(0);
default:
printf("\nCannot process your choice\n");
}
}
}

int PriorityQueue(void)
{
printf("\nEnter first element of Queue: ");
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
if (!newNode) {
printf("Memory allocation failed\n");
exit(1);
}
scanf("%d", &newNode->Data);
newNode->Previous = NULL;
newNode->Next = NULL;
head = newNode;
ptr = head;
NumOfNodes++;
return 0;
}

int Maximum(void)
{
if (head == NULL) return FALSE; // Handle empty queue

int maxVal = head->Data;


ptr = head;

while (ptr != NULL)


{
if (ptr->Data > maxVal)
{
maxVal = ptr->Data;
}
ptr = ptr->Next;
}
return maxVal;
}

int Minimum(void) {
if (head == NULL) return FALSE; // Handle empty queue

int minVal = head->Data;


ptr = head;

while (ptr != NULL)


{
if (ptr->Data < minVal)
{
minVal = ptr->Data;
}
ptr = ptr->Next;
}
return minVal;
}

void Insert(int DT) {


struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
if (!newNode) {
printf("Memory allocation failed\n");
exit(1);
}

newNode->Data = DT;
newNode->Next = NULL;
// Insert at the end of the queue
if (head == NULL) {
newNode->Previous = NULL;
head = newNode;
}
else
{
ptr = head;
while (ptr->Next != NULL)
{
ptr = ptr->Next;
}
ptr->Next = newNode;
newNode->Previous = ptr;
}

NumOfNodes++;
}

int Delete(int DataDel)


{
struct Node *temp = head;
if (temp == NULL) return FALSE; // Empty list

// Check if the head needs to be deleted


if (temp->Data == DataDel)
{
head = temp->Next;
if (head != NULL) {
head->Previous = NULL; // Update head's previous
}
free(temp);
NumOfNodes--;
return TRUE;
}

// Search for the node to delete


while (temp != NULL && temp->Data != DataDel)
{
temp = temp->Next;
}

if (temp == NULL) return FALSE; // Not found

// Adjust pointers
if (temp->Next != NULL)
{
temp->Next->Previous = temp->Previous;
}
if (temp->Previous != NULL)
{
temp->Previous->Next = temp->Next;
}
free(temp);
NumOfNodes--;
return TRUE;
}

int Search(int DataSearch)


{
ptr = head;
while (ptr != NULL) {
if (ptr->Data == DataSearch) return TRUE;
ptr = ptr->Next;
}
return FALSE;
}

void Display(void) {
ptr = head;
printf("\nPriority Queue is as follows:-\n");
while (ptr != NULL) {
printf("\t\t%d", ptr->Data);
ptr = ptr->Next;
}
printf("\n");
}
OUTPUT

RESULT

Thus the Priority Queue using Binary Heap is implemented and the result is
verified successfully.
Ex. No. 9 Dijkstra’s Shortest Path

Date:

Aim
To find the shortest path for the given graph from a specified source to all
other
vertices using Dijkstra’s algorithm.

Algorithm
1. Start
2. Obtain no. of vertices and adjacency matrix for the given graph
3. Create cost matrix from adjacency matrix. C[i][j] is the cost of going
from vertex i to vertex j. If there is no edge between vertices i and j
then C[i][j] is infinity
4. Initialize visited[] to zero
5. Read source vertex and mark it as visited
6. Create the distance matrix, by storing the cost of vertices from vertex
no. 0 to n-1 from the source vertex
distance[i]=cost[0][i];
7. Choose a vertex w, such that distance[w] is minimum and visited[w] is
0. Mark visited[w] as 1.
8. Recalculate the shortest distance of remaining vertices from the source.
9. Only, the vertices not marked as 1 in array visited[ ] should be
considered for recalculation of distance. i.e. for each vertex v
if(visited[v]==0)
distance[v]=min(distance[v]
distance[w]+cost[w][v])
10. Stop
Program

/* Dijkstra’s Shortest Path */

#include <stdio.h>

#include <conio.h>

#define INFINITY 9999

#define MAX 10

int main() {

int G[MAX][MAX], i, j, n, u;

printf("Enter number of vertices: ");

scanf("%d", &n);

printf("Enter the adjacency matrix:\n");

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

for (j = 0; j < n; j++)

scanf("%d", &G[i][j]);

printf("Enter the starting node: ");

scanf("%d", &u);

dijkstra(G, n, u);

return 0;

void dijkstra(int G[MAX][MAX], int n, int startnode)

int cost[MAX][MAX], distance[MAX], pred[MAX];

int visited[MAX], count, mindistance, nextnode, i, j;

// Create the cost matrix

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

for (j = 0; j < n; j++)


cost[i][j] = (G[i][j] == 0) ? INFINITY :

G[i][j];

// Initialize distance, predecessor, and

visited arrays

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

distance[i] = cost[startnode][i];

pred[i] = startnode;

visited[i] = 0;

distance[startnode] = 0;

visited[startnode] = 1;

count = 1;

// Dijkstra's algorithm

while (count < n - 1) {

mindistance = INFINITY;

// Find the next node with the smallest

distance

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

if (distance[i] < mindistance && !

visited[i]) {

mindistance = distance[i];

nextnode = i;

// Mark the next node as visited

visited[nextnode] = 1;

// Update the distance and predecessor for adjacent nodes


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

if (!visited[i])

if (mindistance + cost[nextnode][i] < distance[i])

distance[i] = mindistance + cost[nextnode][i];

pred[i] = nextnode;

count++;

// Print the distance and path to each node

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

if (i != startnode)

printf("\nDistance to node %d = %d", i, distance[i]);

printf("\nPath = %d",i);

j = i;

do

j = pred[j];

printf("<-%d", j);

} while (j !=startnode);

}
}
Output

Enter no. of vertices: 5 Enter the


adjacency matrix:
0 10 0 30 100
10 0 50 0 0
0 50 0 20 10
30 0 20 0 60
100 0 0 60 0
Enter the starting node: 0
Distance to node1 = 10 Path =
1<-0
Distance to node2 = 50
Path = 2<-3<-0
Distance to node3 = 30
Path = 3<-0
Distance to node4 = 60
Path = 4<-2<-3<-0

Result
Thus Dijkstra's algorithm is used to find shortest path from a given vertex.
Ex. No. 10 Prim’s Algorithm
Date:

Aim
To write a C Program to implement Prim’s Algorithm.

Algorithm
This algorithm creates spanning tree with minimum weight from a given weighted graph.

1. Begin
2. Create edge list of given graph, with their weights.
3. 3.Draw all nodes to create skeleton for spanning tree.
4. Select an edge with lowest weight and add it to skeletonand delete edge from edge
list.
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.
6. Repeat step 5 until n-1 edges are
added.
7.Return.
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;
}
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;
no_of_edges=n-1;
while(no_of_edges>0)
{
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]; spanning[u]
[v]=distance[v]; spanning[v]
[u]=distance[v]; no_of_edges--;
visited[v]=1; 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:
0316 00
3050 30
1505 64
6050 02
0360 06

spanning tree matrix:


031 0 00
300 0 30
100 0 04
000 0 02
030 0 00
004 2 00

Total cost of spanning tree=13

Result
Thus Prim’s algorithm is used to find shortest path from a given vertex.
Ex. No. 11a Linear
Search Date:

Aim
To perform linear search of an element on the given array.

Algorithm
1. Start
2. Read number of array elements n
3. Read array elements Ai, i = 0,1,2,…n–1
4. Read search value
5. Assign 0 to found
6. Check each array element against search
If Ai = search then
found = 1
Print "Element found"
Print position i
Stop
7. If found = 0 then
print "Element not found"
8. Stop
Program

/* Linear search on a sorted array */

#include <stdio.h>

int main()

int a[50], i, n, val, found;

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; // Initialize found flag

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

if (a[i] == val)

printf("Element found at position %d\n", i);

found = 1;

break; // Exit loop after finding the

element

}
if (found == 0)

printf("\nElement not found\n");

return 0; // Return 0 to indicate successful completion

Output

Enter number of elements : 7


Enter Array Elements :
23 6 12 5 0 32 10
Enter element to locate : 5
Element found at position : :3

Result
Thus an array was linearly searched for an element's existence.
Ex. No. 11b Binary Search
Date:

Aim
To locate an element in a sorted array using Binary search method

Algorithm
1. Start
2. Read number of array elements, say n
3. Create an array arr consisting n sorted elements
4. Get element, say key to be located
5. Assign 0 to lower and n to upper
6. While (lower < upper)
Determine middle element mid =
(upper+lower)/2 If key = arr[mid] then
Print mid
Stop
Else if key > arr[mid]
then lower = mid
+1
else
upper = mid – 1

7. Print "Element not found"


8. Stop
Program

/* Binary Search on a sorted array */

#include <stdio.h>

int main()

int a[50], i, n, upper, lower, mid, val, found;

printf("Enter array size: ");

scanf("%d", &n);

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

a[i] = 2 * i; // Fill the array with even numbers

printf("\nElements in Sorted Order:\n");

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

printf("%4d", a[i]);

printf("\nEnter element to locate: ");

scanf("%d", &val);

upper = n - 1; // Set upper to last index

lower = 0;

found = -1;

while (lower <= upper)

mid = (upper + lower) / 2;

if (a[mid] == val)
{

printf("Located at position %d\n", mid);

found = 1;

break;

else if (a[mid] > val)

upper = mid - 1;

else

lower = mid + 1;

if (found == -1)

printf("Element not found\n");

return 0; // Return 0 to indicate successful completion

}
Output

Enter array size : 9 Elements


in Sorted Order
0 2 4 6 8 10 12 14 16
Enter element to locate : 12
Located at position 6

Enter array size : 10 Elements


in Sorted Order
0 2 4 6 8 10 12 14 16 18
Enter element to locate : 13
Element not found

Result
Thus an element is located quickly using binary search method.
Ex. No. 12.a Insertion Sort

Date:

Aim
To sort an array of N numbers using Insertion

sort. Algorithm

1. Start
2. Read number of array
elements n 3.Read array
elements Ai
4. Sort the elements using insertion sort
In pass p, move the element in position p left until its correct place is
found among the first p + 1 elements.
Element at position p is saved in temp, and all larger elements (prior to
position p) are moved one spot to the right. Then temp is placed in the
correct spot.
5. Stop
Program

/* Insertion Sort */

#include <stdio.h>

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

// Insertion Sort Algorithm

for (i = 1; i < n; i++)

temp = a[i];

j = i - 1;

// Move elements of a[0..i-1] that are greater than temp

while ((j >= 0) && (temp < a[j]))

a[j + 1] = a[j];

j = j - 1;

a[j + 1] = temp;

p++;

printf("\nAfter Pass %d: ", p);


for (k = 0; k < n; k++)

printf("%d ", a[k]);

printf("\nSorted List: ");

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

printf("%d ", a[i]);

printf("\n");

return 0; // Return 0 to indicate successful completion

Output

Enter total elements: 6


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
Thus array elements was sorted using insertion sort.
Ex No.12.b Selection Sort

Date:

Aim

To write a C Program to implement a Selection Sort.

Algorithm

1 Set min to the first location


2 Search the minimum element in the array
3 swap the first location with the minimum value in the array
4 assign the second element as min.
5 Repeat the process until we get a sorted array.
PROGRAM

/*Selection sort*/

#include <stdio.h>

// Function prototype
void SelSort(int array[], int n);

int main()
{
int array[100], n, i;

// Input number of elements


printf("Enter number of elements: ");
scanf("%d", &n);

// Input array elements


printf("Enter %d numbers:\n", n);
for (i = 0; i < n; i++)
{
scanf("%d", &array[i]);
}

// Perform selection sort


SelSort(array, n);

return 0;
}

// Selection Sort function


void SelSort(int array[], int n)
{
int i, j, position, swap;

for (i = 0; i < n - 1; i++)


{
position = i;

for (j = i + 1; j < n; j++)


{
if (array[position] > array[j])
{
position = j; // Find the index of the minimum element
}
}

// Swap the found minimum element with the first element


if (position != i)
{
swap = array[i];
array[i] = array[position];
array[position] = swap;
}
}
// Print the sorted array
printf("Sorted Array:\n");
for (i = 0; i < n; i++)
{
printf("%d\n", array[i]);
}
}

OUTPUT:
Enter number of
elements 4
Enter 4 Numbers
4
2
7
1
Sorted
Array 1
2
4
7

Result
Thus array elements was sorted using Selection sort.
Ex. No. 13 Merge Sort

Date:

Aim
To sort an array of N numbers using Merge sort.

Algorithm
1. Start
2. Read number of array elements n
3. Read array elements Ai
4. Divide the array into sub-arrays with a set of elements
5. Recursively sort the sub-arrays
6. Merge the sorted sub-arrays onto a single sorted array.
7. Stop
Program

/* Merge sort */

#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 i, 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 : ");
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

Enter total no. of elements : 8


Enter array elements : 24 13 26 1 2 27 38 15

Half sorted list : 1 13 24 26


Half sorted list : 2 15 27 38
Merge sorted list : 1 2 13 15 24 26 27 38

Result
Thus array elements was sorted using merge sort's divide and conquer
method.
Ex. No. 14 Open Addressing Technique (Linear and Quadratic probing)

Date:

Aim
To implement open addressing using a C program.

Algorithm
1. Create a structure, data (hash table item) with key and value as data.
2. Now create an array ofstructure, data ofsome certain size (10, in this
case).But, the size of array must be immediately updated to a prime
number just greater than initial array capacity (i.e 10, in this case).
3. A menu is displayed on the screen.
4. User must choose one option from four choices given in the menu
5. Perform all the operations
6. Stop
PROGRAM:
/*Open Addressing Hashing Technique*/

#include <stdio.h>

int tsize; // Size of the hash table

// Hash function to calculate initial index


int hasht(int key)
{
return key % tsize;
}

// Linear probing
int rehashl(int key)
{
return (key + 1) % tsize;
}

// Quadratic probing
int rehashq(int key, int j)
{
return (key + (j * j)) % tsize;
}

int main()
{
int key, arr[20], hash[20], i, n, op, j, k;
printf("Enter the size of the hash table: ");
scanf("%d", &tsize);
// Ensure size is positive
if (tsize <= 0)
{
printf("Invalid hash table size!\n");
return 1;
}

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


scanf("%d", &n);

// Ensure the number of elements does not exceed the hash table size
if (n > tsize)
{
printf("Number of elements exceeds hash table size!\n");
return 1;
}
// Initialize the hash table
for (i = 0; i < tsize; i++)
{
hash[i] = -1; // -1 indicates an empty slot
}

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: // Linear Probing
// Reinitialize the hash table
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 hash table are: ");
for (i = 0; i < tsize; i++)
{
if (hash[i] != -1)
{
printf("\nElement at position %d: %d", i, hash[i]);
}
else
{
printf("\nElement at position %d: Empty", i);
}
}
break;
case 2: // Quadratic Probing
// Reinitialize the hash table
for (i = 0; i < tsize; i++)
{
hash[i] = -1;
}
for (k = 0; k < n; k++)
{
j = 0; // Initialize j for quadratic probing
key = arr[k];
i = hasht(key);
while (hash[i] != -1)
{
i = rehashq(key, j);
j++; // Increment j for the next probe
}
hash[i] = key;
}
printf("\nThe elements in the hash table are: ");
for (i = 0; i < tsize; i++)
{
if (hash[i] != -1)
{
printf("\nElement at position %d: %d", i, hash[i]);
}
else
{
printf("\nElement at position %d: Empty", i);
}
}
break;

case 3: // Exit
printf("Exiting...\n");
break;
default:
printf("Invalid option! Please try again.\n");
}
}
while (op != 3);

return 0; // Return 0 to indicate successful completion


}
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 hashing has been performed successfully.

You might also like