Download as pdf or txt
Download as pdf or txt
You are on page 1of 74

PGP COLLEGE OF ENGINEERING AND TECHNOLOGY

NAMAKKAL – 637 207

NAME : …………………………………………........................

REG. NO : …………………………………………........................

YEAR/SEM : …………………………………………........................

BRANCH : …………………………………………........................
PGP COLLEGE OF ENGINEERING AND TECHNOLOGY
NAMAKKAL – 637 207

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

CERTIFICATE

This is to certify that bonafide record work done by Mr /Ms…………………………...…………

Register Number ………………..………………………… - BX4001 - DATA STRUCTURES AND

ALGORITHMS PRACTICAL during the academic year 2023-2024(ODD SEMESTER).

Faculty In-Charge Head of Department

Submitted for University Practical Examination held on

INTERNAL EXAMINER EXTERNAL EXAMINER


lOMoAR cPSD| 10518309

lOMoAR cPSD| 10518309

BX4001 DATA STRUCTURES AND ALGORITHMS LAB(REGULATIONS-2021)

List of Experiments

S.No Name of the Experiment


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
Implementation of Evaluating Postfix Expressions,
5.
Infix to Postfix conversion
6. Implementation of Binary Search Trees
7. Implementation of Prim’s Algorithm.
8. Implementation of Linear Search and Binary Search
9. Implementation of Insertion Sort and Selection Sort
10. Implementation of Merge Sort
Implementation of Open Addressing
11.
(Linear Probing and Quadratic Probing)

12. Implementation of Breadth First Search using Queue

13. Implementation of Topological Sort


lOMoAR cPSD| 10518309

INDEX

S.No. Name of the Experiment Page. No Signature


Date

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
Implementation of Evaluating Postfix
5. Expressions,
Infix to Postfix conversion
6. Implementation of Binary Search Trees

7. Implementation of Prim’s Algorithm.

8. Implementation of Linear Search and Binary


Search
9. Implementation of Insertion Sort and Selection
Sort
10. Implementation of Merge Sort

Implementation of Open Addressing


11.
(Linear Probing and Quadratic Probing)
12. Implementation of Breadth First Search using
Queue

13. Implementation of Topological Sort


lOMoAR cPSD| 10518309

EX. NO. 1 ARRAY IMPLEMENTATION OF STACK, QUEUE AND CIRCULAR QUEUE ADTS

DATE :

AIM: To implement Stack, Queue, and Circular Queue ADTs using Arrays

ALGORITHM 1 : ARRAY IMPLEMENTATION OF STACK


//Algorithm to insert an element in a stack
Step 1: IF TOP = MAX-1 PRINT OVERFLOW [END OF IF]
Step 2: SET TOP = TOP+1
Step 3: SET STACK[TOP] = VALUE
Step 4: END
//Algorithm to delete an element from a stack
Step 1: IF TOP = NULL PRINT UNDERFLOW [END OF IF]
Step 2: SET VAL = STACK[TOP]
Step 3: SET TOP = TOP-1
Step 4: END
// Algorithm for Peek operation
Step 1: IF TOP = NULL PRINT STACK IS EMPTY Goto Step 3
Step 2: RETURN STACK[TOP]
Step 3: END

PROGRAM 2 : ARRAY IMPLEMENTATION OF STACK

#include<stdio.h>
int stack[100],choice,n,top,x,i;
void push(void);
void pop(void);
void display(void);
int main()
{
//clrscr();
top=-1;
printf("\n Enter the size of STACK[MAX=100]:");
scanf("%d",&n);
printf("\n\t STACK OPERATIONS USING ARRAY");
printf("\n\t ");
printf("\n\t 1.PUSH\n\t 2.POP\n\t 3.DISPLAY\n\t 4.EXIT");
do
{
printf("\n Enter the Choice:");
scanf("%d",&choice);
switch(choice)
{ case 1:
lOMoAR cPSD| 10518309

{
push();
break;
}
case 2:
{
pop();
break;
}
case 3:
{
display();
break;
}
case 4:
{
printf("\n\t EXIT POINT ");
break;
}
default:
{
printf ("\n\t Please Enter a Valid Choice(1/2/3/4)");
} } }
while(choice!=4);
return 0;
}
void push()
{
if(top>=n-1)
{
printf("\n\tSTACK is over flow");
}
else
{
printf(" Enter a value to be pushed:");
scanf("%d",&x);
top++;
stack[top]=x;
}
}
void pop()
{ if(top<=-1)
{
printf("\n\t Stack is under flow");
}
lOMoAR cPSD| 10518309

else
{
printf("\n\t The popped elements is %d",stack[top]);
top--;
}
}
void display()
{
if(top>=0)
{
printf("\n The elements in STACK \n");
for(i=top; i>=0; i--)
printf("\n%d",stack[i]);
printf("\n Press Next Choice");
} else
{
printf("\n The STACK is empty");
}
}

ALGORITHM 2 : ARRAY IMPLEMENTATION OF QUEUE


1. Ask the user for the operation like insert, delete, display and exit.
2. According to the option entered, access its respective function using switch statement. Use the
variables front and rear to represent the first and last element of the queue.
3. In the function insert(), firstly check if the queue is full. If it is, then print the output as “Queue
Overflow”. Otherwise take the number to be inserted as input and store it in the variable add_item.
Copy the variable add_item to the array queue_array[] and increment the variable rear by 1.
4. In the function delete(), firstly check if the queue is empty. If it is, then print the output as
“Queue Underflow”. Otherwise print the first element of the array queue_array[] and decrement
the variable front by 1.
5. In the function display(), using for loop print all the elements of the array starting from front to
rear.
6. Exit.

PROGRAM 2 : ARRAY IMPLEMENTATION OF QUEUE

/* C Program to Implement a Queue using an Array */


#include <stdio.h>
#define MAX 50

void insert();
void delete();
void display();
lOMoAR cPSD| 10518309

int queue_array[MAX];
int rear = - 1;
int front = - 1;
main()
{
int choice;
while (1)
{
printf("1.Insert element to queue \n");
printf("2.Delete element from queue \n");
printf("3.Display all elements of queue \n");
printf("4.Quit \n");
printf("Enter your choice : ");
scanf("%d", &choice);
switch (choice)
{
case 1:
insert();
break;
case 2:
delete();
break;
case 3:
display();
break;
case 4:
exit(1);
default:
printf("Wrong choice \n");
} /* End of switch */
} /* End of while */
} /* End of main() */

void insert()
{
int add_item;
if (rear == MAX - 1)
printf("Queue Overflow \n");
else
{
if (front == - 1)
/*If queue is initially empty */
front = 0;
printf("Inset the element in queue : ");
scanf("%d", &add_item);
lOMoAR cPSD| 10518309

rear = rear + 1;
queue_array[rear] = add_item;
}
} /* End of insert() */

void delete()
{
if (front == - 1 || front > rear)
{
printf("Queue Underflow \n");
return ;
}
else
{
printf("Element deleted from queue is : %d\n", queue_array[front]);
front = front + 1;
}
} /* End of delete() */

void display()
{
int i;
if (front == - 1)
printf("Queue is empty \n");
else
{
printf("Queue is : \n");
for (i = front; i <= rear; i++)
printf("%d ", queue_array[i]);
printf("\n");
}
} /* End of display() */

ALGORITHM 3 : ARRAY IMPLEMENTATION OF CIRCULAR QUEUE ADTS

Algorithm to insert an element in a circular queue

Step 1: IF (REAR+1)%MAX = FRONT


Write " OVERFLOW "
Goto step 4
[End OF IF]
Step 2: IF FRONT = -1 and REAR = -1
SET FRONT = REAR = 0
ELSE IF REAR = MAX - 1 and FRONT ! = 0
SET REAR = 0
lOMoAR cPSD| 10518309

ELSE
SET REAR = (REAR + 1) % MAX
[END OF IF]
Step 3: SET QUEUE[REAR] = VAL
Step 4: EXIT

Algorithm to delete an element from the circular queue

Step 1: IF FRONT = -1
Write " UNDERFLOW "
Goto Step 4
[END of IF]
Step 2: SET VAL = QUEUE[FRONT]
Step 3: IF FRONT = REAR
SET FRONT = REAR = -1
ELSE
IF FRONT = MAX -1
SET FRONT = 0
ELSE
SET FRONT = FRONT + 1
[END of IF]
[END OF IF]
Step 4: EXIT

PROGRAM 3 : ARRAY IMPLEMENTATION OF CIRCULAR QUEUE ADTS


#include <stdio.h>
# define max 6
int queue[max]; // array declaration
int front=-1;
int rear=-1;
// function to insert an element in a circular queue
void enqueue(int element)
{
if(front==-1 && rear==-1) // condition to check queue is empty
{
front=0;
rear=0;
queue[rear]=element;
}
else if((rear+1)%max==front) // condition to check queue is full
{
lOMoAR cPSD| 10518309

printf("Queue is overflow..");
}
else
{
rear=(rear+1)%max; // rear is incremented
queue[rear]=element; // assigning a value to the queue at the rear position.
}
}
// function to delete the element from the queue
int dequeue()
{
if((front==-1) && (rear==-1)) // condition to check queue is empty
{
printf("\nQueue is underflow..");
}
else if(front==rear)
{
printf("\nThe dequeued element is %d", queue[front]);
front=-1;
rear=-1;
}
else
{
printf("\nThe dequeued element is %d", queue[front]);
front=(front+1)%max;
}
}
// function to display the elements of a queue
void display()
{
int i=front;
if(front==-1 && rear==-1)
{
printf("\n Queue is empty..");
}
else
lOMoAR cPSD| 10518309

{
printf("\nElements in a Queue are :");
while(i<=rear)
{
printf("%d,", queue[i]);
i=(i+1)%max;
}
}
}
int main()
{
int choice=1,x; // variables declaration

while(choice<4 && choice!=0) // while loop


{
printf("\n Press 1: Insert an element");
printf("\nPress 2: Delete an element");
printf("\nPress 3: Display the element");
printf("\nEnter your choice");
scanf("%d", &choice);
switch(choice)
{
case 1:
printf("Enter the element which is to be inserted");
scanf("%d", &x);
enqueue(x);
break;
case 2:
dequeue();
break;
case 3:
display();
}}
return 0;
}
lOMoAR cPSD| 10518309

OUTPUT 1 : STACK
Enter the size of STACK[MAX=100]:10
STACK OPERATIONS USING ARRAY

1. PUSH
2. POP
3. DISPLAY
4. EXIT
Enter the Choice:1
Enter a value to be pushed:12
Enter the Choice:1
Enter a value to be pushed:24

Enter the Choice:1


Enter a value to be pushed:98

Enter the Choice:3

The elements in STACK

98
24
12
Press Next Choice
Enter the Choice:2

The popped elements is 98


Enter the Choice:3

The elements in STACK

24
12
Press Next Choice
Enter the Choice:4

EXIT POINT

OUTPUT 2 : QUEUE

1. Insert element to queue


2. Delete element from queue
3. Display all elements of queue
4.Quit
Enter your choice : 1
lOMoAR cPSD| 10518309

Inset the element in queue : 10


1. Insert element to queue
2. Delete element from queue
3. Display all elements of queue
4.Quit
Enter your choice : 1
Inset the element in queue : 15
1. Insert element to queue
2. Delete element from queue
3. Display all elements of queue
4.Quit
Enter your choice : 1
Inset the element in queue : 20
1. Insert element to queue
2. Delete element from queue
3. Display all elements of queue
4.Quit
Enter your choice : 1
Inset the element in queue : 30
1. Insert element to queue
2. Delete element from queue
3. Display all elements of queue
4.Quit
Enter your choice : 2
Element deleted from queue is : 10
1. Insert element to queue
2. Delete element from queue
3. Display all elements of queue
4. Quit
Enter your choice: 3
Queue is:
15 20 30
1. Insert element to queue
2. Delete element from queue
3. Display all elements of queue
4. Quit
Enter your choice: 4

OUTPUT 3: CIRCULAR QUEUE

Press 1: Insert an element


Press 2: Delete an element
Press 3: Display the element
Enter your choice 1
Enter the element which is to be inserted 3
lOMoAR cPSD| 10518309

Press 1: Insert an element


Press 2: Delete an element
Press 3: Display the element
Enter your choice1
Enter the element which is to be inserted6
Press 1: Insert an element
Press 2: Delete an element
Press 3: Display the element
Enter your choice3
Elements in a Queue are :3,6,
Press 1: Insert an element
Press 2: Delete an element
Press 3: Display the element
Enter your choice2
The dequeued element is 3
Press 1: Insert an element
Press 2: Delete an element
Press 3: Display the element
Enter your choice3
Elements in a Queue are :6,

RESULT :
lOMoAR cPSD| 10518309

EX. NO. 2 IMPLEMENTATION OF SINGLY LINKED LIST


DATE :

AIM : To implement a Singly Linked List using program written in C

ALGORITHM :
Step 1 - Include all the header files which are used in the program.
Step 2 - Declare all the user defined functions.
Step 3 - Define a Node structure with two members data and next
Step 4 - Define a Node pointer 'head' and set it to NULL.
Step 5 - Implement the main method by displaying operations menu and make suitable
function calls in the main method to perform user selected operation

PROGRAM :

#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *head;
void beginsert ();
void lastinsert ();
void randominsert();
void begin_delete();
void last_delete();
void random_delete();
void display();
void search();
void main ()
{
int choice =0;
while(choice != 9)
{
printf("\n\n*********Main Menu*********\n");
printf("\nChoose one option from the following list ...\n");
printf("\n===============================================\n");
lOMoAR cPSD| 10518309

printf("\n1.Insert in beginning \n2.Insert at last\n3.Insert at any random location\n


4.Delete from Beginning\n 5.Delete from last\n6.Delete node after specified location\n
7.Search for an element\n8.Show\n9.Exit\n");
printf("\nEnter your choice?");
scanf("%d",&choice);
switch(choice)
{
case 1:
beginsert();
break;
case 2:
lastinsert();
break;
case 3:
randominsert();
break;
case 4:
begin_delete();
break;
case 5:
last_delete();
break;
case 6:
random_delete();
break;
case 7:
search();
break;
case 8:
display();
break;
case 9:
exit(0);
break;
default:
printf("Please enter valid choice..");
}
}
}
lOMoAR cPSD| 10518309

void beginsert()
{
struct node *ptr;
int item;
ptr = (struct node *) malloc(sizeof(struct node *));
if(ptr == NULL)
{
printf("\nOVERFLOW");
}
else
{
printf("\nEnter value\n");
scanf("%d",&item);
ptr->data = item;
ptr->next = head;
head = ptr;
printf("\nNode inserted");
}
}
void lastinsert()
{
struct node *ptr,*temp;
int item;
ptr = (struct node*)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("\nOVERFLOW");
}
else
{
printf("\nEnter value?\n");
scanf("%d",&item);
ptr->data = item;
if(head == NULL)
{
ptr -> next = NULL;
head = ptr;
printf("\nNode inserted");
}
else
lOMoAR cPSD| 10518309

{
temp = head;
while (temp -> next != NULL)
{
temp = temp -> next;
}
temp->next = ptr;
ptr->next = NULL;
printf("\nNode inserted");
} } }
void randominsert()
{
int i,loc,item;
struct node *ptr, *temp;
ptr = (struct node *) malloc (sizeof(struct node));
if(ptr == NULL)
{
printf("\nOVERFLOW");
}
else
{
printf("\nEnter element value");
scanf("%d",&item);
ptr->data = item;
printf("\nEnter the location after which you want to insert ");
scanf("\n%d",&loc);
temp=head;
for(i=0;i<loc;i++)
{
temp = temp->next;
if(temp == NULL)
{
printf("\ncan't insert\n");
return;
} }
ptr ->next = temp ->next;
temp ->next = ptr;
printf("\nNode inserted");
}}
lOMoAR cPSD| 10518309

void begin_delete()
{
struct node *ptr;
if(head == NULL)
{
printf("\nList is empty\n");
}
else
{
ptr = head;
head = ptr->next;
free(ptr);
printf("\nNode deleted from the begining ...\n");
}
}
void last_delete()
{
struct node *ptr,*ptr1;
if(head == NULL)
{
printf("\nlist is empty");
}
else if(head -> next == NULL)
{
head = NULL;
free(head);
printf("\nOnly node of the list deleted ...\n");
}
else
{
ptr = head;
while(ptr->next != NULL)
{
ptr1 = ptr;
ptr = ptr ->next;
}
ptr1->next = NULL;
free(ptr);
printf("\nDeleted Node from the last ...\n"); } }
lOMoAR cPSD| 10518309

void random_delete()
{
struct node *ptr,*ptr1;
int loc,i;
printf("\n Enter the location of the node after which you want to perform deletion \n");
scanf("%d",&loc);
ptr=head;
for(i=0;i<loc;i++)
{
ptr1 = ptr;
ptr = ptr->next;
if(ptr == NULL)
{
printf("\nCan't delete");
return;
}
}
ptr1 ->next = ptr ->next;
free(ptr);
printf("\nDeleted node %d ",loc+1);
}
void search()
{
struct node *ptr;
int item,i=0,flag;
ptr = head;
if(ptr == NULL)
{
printf("\nEmpty List\n");
}
else
{
printf("\nEnter item which you want to search?\n");
scanf("%d",&item);
while (ptr!=NULL)
{
if(ptr->data == item)
{
printf("item found at location %d ",i+1);
lOMoAR cPSD| 10518309

flag=0;
} else
{ flag=1; }
i++;
ptr = ptr -> next;
}
if(flag==1)
{
printf("Item not found\n");
} } }

void display()
{
struct node *ptr;
ptr = head;
if(ptr == NULL)
{
printf("Nothing to print");
}
else
{
printf("\nprinting values.......... \n");
while (ptr!=NULL)
{
printf("\n%d",ptr->data);
ptr = ptr -> next;
} }}

OUTPUT
*********Main Menu*********
Choose one option from the following list ...
=======================================
1. Insert in beginning 6. Delete node specified location
2. Insert at last 7. Search for an element
3. Insert at any random location 8.Show
4. Delete from Beginning 9. Exit
5. Delete from last
Enter your choice?1
Enter value 7
Node inserted
lOMoAR cPSD| 10518309

*********Main Menu*********
Choose one option from the following list ...
=======================================
1. Insert in beginning 6. Delete node specified location
2. Insert at last 7. Search for an element
3. Insert at any random location 8.Show
4. Delete from Beginning 9.Exit
5. Delete from last
Enter your choice? 1
Enter value 8
Node inserted

*********Main Menu*********
Choose one option from the following list ...
=======================================
1. Insert in beginning 6. Delete node specified location
2. Insert at last 7. Search for an element
3. Insert at any random location 8.Show
4. Delete fromBeginning 9.Exit
5. Delete from last
Enter your choice?1
Enter value6
Node inserted
*********Main Menu*********
Choose one option from the following list ...
=======================================
1. Insert in beginning 6. Delete node specified location
2. Insert at last 7. Search for an element
3. Insert at any random location 8.Show
4. Delete from Beginning 9. Exit
5. Delete from last
Enter your choice?8
printing values . . . . .
6
8
7

RESULT :
lOMoAR cPSD| 10518309

EX. NO. 3 LINKED LIST IMPLEMENTATION OF STACK AND LINEAR QUEUE ADTS
DATE :

AIM :
To implement stack and linear Queue ADT using linked list in C Program

ALGORITHM 1:
Algorithm to insert an element in a linked stack
Step 1: Allocate memory for the new node and name it as NEW_NODE
Step 2: SET NEW_NODE DATA = VAL
Step 3: IF TOP = NULL
SET NEW_NODE NEXT = NULL
SET TOP =NEW_NODE
ELSE
SET NEW_NODE NEXT = TOP
SET TOP =NEW_NODE
[END OF IF]
Step 4: END
Algorithm to delete an element from a linked stack
Step 1: IF TOP = NULL PRINT “UNDERFLOW”
Goto Step 5
[END OF IF]
Step 2: SET PTR = TOP
Step 3: SET TOP = TOP NEXT
Step 4: FREE PTR
Step 5: END

PROGRAM 1:
/*
* C PROGRAM TO IMPLEMENT A STACK USING LINKED LIST
*/
#include <stdio.h>
#include <stdlib.h>
struct node
{
int info;
struct node *ptr;
} *top,*top1,*temp;
int topelement();
lOMoAR cPSD| 10518309

void push(int data);


void pop();
void empty();
void display();
void destroy();
void stack_count();
void create();
int count = 0;
void main()
{
int no, ch, e;
printf("\n 1 - Push");
printf("\n 2 - Pop");
printf("\n 3 - Top");
printf("\n 4 - Empty");
printf("\n 5 - Exit");
printf("\n 6 - Dipslay");
printf("\n 7 - Stack Count");
printf("\n 8 - Destroy stack");
create();
while (1)
{
printf("\n Enter choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("Enter data : ");
scanf("%d", &no);
push(no);
break;
case 2:
pop();
break;
case 3:
if (top == NULL)
printf("No elements in stack");
else
{
lOMoAR cPSD| 10518309

e = topelement();
printf("\n Top element : %d", e);
}
break;
case 4:
empty();
break;
case 5:
exit(0);
case 6:
display();
break;
case 7:
stack_count();
break;
case 8:
destroy();
break;
default :
printf(" Wrong choice, Please enter correct choice ");
break;
}
}
}
/* Create empty stack */
void create()
{
top = NULL;
}
/* Count stack elements */
void stack_count()
{
printf("\n No. of elements in stack : %d", count);
}
/* Push data into stack */
void push(int data)
{
if (top == NULL)
{
lOMoAR cPSD| 10518309

top =(struct node *)malloc(1*sizeof(struct node));


top->ptr = NULL;
top->info = data;
}
else
{
temp =(struct node *)malloc(1*sizeof(struct node));
temp->ptr = top;
temp->info = data;
top = temp;
}
count++;
}
/* Display stack elements */
void display()
{
top1 = top;

if (top1 == NULL)
{
printf("Stack is empty");
return;
}
while (top1 != NULL)
{
printf("%d ", top1->info);
top1 = top1->ptr;
}
}
/* Pop Operation on stack */
void pop()
{
top1 = top;

if (top1 == NULL)
{
printf("\n Error : Trying to pop from empty stack");
return;
}
lOMoAR cPSD| 10518309

else
top1 = top1->ptr;
printf("\n Popped value : %d", top->info);
free(top);
top = top1;
count--;
}
/* Return top element */
int topelement()
{
return(top->info);
}
/* Check if stack is empty or not */
void empty()
{
if (top == NULL)
printf("\n Stack is empty");
else
printf("\n Stack is not empty with %d elements", count);
}

/* Destroy entire stack */


void destroy()
{
top1 = top;

while (top1 != NULL)


{
top1 = top->ptr;
free(top);
top = top1;
top1 = top1->ptr;
}
free(top1);
top = NULL;
printf("\n All stack elements destroyed");
count = 0;
}
lOMoAR cPSD| 10518309

ALGORITHM 2 : ALGORITHM TO INSERT AN ELEMENT IN A LINKED QUEUE


Step 1: Allocate memory for the new node and name it as PTR
Step 2: SET PTR DATA = VAL
Step 3: IF FRONT = NULL
SET FRONT = REAR = PTR
SET FRONT NEXT = REAR NEXT = NULL
ELSE
SET REAR NEXT = PTR
SET REAR = PTR
SET REAR NEXT = NULL
[END OF IF]
Step 4: END

Algorithm to delete an element from a linked queue


Step 1: IF FRONT = NULL
Write “Underflow”
Go to Step 5
[END OF IF]
Step 2: SET PTR = FRONT
Step 3: SET FRONT = FRONT NEXT
Step 4: FREE PTR
Step 5: END

PROGRAM 2 : IMPLEMENT LINEAR QUEUE USING LINKED LIST


/*
* C Program to Implement Queue Data Structure using Linked List
*/
#include <stdio.h>
#include <stdlib.h>
struct node
{
int info;
struct node *ptr;
}*front,*rear,*temp,*front1;
int frontelement();
void enq(int data);
void deq();
void empty();
void display();
lOMoAR cPSD| 10518309

void create();
void queuesize();
int count = 0;

void main()
{
int no, ch, e;

printf("\n 1 - Enque");
printf("\n 2 - Deque");
printf("\n 3 - Front element");
printf("\n 4 - Empty");
printf("\n 5 - Exit");
printf("\n 6 - Display");
printf("\n 7 - Queue size");
create();
while (1)
{
printf("\n Enter choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("Enter data : ");
scanf("%d", &no);
enq(no);
break;
case 2:
deq();
break;
case 3:
e = frontelement();
if (e != 0)
printf("Front element : %d", e);
else
printf("\n No front element in Queue as queue is empty");
break;
case 4:
empty();
lOMoAR cPSD| 10518309

break;
case 5:
exit(0);
case 6:
display();
break;
case 7:
queuesize();
break;
default:
printf("Wrong choice, Please enter correct choice ");
break;
}
}
}

/* Create an empty queue */


void create()
{
front = rear = NULL;
}

/* Returns queue size */


void queuesize()
{
printf("\n Queue size : %d", count);
}

/* Enqueing the queue */


void enq(int data)
{
if (rear == NULL)
{
rear = (struct node *)malloc(1*sizeof(struct node));
rear->ptr = NULL;
rear->info = data;
front = rear;
}
else
lOMoAR cPSD| 10518309

{
temp=(struct node *)malloc(1*sizeof(struct node));
rear->ptr = temp;
temp->info = data;
temp->ptr = NULL;
rear = temp;
}
count++;
}
/* Displaying the queue elements */
void display()
{
front1 = front;
if ((front1 == NULL) && (rear == NULL))
{
printf("Queue is empty");
return;
}
while (front1 != rear)
{
printf("%d ", front1->info);
front1 = front1->ptr;
}
if (front1 == rear)
printf("%d", front1->info);
}
/* Dequeing the queue */
void deq()
{
front1 = front;

if (front1 == NULL)
{
printf("\n Error: Trying to display elements from empty queue");
return;
}
else
if (front1->ptr != NULL)
{
lOMoAR cPSD| 10518309

front1 = front1->ptr;
printf("\n Dequed value : %d", front->info);
free(front);
front = front1;
}
else
{
printf("\n Dequed value : %d", front->info);
free(front);
front = NULL;
rear = NULL;
}
count--;
}

/* Returns the front element of queue */


int frontelement()
{
if ((front != NULL) && (rear != NULL))
return(front->info);
else
return 0;
}

/* Display if queue is empty or not */


void empty()
{
if ((front == NULL) && (rear == NULL))
printf("\n Queue empty");
else
printf("Queue not empty");
}
lOMoAR cPSD| 10518309

OUTPUT - STACK
1 - Push
2 - Pop
3 - Top
4 - Empty
5 - Exit
6 - Dipslay
7 - Stack Count
8 - Destroy stack
Enter choice : 1
Enter data : 56
Enter choice : 1
Enter data : 80
Enter choice : 2
Popped value : 80
Enter choice : 3
Top element : 56
Enter choice : 1
Enter data : 78
Enter choice : 1
Enter data : 90
Enter choice : 6
90 78 56
Enter choice : 7
No. of elements in stack : 3
Enter choice : 8
All stack elements destroyed
Enter choice : 4
Stack is empty
Enter choice : 5

OUTPUT - QUEUE
1 - Enque
2 - Deque
3 - Front element
4 - Empty
5 - Exit
6 - Display
7 - Queue size
lOMoAR cPSD| 10518309

Enter choice : 1
Enter data : 14
Enter choice : 1
Enter data : 85
Enter choice : 1
Enter data : 38
Enter choice : 3
Front element : 14
Enter choice : 6
14 85 38
Enter choice : 7
Queue size : 3
Enter choice : 2
Dequed value : 14
Enter choice : 6
85 38
Enter choice : 7
Queue size : 2
Enter choice : 4
Queue not empty
Enter choice : 5

RESULT :
lOMoAR cPSD| 10518309

EX. NO. 4 IMPLEMENTATION OF POLYNOMIAL MANIPULATION USING LINKED LIST


DATE :

AIM : To implement polynomial manipulation using linked list in C Program

ALGORITHM : Input − polynomial p1 and p2 represented as a linked list.


Step 1: loop around all values of linked list and follow step 2& 3.
Step 2: if the value of a node‟s exponent. is greater copy this node to result node and head
towards the next node.
Step 3: if the values of both node‟s exponent is same add the coefficients and then copy the
added value with node to the result.
Step 4: Print the resultant node.

PROGRAM :
# include <stdio.h>
struct Node {
int coeff;
int pow;
struct Node* next;
};
// Function to create new node
void create_node(int x, int y, struct Node** temp)
{
struct Node *r, *z;
z = *temp;
if (z == NULL) {
r = (struct Node*)malloc(sizeof(struct Node));
r->coeff = x;
r->pow = y;
*temp = r;
r->next = (struct Node*)malloc(sizeof(struct Node));
r = r->next;
r->next = NULL;
} else {
r->coeff = x;
r->pow = y;
r->next = (struct Node*)malloc(sizeof(struct Node));
r = r->next;
r->next = NULL;
}
}
lOMoAR cPSD| 10518309

// Function Adding two polynomial numbers


void polyadd(struct Node* poly1, struct Node* poly2, struct Node* poly)
{
while (poly1->next && poly2->next) {
// If power of 1st polynomial is greater then 2nd, then store 1st as it is and move its pointer
if (poly1->pow > poly2->pow) {
poly->pow = poly1->pow;
poly->coeff = poly1->coeff;
poly1 = poly1->next;
}
// If power of 2nd polynomial is greater then 1st, then store 2nd as it is and move its pointer
else if (poly1->pow < poly2->pow) {
poly->pow = poly2->pow;
poly->coeff = poly2->coeff;
poly2 = poly2->next;
}
// If power of both polynomial numbers is same then add their coefficients
else {
poly->pow = poly1->pow;
poly->coeff = poly1->coeff + poly2->coeff;
poly1 = poly1->next;
poly2 = poly2->next;
}
// Dynamically create new node
poly->next = (struct Node*)malloc(sizeof(struct Node));
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;
}
lOMoAR cPSD| 10518309

poly->next = (struct Node*)malloc(sizeof(struct Node));


poly = poly->next;
poly->next = NULL;
}
}
// Display Linked list
void show(struct Node* node)
{
while (node->next != NULL)
{ printf("%dx^%d", node->coeff, node->pow);
node = node->next;
if (node->coeff >= 0) {
if (node->next != NULL)
printf("+");
} } }
int main()
{
struct Node *poly1 = NULL, *poly2 = NULL, *poly = NULL;
// Create first list of 5x^2 + 4x^1 + 2x^0
create_node(5, 2, &poly1);
create_node(4, 1, &poly1);
create_node(2, 0, &poly1);
// Create second list of -5x^1 - 5x^0
create_node(-5, 1, &poly2);
create_node(-5, 0, &poly2);
printf("1st Number: ");
show(poly1);
printf("\n2nd Number: ");
show(poly2);
poly = (struct Node*)malloc(sizeof(struct Node));
// Function add two polynomial numbers
polyadd(poly1, poly2, poly);
// Display resultant List
printf("\nAdded polynomial: ");
show(poly);
return 0;
}
lOMoAR cPSD| 10518309

OUTPUT
1st Number: 5x^2+4x^1+2x^0
2nd Number: -5x^1-5x^0
Added polynomial: 5x^2-1x^1-3x^0

RESULT :
lOMoAR cPSD| 10518309

EX. NO. 5 IMPLEMENTATION OF EVALUATING POSTFIX EXPRESSIONS,


INFIX TO POSTFIX CONVERSION
DATE :

AIM : To implement the algorithm for evaluating postfix expressions and converting infix to postfix
Conversion in C Program

ALGORITHM 1 : EVALUATING POSTFIX EXPRESSIONS


As Postfix expression is without parenthesis and can be evaluated as two operands and an operator at a
time, this becomes easier for the compiler and the computer to handle.

Step 1: If a character is an operand push it to Stack


Step 2: If the character is an operator, Pop two elements from the Stack.
Operate on these elements according to the operator, and push the result back to the Stack
Step 3: Step 1 and 2 will be repeated until the end has reached.
Step 4: The Result is stored at the top of the Stack, return it
Step 5: End

PROGRAM 1: EVALUATION OF POSTFIX EXPRESSIONS USING STACK

/* This program is for evaluation of postfix expression. This program assume that there
are only four operators (*, /, +, -) in an expression and operand is single digit only Further
this program does not do any error handling e.g. it does not check that entered postfix
expression is valid * or not. * */

#include <stdio.h>
#include <ctype.h>
#define MAXSTACK 100 /* for max size of stack */
#define POSTFIXSIZE 100 /* define max number of charcters in postfix expression */
/* declare stack and its top pointer to be used during postfix expression evaluation*/
int stack[MAXSTACK];
int top = -1; /* because array index in C begins at 0 */
/* can be do this initialization somewhere else */

/* define push operation */


void push(int item)
{
if (top >= MAXSTACK - 1) {
printf("stack over flow");
return;
}
lOMoAR cPSD| 10518309

else {
top = top + 1;
stack[top] = item;
}
}
/* define pop operation */
int pop()
{
int item;
if (top < 0) {
printf("stack under flow");
}
else {
item = stack[top];
top = top - 1;
return item;
}
}
/* define function that is used to input postfix expression and to evaluate it */
void EvalPostfix(char postfix[])
{
int i;
char ch;
int val;
int A, B;
/* evaluate postfix expression */
for (i = 0; postfix[i] != ')'; i++) {
ch = postfix[i];
if (isdigit(ch)) {
/* we saw an operand,push the digit onto stack ch - '0' is used for getting digit rather
than ASCII code of digit */
push(ch - '0'); }
else if (ch == '+' || ch == '-' || ch == '*' || ch == '/') {
/* we saw an operator pop top element A and next-to-top elemnet B
* from stack and compute B operator A */
A = pop();
B = pop();
switch (ch) /* ch is an operator */
{
lOMoAR cPSD| 10518309

case '*':
val = B * A;
break;
case '/':
val = B / A;
break;
case '+':
val = B + A;
break;
case '-':
val = B - A;
break;
}
/* push the value obtained above onto the stack */
push(val);
}
}
printf(" \n Result of expression evaluation : %d \n", pop());
}
int main()
{
int i;
/* declare character array to store postfix expression */
char postfix[POSTFIXSIZE];
printf("ASSUMPTION: There are only four operators(*, /, +, -) in an expression and operand is
single digit only.\n");
printf(" \nEnter postfix expression,\npress right parenthesis ')' for end expression : ");
/* take input of postfix expression from user */
for (i = 0; i <= POSTFIXSIZE - 1; i++) {
scanf("%c", &postfix[i]);
if (postfix[i] == ')') /* is there any way to eliminate this if */
{
break;
} /* and break statement */
}
/* call function to evaluate postfix expression */
EvalPostfix(postfix);
return 0;
}
lOMoAR cPSD| 10518309

ALGORITHM 2 : TO CONVERT INFIX TO POSTFIX


Let, X is an arithmetic expression written in infix notation. This algorithm finds the equivalent
postfix expression Y.
1. Push “(“onto Stack, and add “)” to the end of X.
2. Scan X from left to right and repeat Step 3 to 6 for each element of X until the Stack is empty.
3. If an operand is encountered, add it to Y.
4. If a left parenthesis is encountered, push it onto Stack.
5. If an operator is encountered ,then:
1. Repeatedly pop from Stack and add to Y each operator (on the top of Stack) which has the
same precedence as or higher precedence than operator.
2. Add operator to Stack.
[End of If]
6. If a right parenthesis is encountered ,then:
1. Repeatedly pop from Stack and add to Y each operator (on the top of Stack) until a left
parenthesis is encountered.
2. Remove the left Parenthesis.
[End of If]
[End of If]
7. END.

Let’s take an example to better understand the algorithm


Infix Expression: A+ (B*C-(D/E^F)*G)*H, where ^ is an exponential operator.
Resultant Postfix Expression: ABC*DEF^/G*-H*+

PROGRAM 2 - CONVERT INFIX TO POSTFIX EXPRESSION


#include<stdio.h>
#include<stdlib.h> /* for exit() */
#include<ctype.h> /* for isdigit(char ) */
#include<string.h>
#define SIZE 100
/* declared here as global variable because stack[] is used by more than one functions */
char stack[SIZE];
int top = -1;
/* define push operation */
void push(char item)
{
if(top >= SIZE-1)
{ printf("\nStack Overflow."); }
else
{ top = top+1;
stack[top] = item;
} }
lOMoAR cPSD| 10518309

/* define pop operation */


char pop()
{
char item ;
if(top <0)
{
printf("stack under flow: invalid infix expression");
getchar();
/* underflow may occur for invalid expression */
/* where ( and ) are not matched */
exit(1);
}
else
{ item = stack[top];
top = top-1;
return(item);
}
}
/* define function that is used to determine whether any symbol is operator or not (that is symbol is
operand) this fucntion returns 1 if symbol is opreator else return 0 */
int is_operator(char symbol)
{
if(symbol == '^' || symbol == '*' || symbol == '/' || symbol == '+' || symbol =='-')
{
return 1;
}
else
{
return 0;
}
}
/* define function that is used to assign precedence to operator. * Here ^ denotes exponent operator.
* In this function we assume that higher integer value * means higher precedence */
int precedence(char symbol)
{
if(symbol == '^')/* exponent operator, highest precedence*/
{
return(3);
}
lOMoAR cPSD| 10518309

else if(symbol == '*' || symbol == '/')


{ return(2); }
else if(symbol == '+' || symbol == '-') /* lowest precedence */
{ return(1); }
else
{ return(0); }
}
void InfixToPostfix(char infix_exp[], char postfix_exp[])
{
int i, j;
char item;
char x;
push('('); /* push '(' onto stack */
strcat(infix_exp,")"); /* add ')' to infix expression */
i=0;
j=0;
item=infix_exp[i]; /* initialize before loop*/
while(item != '\0') /* run loop till end of infix expression */
{
if(item == '(')
{
push(item);
}
else if( isdigit(item) || isalpha(item))
{
postfix_exp[j] = item; /* add operand symbol to postfix expr */
j++;
}
else if(is_operator(item) == 1) /* means symbol is operator */
{
x=pop();
while(is_operator(x) == 1 && precedence(x)>= precedence(item))
{
postfix_exp[j] = x;/* so pop all higher precendence operator and */
j++;
x = pop(); /* add them to postfix expresion */
}
push(x);
/* because just above while loop will terminate we have popped one extra item for
lOMoAR cPSD| 10518309

which condition fails and loop terminates, so that one*/


push(item); /* push current operator symbol onto stack */
}
else if(item == ')') /* if current symbol is ')' then */
{
x = pop(); /* pop and keep popping until */
while(x != '(') /* '(' encounterd */
{
postfix_exp[j] = x;
j++;
x = pop();
}}
else {
/* if current symbol is neither operand not '(' nor ')' and nor operator */
printf("\nInvalid infix Expression.\n"); /* the it is illegeal symbol */
getchar();
exit(1);
}
i++;
item = infix_exp[i]; /* go to next symbol of infix expression */
} /* while loop ends here */
if(top>0)
{
printf("\nInvalid infix Expression.\n"); /* the it is illegeal symbol */
getchar();
exit(1);
}
if(top>0)
{
printf("\nInvalid infix Expression.\n"); /* the it is illegeal symbol */
getchar();
exit(1); }
postfix_exp[j] = '\0'; /* add sentinel else puts() fucntion */
/* will print entire postfix[] array upto SIZE */
}
/* main function begins */
int main()
{
char infix[SIZE], postfix[SIZE]; /* declare infix string and postfix string */
lOMoAR cPSD| 10518309

/* why we asked the user to enter infix expression in parentheses ( )


* What changes are required in program to get rid of this restriction since it is not in algorithm * */
printf("ASSUMPTION: The infix expression contains single letter variables and single digit
constants only.\n");
printf("\nEnter Infix expression : ");
gets(infix);
InfixToPostfix(infix,postfix); /* call to convert */
printf("Postfix Expression: ");
puts(postfix); /* print postfix expression */
return 0;
}

OUTPUT 1 – EVALUATING POSTFIX EXPRESSION


First Run:
Enter postfix expression, press right parenthesis ')' for end expression : 456*+)
Result of expression evaluation : 34
Second Run:
Enter postfix expression, press right parenthesis ')' for end expression: 12345*+*+)
Result of expression evaluation: 47

OUTPUT 2 - INFIX TO POSTFIX CONVERSION


First Run:
Enter Infix expression : A+(B*C-(D/E^F)*G)*H
Postfix Expression: ABC*DEF^/G*-H*+

Second Run:
Enter Infix expression : (3^2*5)/(3*2-3)+5
Postfix Expression: 32^5*32*3-/5+

RESULT :
lOMoAR cPSD| 10518309

EX. NO. 6 IMPLEMENTATION OF BINARY SEARCH TREES


DATE:

AIM : To implement Binary search trees and its operations using C Program

ALGORITHM :
A BST is a binary tree of nodes ordered in the following way:
1. Each node contains one key (also unique)
2. The keys in the left subtree are < (less) than the key in its parent node
3. The keys in the right subtree > (greater) than the key in its parent node
4. Duplicate node keys are not allowed.
5. Inserting a node
Insert(N, T) = N if T is empty
= insert(N, T.left) if N < T
= insert(N, T.right) if N > T
6. Searching for a node
Search(N, T) = false if T is empty
= true if T = N
= search(N, T.left) if N < T
= search(N, T.right) if N > T
7. Deleting a node
8. Traversing a BST
Step 1: Repeat Steps 2 to 4 while TREE != NULL
Step 2: Write TREE DATA
Step 3: PREORDER(TREE LEFT)
Step 4: PREORDER(TREE RIGHT)
[END OF LOOP]
Step 5: END

PROGRAM
/* C program to implement the Binary Search Tree */
#include <stdio.h>
#include <stdlib.h>
// structure of a node
struct node
{
int data;
struct node *left;
struct node *right;
};
// globally initialized root pointer
struct node *root = NULL;
// function prototyping
lOMoAR cPSD| 10518309

struct node *create_node(int);


void insert(int);
struct node *delete (struct node *, int);
int search(int);
void inorder(struct node *);
void postorder();
void preorder();
struct node *smallest_node(struct node *);
struct node *largest_node(struct node *);
int get_data();
int main()
{
int userChoice;
int userActive = 'Y';
int data;
struct node* result = NULL;
while (userActive == 'Y' || userActive == 'y')
{
printf("\n\n------- Binary Search Tree \n");
printf("\n1. Insert");
printf("\n2. Delete");
printf("\n3. Search");
printf("\n4. Get Larger Node Data");
printf("\n5. Get smaller Node data");
printf("\n\n-- Traversals --");
printf("\n\n6. Inorder ");
printf("\n7. Post Order ");
printf("\n8. Pre Oder ");
printf("\n9. Exit");
printf("\n\nEnter Your Choice: ");
scanf("%d", &userChoice);
printf("\n");
switch(userChoice)
{
case 1:
data = get_data();
insert(data);
break;
lOMoAR cPSD| 10518309

case 2:
data = get_data();
root = delete(root, data);
break;
case 3:
data = get_data();
if (search(data) == 1)
{ printf("\nData was found!\n"); }
else
{ printf("\nData does not found!\n"); }
break;
case 4:
result = largest_node(root);
if (result != NULL)
{ printf("\nLargest Data: %d\n", result->data); }
break;
case 5:
result = smallest_node(root);
if (result != NULL)
{ printf("\nSmallest Data: %d\n", result->data); }
break;
case 6:
inorder(root);
break;
case 7:
postorder(root);
break;
case 8:
preorder(root);
break;
case 9:
printf("\n\nProgram was terminated\n");
break;
default:
printf("\n\tInvalid Choice\n");
break; }
printf("\n \nDo you want to continue? ");
fflush(stdin);
scanf(" %c", &userActive);
lOMoAR cPSD| 10518309

} return 0; }
// creates a new node
struct node *create_node(int data)
{
struct node *new_node = (struct node *)malloc(sizeof(struct node));
if (new_node == NULL)
{ printf("\nMemory for new node can't be allocated");
return NULL; }
new_node->data = data;
new_node->left = NULL;
new_node->right = NULL;
return new_node;
}
void insert(int data) // inserts the data in the BST
{
struct node *new_node = create_node(data);
if (new_node != NULL)
{ // if the root is empty then make a new node as the root node
if (root == NULL)
{ root = new_node;
printf("\n* node having data %d was inserted\n", data);
return; }
struct node *temp = root;
struct node *prev = NULL;
// traverse through the BST to get the correct position for insertion
while (temp != NULL)
{ prev = temp;
if (data > temp->data)
{ temp = temp->right; }
else
{ temp = temp->left; } }

// found the last node where the new node should insert
if (data > prev->data)
{ prev->right = new_node; }
else
{ prev->left = new_node; }
printf("\n* node having data %d was inserted\n", data);
} }
lOMoAR cPSD| 10518309

struct node *delete (struct node *root, int key) // deletes the given key node from the BST
{
if (root == NULL)
{ return root; }
if (key < root->data)
{ root->left = delete (root->left, key); }
else if (key > root->data)
{ root->right = delete (root->right, key); }
else
{ if (root->left == NULL)
{ struct node *temp = root->right;
free(root);
return temp; }
else if (root->right == NULL)
{ struct node *temp = root->left;
free(root);
return temp; }
struct node *temp = smallest_node(root->right);
root->data = temp->data;
root->right = delete (root->right, temp->data);
} return root; }
// search the given key node in BST
int search(int key)
{
struct node *temp = root;
while (temp != NULL)
{ if (key == temp->data)
{ return 1; }
else if (key > temp->data)
{ temp = temp->right; }
else
{ temp = temp->left; } }
return 0; }
// finds the node with the smallest value in BST
struct node *smallest_node(struct node *root)
{ struct node *curr = root;
while (curr != NULL && curr->left != NULL)
{ curr = curr->left; } return curr; }
lOMoAR cPSD| 10518309

struct node *largest_node(struct node *root) // finds the node with the largest value in BST
{
struct node *curr = root;
while (curr != NULL && curr->right != NULL)
{ curr = curr->right; }
return curr;
}
void inorder(struct node *root) // inorder traversal of the BST
{
if (root == NULL)
{ return; }
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
void preorder(struct node *root) // preorder traversal of the BST
{
if (root == NULL)
{ return; }
printf("%d ", root->data);
preorder(root->left);
preorder(root->right);
}
void postorder(struct node *root) // postorder travsersal of the BST
{
if (root == NULL)
{ return; }
postorder(root->left);
postorder(root->right);
printf("%d ", root->data);
}
// getting data from the user
int get_data()
{
int data;
printf("\nEnter Data: ");
scanf("%d", &data);
return data;
}
lOMoAR cPSD| 10518309

OUTPUT :

1. Insert
. Delete
3. Search
4. Get Larger Node Data
5. Get smaller Node data
====Traversals=====
6. Inorder
7. Post Order
8. Pre Oder
9. Exit
Enter Your Choice: 6

RESULT:
lOMoAR cPSD| 10518309

EX. NO. 7 IMPLEMENTATION OF PRIM’S ALGORITHM


DATE:

AIM : To implement Prim‟s Algorithm using C Program

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. Draw all nodes to create skeleton for spanning tree.
4. Select an edge with lowest weight and add it to skeleton and 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);
lOMoAR cPSD| 10518309

return 0;
}
int prims()
{
int cost[MAX][MAX];
int u,v,min_distance,distance[MAX],from[MAX];
int visited[MAX],no_of_edges,i,min_cost,j;
//create cost[][] matrix,spanning[][]
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{ if(G[i][j]==
0)
cost[i][j]=infinity;
else
cost[i][j]=G[i][j];
spanning[i][j]=0;
}
//initialise visited[],distance[] and from[]
distance[0]=0;
visited[0]=1;
for(i=1;i<n;i++)
{
distance[i]=cost[0][i];
from[i]=0;
visited[i]=0;
}
min_cost=0; //cost of spanning tree
no_of_edges=n-1; //no. of edges to be added
while(no_of_edges>0)
{
//find the vertex at minimum distance from the tree
min_distance=infinity;
for(i=1;i<n;i++)
if(visited[i]==0&&distance[i]<min_distance)
{
v=i;
min_distance=distance[i];
}
u=from[v];
lOMoAR cPSD| 10518309

//insert the edge in spanning tree


spanning[u][v]=distance[v];
spanning[v][u]=distance[v];
no_of_edges--;
visited[v]=1;
//updated the distance[] array
for(i=1;i<n;i++)
if(visited[i]==0&&cost[i][v]<distance[i])
{
distance[i]=cost[i][v];
from[i]=v;
}
min_cost=min_cost+cost[u][v];
}
return(min_cost);
}

OUTPUT
Enter no. of vertices:6
Enter the adjacency matrix:
031600
305030
150564
605002
036006
004260
spanning tree matrix:
031000
300030
100004
000002
030000
004200
Total cost of spanning tree=13

RESULT :
lOMoAR cPSD| 10518309

EX. NO. 08. IMPLEMENTATION OF LINEAR SEARCH AND BINARY SEARCH


DATE:

AIM :
To implement linear search and binary search algorithm using C Program

ALGORITHM :
Algorithm for Linear Search
STEP 1 : Initially accept the element to be searched from the user.
STEP 2: Then, we create a for loop and start searching for the element in a sequential fashion.
STEP 3 : if match is encountered i.e. array[element] == key value, return the element along with
its position in the array.
STEP 4 : If no values are found that match the input, it returns -1.
Algorithm for Binary Search
Step 1 : Find the middle element of array using middle = initial_value + end_value / 2 ;
Step 2 : If middle = element, return „element found‟ and index.
Step 3 : if middle > element, call the function with end_value = middle - 1 .
Step 4 : if middle < element, call the function with start_value = middle + 1 .
Step 5 : exit.

PROGRAM : /* To implement linear search and Binary search */


#include <stdio.h>
#include <stdlib.h>
main() { /* Declare variables - array_of_number,search_key,i,j,low,high*/
int array[100],search_key,i,j,n,low,high,location,choice;
void linear_search(int search_key,int array[100],int n);
void binary_search(int search_key,int array[100],int n);
clrscr(); /* read the elements of array */
printf("ENTER THE SIZE OF THE ARRAY:");
scanf("%d",&n);
printf("ENTER THE ELEMENTS OF THE ARRAY:\n");
for(i=1;i<=n;i++) { scanf("%d",&array[i]); }
/* Get the Search Key element for Linear Search */
printf("ENTER THE SEARCH KEY:");
scanf("%d",&search_key); /* Choice of Search Algorithm */
printf(" \n");
printf("1.LINEAR SEARCH\n");
printf("2.BINARY SEARCH\n");
printf(" \n");
printf("ENTER YOUR CHOICE:");
scanf("%d",&choice);
lOMoAR cPSD| 10518309

switch(choice)
{
case 1:
linear_search(search_key,array,n);
break;
case 2: binary_search(search_key,array,n);
break;
default:
exit(0);
}
getch();
return 0;
}
/* LINEAR SEARCH */
void linear_search(int search_key,int array[100],int n)
{
/*Declare Variable */
int i,location;
for(i=1;i<=n;i++)
{
if(search_key == array[i])
{
location = i;
printf(" \n");
printf("The location of Search Key = %d is %d\n",search_key,location);
printf(" \n");
}}}
/* Binary Search to find Search Key */
void binary_search(int search_key,int array[100],int n)
{
int mid,i,low,high; low = 1; high = n;
mid = (low + high)/2; i=1;
while(search_key != array[mid])
{
if(search_key <= array[mid])
{
low = 1; high = mid+1;
mid = (low+high)/2;
}
lOMoAR cPSD| 10518309

else {
low = mid+1; high = n;
mid = (low+high)/2;
}}
printf(" \n");
printf("location=%d\t",mid); printf("Search_Key=%d Found!\n",search_key);
printf(" \n");
}

OUTPUT :
ENTER THE SIZE OF THE ARRAY:6
ENTER THE ELEMENTS OF THE ARRAY: 45 6 86 23 64 77
ENTER THE SEARCH KEY:86
1. LINEAR SEARCH
2. BINARY SEARCH
ENTER YOUR CHOICE:2
Location =3
Search_Key = 86
Found!

RESULT :
lOMoAR cPSD| 10518309

EX. NO. 09. IMPLEMENTATION OF INSERTION SORT AND SELECTION SORT

DATE :

AIM : To implement insertion Sort and Selection Sort using C Program

ALGORITHM :
Algorithm for Insertion Sort
Step 1 − If the element is the first one, it is already sorted.
Step 2 – Move to next element
Step 3 − Compare the current element with all elements in the sorted array
Step 4 – If the element in the sorted array is smaller than the current element, iterate to
the next element. Otherwise, shift all the greater element in the array by one
position towards the right
Step 5 − Insert the value at the correct position
Step 6 − Repeat until the complete list is sorted
Algorithm for Selection Sort:
Step 1 − Set min to the first location
Step 2 − Search the minimum element in the array
Step 3 – swap the first location with the minimum value in the array
Step 4 – assign the second element as min.
Step 5 − Repeat the process

PROGRAM FOR INSERTION SORT


#include <math.h>
#include <stdio.h>
// Insertion Sort Function
void insertionSort(int array[], int n)
{
int i, element, j;
for (i = 1; i < n; i++) { element = array[i]; j = i - 1; while (j >= 0 && array[j] > element)
{ array[j + 1] = array[j];
j = j - 1;
}
array[j + 1] = element;
}}
// Function to print the elements of an array
void printArray(int array[], int n)
{
int i;
for (i = 0; i < n; i++)
printf("%d ", array[i]);
lOMoAR cPSD| 10518309

printf("n");
}

PROGRAM FOR SELECTION SORT


#include <stdio.h>
void SelSort(int array[],int n);
int main()
{
int array[100], n,i;
printf("Enter number of elementsn");
scanf("%d", &n);
printf("Enter %d Numbersn", n);
for(i = 0; i < n; i++)
scanf("%d", &array[i]);
SelSort(array,n);
return 0;
}
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;
}
if(position != i)
{
swap=array[i];
array[i]=array[position];
array[position]=swap;
}
}
printf("Sorted Array:n");
for(i = 0; i < n; i++)
printf("%dn", array[i]);
}
lOMoAR cPSD| 10518309

OUTPUT :
Enter number of elements 5
Enter 5 Numbers
78
56
-23
45
9
Sorted Array:
-23 9 45 56 78

RESULT:
lOMoAR cPSD| 10518309

EX. NO. 10 IMPLEMENTATION OF MERGE SORT


DATE :

AIM : To implement Merge Sort using C Program

ALGORITHM :
Step 1 : MergeSort(arr[], l, r), where l is the index of the first element & r is the index of
the last element. If r > l
Step 2: Find the middle index of the array to divide it in two halves: m = (l+r)/2
Step 3: Call MergeSort for first half: mergeSort(array, l, m)
Step 4. Call mergeSort for second half: mergeSort(array, m+1, r)
Step 5. Recursively, merge the two halves in a sorted manner, so that only one sorted
array is left: merge(array, l, m, r)

PROGRAM :
#include<stdio.h>
void mergesort(int a[],int i,int j);
void merge(int a[],int i1,int j1,int i2,int j2);
int main()
{
int a[30],n,i;
printf("Enter no of elements:");
scanf("%d",&n);
printf("Enter array elements:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
mergesort(a,0,n-1);
printf("\nSorted array is :");
for(i=0;i<n;i++)
printf("%d ",a[i]);
return 0;
}
void mergesort(int a[],int i,int j)
{
int mid;
if(i<j)
{ mid=(i+j)/2;
mergesort(a,i,mid); //left recursion
mergesort(a,mid+1,j); //right recursion
merge(a,i,mid,mid+1,j); //merging of two sorted sub-arrays
} }
lOMoAR cPSD| 10518309

void merge(int a[],int i1,int j1,int i2,int j2)


{
int temp[50]; //array used for merging
int i,j,k;
i=i1; //beginning of the first list
j=i2; //beginning of the second list
k=0;
while(i<=j1 && j<=j2) //while elements in both lists
{
if(a[i]<a[j])
temp[k++]=a[i++];
else
temp[k++]=a[j++];
}
while(i<=j1) //copy remaining elements of the first list
temp[k++]=a[i++];
while(j<=j2) //copy remaining elements of the second list
temp[k++]=a[j++];
//Transfer elements from temp[] back to a[]
for(i=i1,j=0;i<=j2;i++,j++)
a[i]=temp[j];
}

OUTPUT :
Enter number of elements 5
Enter 5 Numbers
78
56
-23
45
9
Sorted Array:
-23 9 45 56 78

RESULT :
lOMoAR cPSD| 10518309

EX. NO. 11 IMPLEMENTATION OF OPEN ADDRESSING


DATE: (LINEAR PROBING AND QUADRATIC PROBING)

AIM :
To implement Linear probing and Quadratic Probing techniques of Open Addressing

ALGORITHM
 Define a node, structure say HashNode, to a key-value pair to be hashed.
 Initialize an array of the pointer of type HashNode, say *arr[] to store all key-value pairs.
 Insert(Key, Value): Insert the pair {Key, Value} in the Hash Table.
 Initialize a HashNode variable, say temp, with value {Key, Value}.
 Find the index where the key can be stored using the, Hash Function and then
store the index in a variable say HashIndex.
 If arr[HashIndex] is not empty or there exists another Key, then do linear
probing by continuously updating the HashIndex as HashIndex
=(HashIndex+1)%capacity.
 If arr[HashIndex] is not null, then insert the given Node by assigning the
address of temp to arr[HashIndex].
 Find(Key): Finds the value of the Key in the Hash Table.
 Find the index where the key may exist using a Hash Function and then store
the index in a variable, say HashIndex.
 If the arr[HashIndex] contains the key, Key then returns the value of it.
 Otherwise, do linear probing by continuously updating
the HashIndex as HashIndex =(HashIndex+1)%capacity. Then, if Key is
found, then return the value of the Key at that HashIndex and then return true.
 If the Key is not found, then return -1 representing not found. Otherwise, return
the value of the Key.
 Delete(Key): Deletes the Key from the Hash Table.
 Find the index where the key may exist using a Hash Function and then store
the index in a variable, say HashIndex.
 If the arr[HashIndex] contains the key, Key then delete by assigning {-1, -
1} to the arr[HashIndex] and then return true.
 Otherwise, do linear probing by continuously updating
the HashIndex as HashIndex =(HashIndex+1)%capacity. Then, if Key is
found then delete the value of the Key at that HashIndex and then return true.
 If the Key is not found, then the return is false.
lOMoAR cPSD| 10518309

PROGRAM
#include <stdio.h>
#include <conio.h>
int tsize;
int hasht(int key)
{
int i ;
i = key%tsize ;
return i;
}
//-------LINEAR PROBING-------
int rehashl(int key)
{
int i ;
i = (key+1)%tsize ;
return i ;
}
//-------QUADRATIC PROBING-------
int rehashq(int key, int j)
{
int i ;
i = (key+(j*j))%tsize ;
return i ;
}
void main()
{
int key,arr[20],hash[20],i,n,s,op,j,k ;
clrscr() ;
printf ("Enter the size of the hash table: ");
scanf ("%d",&tsize);
printf ("\nEnter the number of elements: ");
scanf ("%d",&n);
for (i=0;i<tsize;i++)
hash[i]=-1 ;
printf ("Enter Elements: ");
for (i=0;i<n;i++)
{ scanf("%d",&arr[i]); }
do
{
lOMoAR cPSD| 10518309

printf("\n\n1.Linear Probing\n2.Quadratic Probing \n3.Exit \nEnter your option: ");


scanf("%d",&op);
switch(op)
{
case 1:
for (i=0;i<tsize;i++)
hash[i]=-1 ;
for(k=0;k<n;k++)
{
key=arr[k] ;
i = hasht(key);
while (hash[i]!=-1)
{ i = rehashl(i);
}
hash[i]=key ;
}
printf("\nThe elements in the array are: ");
for (i=0;i<tsize;i++)
{
printf("\n Element at position %d: %d",i,hash[i]);
}
break ;
case 2:
for (i=0;i<tsize;i++)
hash[i]=-1 ;
for(k=0;k<n;k++)
{
j=1;
key=arr[k] ;
i = hasht(key);
while (hash[i]!=-1)
{
i = rehashq(i,j);
j++ ;
}
hash[i]=key ;
}
printf("\nThe elements in the array are: ");
}
lOMoAR cPSD| 10518309

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:
lOMoAR cPSD| 10518309

EX. NO. 12 IMPLEMENTING BFS USING QUEUE IN C


DATE:
ALGORITHM :
STEP 1 : Start by putting any one of the graph's vertices at the back of a queue.
STEP 2 : Take the front item of the queue and add it to the visited list.
STEP 3 : Create a list of that vertex's adjacent nodes. Add the ones which aren't in the
visited list to the back of the queue.
STEP 4 : Keep repeating steps 2 and 3 until the queue is empty.

PROGRAM :
#include<stdio.h>
#include<stdlib.h>
struct queue
{ int size;
int f;
int r;
int* arr; };
int isEmpty(struct queue
*q){ if(q->r==q->f) {
return 1;
} return 0; }
int isFull(struct queue
*q){ if(q->r==q->size-
1){
return 1; }
return 0; }
void enqueue(struct queue *q, int
val){ if(isFull(q)){
printf("This Queue is full\n"); }
else{
q->r++;
q->arr[q->r] = val;
// printf("Enqued element: %d\n", val);
} }
int dequeue(struct queue
*q){ int a = -1;
if(isEmpty(q)){
printf("This Queue is empty\n");
lOMoAR cPSD| 10518309

} else
{ q-
>f++;
a = q->arr[q->f];
} return a;
}
int main(){
// Initializing Queue (Array Implementation)
struct queue q;
q.size = 400;
q.f = q.r = 0;
q.arr = (int*) malloc(q.size*sizeof(int));
// BFS Implementation
int node;
int i = 1;
int visited[7] = {0,0,0,0,0,0,0};
int a [7][7] = {
{0,1,1,1,0,0,0},
{1,0,1,0,0,0,0},
{1,1,0,1,1,0,0},
{1,0,1,0,1,0,0},
{0,0,1,1,0,1,1},
{0,0,0,0,1,0,0},
{0,0,0,0,1,0,0}
};
printf("%d", i);
visited[i] = 1;
enqueue(&q, i); // Enqueue i for exploration
while (!isEmpty(&q))
{
int node = dequeue(&q);
for (int j = 0; j < 7; j++)
{
if(a[node][j] ==1 && visited[j] ==
0){ printf("%d", j);
visited[j] = 1;
enqueue(&q, j);
}
} }
return 0; }
lOMoAR cPSD| 10518309

OUTPUT :
1023456

RESULT :
lOMoAR cPSD| 10518309

EX.NO. 13 TOPOLOGICAL SORT


DATE:

AIM : To implement Topological Sorting using C Program.

ALGORITHM :
1. Store each vertex‟s In-Degree in an array D
2. Initialize queue with all “in-degree=0” vertices
3. While there are vertices remaining in the queue:
(a) Dequeue and output a vertex
(b) Reduce In-Degree of all vertices adjacent to it by 1
(c) Enqueue any of these vertices whose In-Degree became zero
4. If all vertices are output then success, otherwise there is a cycle.

PROGRAM :
#include<stdio.h>
#include<conio.h>
int main()
{
int i,j,k,n,a[10][10],indeg[10],flag[10],count=0;
printf("Enter the no of vertices:\n");
scanf("%d",&n);
printf("Enter the adjacency matrix:\n");
for(i=0;i<n;i++){
printf("Enter row %d\n",i+1);
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
}
for(i=0;i<n;i++){ i
ndeg[i]=0;
flag[i]=0; }
for(i=0;i<n;i++)
for(j=0;j<n;j++)
indeg[i]=indeg[i]+a[j][i];
printf("\nThe topological order is:");
while(count<n){
for(k=0;k<n;k++){
if((indeg[k]==0) && (flag[k]==0)){
printf("%d ",(k+1));
flag [k]=1;
}
lOMoAR cPSD| 10518309

for(i=0;i<n;i++){ if(
a[i][k]==1)
indeg[k]--;
}
}
count++;
}
return 0;
}

OUTPUT :
Enter the no of vertices:
3
Enter the adjacency matrix:
Enter row 1
1
2
3
Enter row 2
1
2
3
Enter row 3
1
2
3
The topological order is:1

RESULT:

You might also like