Data Structure - Lab Manual 2021r
Data Structure - Lab Manual 2021r
PALANCHUR, CHENNAI
(Lab Manual)
III SEMESTER
(2021 REGULATION)
CS3311 DATA STRUCTURES LABORATORY LTPC
0 0 3 1.5
COURSE OBJECTIVES:
LIST OF EXERCISES:
TOTAL:45 PERIODS
COURSE OUTCOMES:
CO-PO Mapping:
Course PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2 PSO3
C.1 1 2 2 1 2 1 2 2 2 2 3
C.2 3 3 1 1 1 1 1 3 1 2 2
C.3 2 1 3 1 1 1 2 3 3 3 3
C.4 3 1 3 3 1 2 3 3 2 1 2
C.5 3 2 1 1 2 3 3 3 1 3 1 3
C.6 3 3 1 1 1 2 2 1 1 3 2 3
Ex. No. 1A ARRAY IMPLEMENTATION OF STACK
Date:
Aim
To implement stack operations using array.
Algorithm
Step 1 - Include all the header files which are used in the program and define a
constant 'SIZE' with specific value.
Step 2 - Declare all the functions used in stack implementation.
Step 3 - Create a one dimensional array with fixed size (int stack[SIZE])
Step 4 - Define a integer variable 'top' and initialize with '-1'. (int top = -1)
Step 5 - In main method, display menu with list of operations and make
suitable function calls to perform operation selected by the user on the stack.
PROGRAM CODE
#include<stdio.h>
#include<conio.h>
#define SIZE 10
void push(int);
void pop();
void display();
int stack[SIZE], top = -1;
void main()
{
int value, choice;
clrscr();
while(1){
printf("\n\n***** MENU *****\n");
printf("1. Push\n2. Pop\n3. Display\n4. Exit");
printf("\nEnter your choice: ");
scanf("%d",&choice);
switch(choice){
case 1: printf("Enter the value to be insert: ");
scanf("%d",&value);
push(value);
break;
case 2: pop();
break;
case 3: display();
break;
case 4: exit(0);
default: printf("\nWrong selection!!! Try again!!!");
}
}
}
void push(int value){
if(top == SIZE-1)
printf("\nStack is Full!!! Insertion is not possible!!!");
else{
top++;
stack[top] = value;
printf("\nInsertion success!!!");
}
}
void pop(){
if(top == -1)
printf("\nStack is Empty!!! Deletion is not possible!!!");
else{
printf("\nDeleted : %d", stack[top]);
top--;
}
}
void display(){
if(top == -1)
printf("\nStack is Empty!!!");
else{
int i;
printf("\nStack elements are:\n");
for(i=top; i>=0; i--)
printf("%d\n",stack[i]);
}
}
OUTPUT
RESULT
Thus the C Program to implement the Stack operation using Arrays are implemented
successfully.
Ex. No. 1B ARRAY IMPLEMENTATION OF QUEUE
Date:
Aim
To implement Queue operations using array.
Algorithm
PROGRAM CODE
#include<stdio.h>
#include<stdlib.h>
#define maxsize 5
void insert();
void delete();
void display();
int front = -1, rear = -1;
int queue[maxsize];
void main ()
{
int choice;
while(choice != 4)
{
printf("\n*************************Main
Menu*****************************\n");
printf("\n==================================================
===============\n");
printf("\[Link] an element\[Link] an element\[Link] the
queue\[Link]\n");
printf("\nEnter your choice ?");
scanf("%d",&choice);
switch(choice)
{
case 1:
insert();
break;
case 2:
delete();
break;
case 3:
display();
break;
case 4:
exit(0);
break;
default:
printf("\nEnter valid choice??\n");
}
}
}
void insert()
{
int item;
printf("\nEnter the element\n");
scanf("\n%d",&item);
if(rear == maxsize-1)
{
printf("\nOVERFLOW\n");
return;
}
if(front == -1 && rear == -1)
{
front = 0;
rear = 0;
}
else
{
rear = rear+1;
}
queue[rear] = item;
printf("\nValue inserted ");
}
void delete()
{
int item;
if (front == -1 || front > rear)
{
printf("\nUNDERFLOW\n");
return;
}
else
{
item = queue[front];
if(front == rear)
{
front = -1;
rear = -1 ;
}
else
{
front = front + 1;
}
printf("\nvalue deleted ");
}
void display()
{
int i;
if(rear == -1)
{
printf("\nEmpty queue\n");
}
else
{ printf("\nprinting values .....\n");
for(i=front;i<=rear;i++)
{
printf("\n%d\n",queue[i]);
} }}
OUTPUT:
*************Main Menu**************
==============================================
[Link] an element
[Link] an element
[Link] the queue
[Link]
Enter your choice ?1
Enter the element
123
Value inserted
Result
Thus the C Program to implement the Queue operations using array was
executed successfully.
Ex. No. 1C ARRAY IMPLEMENTATION OF CIRCULAR QUEUE
Date:
Aim
To implement Circular Queue operations using array.
Algorithm
PROGRAM CODE
#include <stdio.h>
# define max 6
int queue[max]; // array declaration
int front=-1;
int rear=-1;
// function to insert an element in a circular queue
void enqueue(int element)
{
if(front==-1 && rear==-1) // condition to check queue is empty
{
front=0;
rear=0;
queue[rear]=element;
}
else if((rear+1)%max==front) // condition to check queue is full
{
printf("Queue is overflow..");
}
else
{
rear=(rear+1)%max; // rear is incremented
queue[rear]=element; // assigning a value to the queue at the rear position.
}
}
switch(choice)
{
case 1:
}}
return 0;
}
OUTPUT:
RESULT
Thus the C program to implement the circular queue operations are executed
successfully.
Ex. No. 2 IMPLEMENTATION OF SINGLY LINKED LIST
Date:
AIM
To implement Singly linked list 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 CODE
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void insertAtBeginning(int);
void insertAtEnd(int);
void insertBetween(int,int,int);
void display();
void removeBeginning();
void removeEnd();
void removeSpecific(int);
struct Node
{
int data;
struct Node *next;
}*head = NULL;
void main()
{
int choice,value,choice1,loc1,loc2;
clrscr();
while(1){
mainMenu: printf("\n\n****** MENU ******\n1. Insert\n2. Display\n3.
Delete\n4. Exit\nEnter your choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1: printf("Enter the value to be insert: ");
scanf("%d",&value);
while(1){
printf("Where you want to insert: \n1. At Beginning\n2. At End\n3.
Between\nEnter your choice: ");
scanf("%d",&choice1);
switch(choice1)
{
case 1: insertAtBeginning(value);
break;
case 2: insertAtEnd(value);
break;
case 3: printf("Enter the two values where you wanto insert: ");
scanf("%d%d",&loc1,&loc2);
insertBetween(value,loc1,loc2);
break;
default: printf("\nWrong Input!! Try again!!!\n\n");
goto mainMenu;
}
goto subMenuEnd;
}
subMenuEnd:
break;
case 2: display();
break;
case 3: printf("How do you want to Delete: \n1. From Beginning\n2. From
End\n3. Spesific\nEnter your choice: ");
scanf("%d",&choice1);
switch(choice1)
{
case 1: removeBeginning();
break;
case 2: removeEnd();
break;
case 3: printf("Enter the value which you wanto delete: ");
scanf("%d",&loc2);
removeSpecific(loc2);
break;
default: printf("\nWrong Input!! Try again!!!\n\n");
goto mainMenu;
}
break;
case 4: exit(0);
default: printf("\nWrong input!!! Try again!!\n\n");
}
}
}
void removeBeginning()
{
if(head == NULL)
printf("\n\nList is Empty!!!");
else
{
struct Node *temp = head;
if(head->next == NULL)
{
head = NULL;
free(temp);
}
else
{
head = temp->next;
free(temp);
printf("\nOne node deleted!!!\n\n");
}
}
}
void removeEnd()
{
if(head == NULL)
{
printf("\nList is Empty!!!\n");
}
else
{
struct Node *temp1 = head,*temp2;
if(head->next == NULL)
head = NULL;
else
{
while(temp1->next != NULL)
{
temp2 = temp1;
temp1 = temp1->next;
}
temp2->next = NULL;
}
free(temp1);
printf("\nOne node deleted!!!\n\n");
}
}
void removeSpecific(int delValue)
{
struct Node *temp1 = head, *temp2;
while(temp1->data != delValue)
{
if(temp1 -> next == NULL){
printf("\nGiven node not found in the list!!!");
goto functionEnd;
}
temp2 = temp1;
temp1 = temp1 -> next;
}
temp2 -> next = temp1 -> next;
free(temp1);
printf("\nOne node deleted!!!\n\n");
functionEnd:
}
void display()
{
if(head == NULL)
{
printf("\nList is Empty\n");
}
else
{
struct Node *temp = head;
printf("\n\nList elements are - \n");
while(temp->next != NULL)
{
printf("%d --->",temp->data);
temp = temp->next;
}
printf("%d --->NULL",temp->data);
}
}
OUTPUT
RESULT:
Thus the C program to implement the singly linked list was executed successfully
Ex. No. 3 LINKED LIST IMPLEMENTATION OF STACK AND LINEAR QUEUE
Date:
AIM
To implement linked list implementation of stack and linear queue
ALGORITHM
Step 1 - Include all the header files which are used in the program. And declare all
the user defined functions.
Step 2 - Define a 'Node' structure with two members data and next.
Step 3 - Define a Node pointer 'top' and set it to NULL.
Step 4 - Implement the main method by displaying Menu with list of operations and
make suitable function calls in the main method.
PROGRAM CODE
#include<stdio.h>
#include<conio.h>
struct Node
{
int data;
struct Node *next;
}*top = NULL;
void push(int);
void pop();
void display();
void main()
{
int choice, value;
clrscr();
printf("\n:: Stack using Linked List ::\n");
while(1){
printf("\n****** MENU ******\n");
printf("1. Push\n2. Pop\n3. Display\n4. Exit\n");
printf("Enter your choice: ");
scanf("%d",&choice);
switch(choice){
case 1: printf("Enter the value to be insert: ");
scanf("%d", &value);
push(value);
break;
case 2: pop(); break;
case 3: display(); break;
case 4: exit(0);
default: printf("\nWrong selection!!! Please try again!!!\n");
}
}
}
void push(int value)
{
struct Node *newNode;
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
if(top == NULL)
newNode->next = NULL;
else
newNode->next = top;
top = newNode;
printf("\nInsertion is Success!!!\n");
}
void pop()
{
if(top == NULL)
printf("\nStack is Empty!!!\n");
else{
struct Node *temp = top;
printf("\nDeleted element: %d", temp->data);
top = temp->next;
free(temp);
}
}
void display()
{
if(top == NULL)
printf("\nStack is Empty!!!\n");
else{
struct Node *temp = top;
while(temp->next != NULL){
printf("%d--->",temp->data);
temp = temp -> next;
}
printf("%d--->NULL",temp->data);
}
}
OUTPUT
RESULT:
Thus the C program to implement the stack using linked list was executed
successfully
Ex. No. 4 IMPLEMENTATION OF POLYNOMIAL MANIPULATION USING
LINKED LIST
Date:
Aim
To implement polynomial manipulation using linked list
Algorithm:
Step 1:- Initialize the Structure with coefficient and power also pointer to next
position.
Step 2:- Write a Function create_node to create new node.
Step 3:- Create a node to store power and coeff of a variable.
Step 4:- Write a Function polyadd to add two polynomial numbers.
Step 5:- If power of 1st polynomial is greater then 2nd, then store 1st as it is and
move its pointer
Step 6:- If power of both polynomial numbers is same then add their coefficients
Step 7:- Finally display resultant Linked List.
PROGRAM:
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;
// Driver program
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);
OUTPUT:
RESULT:
Aim
To implement evaluating postfix expression
Algorithm
PROGRAM
#include<stdio.h>
#include<string.h>
#include<ctype.h>
int pop();
int i,l,top=-1,value[25],val,p,q,r;
char a[25],x;
void main()
{
printf("\nEnter the postfix expression\n");
gets(a);
l=strlen(a);
for(i=0;i<l;i++)
{ if(isalpha(a[i]))
{
printf("\nEnter the value for %c",a[i]);
scanf("%d",&val);
top=top+1; value[top]=val;
}
else
{
x=a[i];
p=pop();
q=pop(); switch(x)
{
case '+': r=p+q;
top=top+1; value[top]=r; break;
case '-': r=q-p;
top=top+1; value[top]=r; break;
case '*': r=p*q;
top=top+1; value[top]=r; break;
case '/': r=q/p;
top=top+1; value[top]=r; break;
}
}
}
r=value[top];
printf("\nValue of expression is %d",r);
}
int pop()
{
int ch; ch=value[top]; top=top-1; return ch;
}
OUTPUT
Enter the value for a 130 Enter the value for b 4 Enter the value for c 2
Value of expression is 132
RESULT:
Thus the above c program to evaluate a postfix expression using Stack is executed
successfully.
Ex. No. 6 IMPLEMENTATION OF BINARY SEARCH TREE
Date:
Aim
To write a C program to implement Binary Search Tree using C.
Algorithm:
Step 1:- Initialize the Structure with value and pointers for left- right node.
Step 2:- Three (preorder, postorder and inorder) operations for depth-first traversal of a
tree.
Step 2.2:- Inorder: Visit a node after traversing it’s left subtree but before
Step 2.3:- Postorder: Visit a node after traversing all of it’s subtrees.
Step 3:- To find search smallest and largest element compare and go to the left sub tree
to find the min element .
Step 4:- Write a Function to search the appropriate position to insert the new node .
#include <stdio.h>
#include <stdlib.h>
struct btnode
{
int value;
struct btnode *l;
struct btnode *r;
}*root = NULL, *temp = NULL, *t2, *t1;
void delete1();
void insert();
void delete();
void inorder(struct btnode *t);
void create();
void search(struct btnode *t);
void preorder(struct btnode *t);
void postorder(struct btnode *t);
void search1(struct btnode *t,int data);
int smallest(struct btnode *t);
int largest(struct btnode *t);
{
int ch;
printf("\nOPERATIONS ---");
printf("\n1 - Insert an element into tree\n");
printf("2 - Delete an element from the tree\n");
printf("3 - Inorder Traversal\n");
printf("4 - Preorder Traversal\n");
printf("5 - Postorder Traversal\n");
printf("6 - Exit\n");
while(1)
{
printf("\nEnter your choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
insert();
break;
case 2:
delete();
break;
case 3:
inorder(root);
break;
case 4:
preorder(root);
break;
case 5:
postorder(root);
break;
case 6:
exit(0);
default :
printf("Wrong choice, Please enter correct choice ");
break;
}
}
}/* To insert a node in the tree */
void insert()
{
create();
if (root == NULL)
root = temp;
else
search(root);
}
/* To create a node */
void create()
{
int data;
if (root == NULL)
{
printf("No elements in a tree to delete");
return;
}
printf("Enter the data to be deleted : ");
scanf("%d", &data);
t1 = root;
t2 = root;
search1(root, data);
}
/* To delete a node */
void delete1(struct btnode *t)
{
int k;
}
else
{
t1->r = t->l;
}
t = NULL;
free(t);
return;
}
OUTPUT :
OPERATIONS ---
1 - Insert an element into tree
2 - Delete an element from the tree
3 - Inorder Traversal
4 - Preorder Traversal
5 - Postorder Traversal
6 - Exit
RESULT:
Thus the above c program to implement Binary Search Tree is executed successfully
Ex. No. 7 IMPLEMENTATION OF AVL TREE
Date:
Aim:
To write a C program to implement AVL Tree.
Algorithm:
Step 1:- Initialize the Structure with balance and pointer for left, right node
.
Step 2:- Write a Function for insertion operation.
Step 3:- Read the insert element from the user
Step 4:- Insert the new element into the tree using Binary Search Tree
insertion logic. Step 5:- After insertion, check the Balance Factor of every
node.
Step 6:- If the Balance Factor of every node is 0 or 1 or -1 then go for next
operation.
Step 7:- If the Balance Factor of any node is other than 0 or 1 or -1 then tree
is said to be imbalanced.
Step 8:- Then perform the suitable single(LL or RR) or double(LR or RL)
Rotation to make it balanced. And then terminate the program.
PROGRAM:
#include<stdio.h>
#include<malloc.h>
typedef enum { FALSE ,TRUE } bool;
struct node
{
int info;
int balance;
struct node *lchild; struct node *rchild;
};
struct node *insert (int , struct node *, int *);
struct node* search(struct node *,int);
int main()
{
bool ht_inc; int info ;
int choice;
struct node *root = (struct node *)malloc(sizeof(struct node)); root = NULL;
while(1)
{
printf("[Link]\n"); printf("[Link]\n"); printf("[Link]\n"); printf("Enter your
choice : "); scanf("%d",&choice); switch(choice)
{
case 1:
printf("Enter the value to be inserted : "); scanf("%d", &info);
if( search(root,info) == NULL ) root = insert(info, root, &ht_inc);
else
printf("Duplicate value ignored\n"); break;
case 2:
if(root==NULL)
{
printf("Tree is empty\n"); continue;
}
printf("Tree is :\n"); display(root, 1); printf("\n\n");
printf("Inorder Traversal is: "); inorder(root);
printf("\n"); break;
case 3:
exit(1); default:
printf("Wrong choice\n");
}/*End of switch*/
}/*End of while*/
}/*End of main()*/
struct node* search(struct node *ptr,int info)
{
if(ptr!=NULL) if(info < ptr->info)
ptr=search(ptr->lchild,info); else if( info > ptr->info)
ptr=search(ptr->rchild,info); return(ptr);
}/*End of search()*/
struct node *insert (int info, struct node *pptr, int *ht_inc)
{
struct node *aptr; struct node *bptr; if(pptr==NULL)
{
pptr = (struct node *) malloc(sizeof(struct node)); pptr->info = info;
pptr->lchild = NULL; pptr->rchild = NULL; pptr->balance = 0;
*ht_inc = TRUE; return (pptr);
}
if(info < pptr->info)
{
pptr->lchild = insert(info, pptr->lchild, ht_inc); if(*ht_inc==TRUE)
{
switch(pptr->balance)
{
case -1: /* Right heavy */ pptr->balance = 0;
*ht_inc = FALSE; break;
case 0: /* Balanced */
pptr->balance = 1; break;
case 1: /* Left heavy */ aptr = pptr->lchild; if(aptr->balance == 1)
{
printf("Left to Left Rotation\n"); pptr->lchild= aptr->rchild;
aptr->rchild = pptr; pptr->balance = 0; aptr->balance=0; pptr = aptr;
}
else
{
printf("Left to right rotation\n"); bptr = aptr->rchild;
aptr->rchild = bptr->lchild; bptr->lchild = aptr;
pptr->lchild = bptr->rchild; bptr->rchild = pptr;
}/*End of if*/
if(bptr->balance == -1)
pptr->balance = 1; else
pptr->balance = 0;
if(bptr->balance == 1)
aptr->balance = -1; else
aptr->balance = 0; bptr->balance=0; pptr = bptr;
}/*End of else*/
*ht_inc = FALSE;
}/*End of switch */
}/*End of if*/
}/*End of if*/ return(pptr);
}/*End of insert()*/
display(struct node *ptr,int level)
{
int i;
if ( ptr!=NULL )
{
display(ptr->rchild, level+1); printf("\n");
for (i = 0; i < level; i++) printf(" ");
printf("%d", ptr->info); display(ptr->lchild, level+1);
}/*End of if*/
}/*End of display()*/
OUTPUT:
[Link]
[Link] [Link]
Enter your choice : 1
Enter the value to be inserted : 201
[Link]
[Link] [Link]
Enter your choice : 1
Enter the value to be inserted : 300
[Link]
[Link] [Link]
Enter your choice : 1
Enter the value to be inserted : 1001
Right to Right Rotation
[Link] [Link] [Link]
Enter your choice : 2 Tree is :
1001
300
201
1001
300
201
10
RESULT:
Thus the above c program to implement AVL Tree is executed successfully.
Ex. No. 8 IMPLEMENTATION OF HEAP USING PRIORITY QUEUE
Date:
Aim:
To write a C program to implement heap using priority Queue
Algorithm:
Step 1:- Initialize the Structure with priority, information and pointer to
next node .
Step 2:- Write a Function for insertion, deletion and display operation.
Step 3:- Read the insert element and its priority from the user.
Step 4:- Insert the element according to the priority in appropriate node.
Step 5:- Delete the queue using del function, display “QUEUE
UNDERFLOW” if null.
Step 6:- Display the queue with separate function and terminate the
execution.
PROGRAM:
#include<stdio.h>
#include<malloc.h>
void insert();
void del();
void display();
struct node
{
int main()
int ch; do
{
scanf("%d",&ch); switch(ch)
{
break;
while(ch<4);
void insert()
scanf("%d",&item);
//new->next=start; start=new;
}
else if(start!=NULL&&itprio<=start->priority)
{ new->next=start; start=new;
}
else
q=start;
{q=q->next;}
new->next=q->next; q->next=new;
}
}
void del()
if(start==NULL)
printf("\nQUEUE UNDERFLOW\n");
else
new=start;
void display()
temp=start; if(start==NULL)
printf("QUEUE IS EMPTY\n"); else
{
//temp=temp->next;
}
OUTPUT:
[1] INSERTION
[2] DELETION
[3] DISPLAY
[4] EXIT
:1
ENTER THE [Link] BE INSERTED : 7
ENTER ITS PRIORITY : 3
13 priority =1
10 priority =2
7 priority =3
DELETED ITEM IS 13
[1] INSERTION [2] DELETION [3] DISPLAY [4] EXIT
RESULT:
Thus the above c program to implement heap using priority Queue is
executed successfully.
Ex. No. 9 IMPLEMENTATION OF DIJIKSTRAS ALGORITHM
Date:
Aim
To implement Dijkstra’s algorithm in C
Algorithm
Step 1 - Create cost matrix C[ ][ ] from adjacency matrix adj[ ][ ]. 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.
Step 2 - Array visited[ ] is initialized to zero.
for(i=0;i<n;i++)
visited[i]=0;
Step 3 - If the vertex 0 is the source vertex then visited[0] is marked as 1.
Step 4 - Create the distance matrix, by storing the cost of vertices from vertex
no. 0 to n-1 from the source vertex 0.
for(i=1;i<n;i++)
distance[i]=cost[0][i];
Step 5: if(visited[v]==0)
distance[v]=min(distance[v],
distance[w]+cost[w][v])
PROGRAM CODE:
#include<stdio.h>
#include<conio.h>
#define INFINITY 9999
#define MAX 10
int main()
{
int G[MAX][MAX],i,j,n,u;
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]);
printf("\nEnter the starting node:");
scanf("%d",&u);
dijkstra(G,n,u);
return 0;
}
int cost[MAX][MAX],distance[MAX],pred[MAX];
int visited[MAX],count,mindistance,nextnode,i,j;
//pred[] stores the predecessor of each node
//count gives the number of nodes seen so far
//create the cost matrix
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];
//initialize pred[],distance[] and visited[]
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;
while(count<n-1)
{
mindistance=INFINITY;
//nextnode gives the node at minimum distance
for(i=0;i<n;i++)
if(distance[i]<mindistance&&!visited[i])
{
mindistance=distance[i];
nextnode=i;
}
//check if a better path exists through nextnode
visited[nextnode]=1;
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++;
}
OUTPUT
RESULT:
Thus the C program to implement Dijkstra’s algorithm is done successfully.
Ex. No. 10 IMPLEMENTATION OF PRIMS ALGORITHM
Date:
Aim
To implement prims algorithm in C
Algorithm
Step 1 - Start
Step 2 - Create edge list of given graph, with their weights.
Step 3 -Draw all nodes to create skeleton for spanning tree.
Step 4 - Select an edge with lowest weight and add it to skeleton and delete
edge from edge list.
Step 5 - Add other edges. While adding an edge take care that the one end of
the edge should always be in the skeleton tree and its cost should be minimum.
Step 6: Repeat step 5 until n-1 edges are added.
PROGRAM CODE
#include<stdio.h>
#include<stdlib.h>
int G[MAX][MAX],spanning[MAX][MAX],n;
int prims();
int main()
{
int i,j,total_cost;
printf("Enter no. of vertices:");
scanf("%d",&n);
printf("\nEnter the adjacency matrix:\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
total_cost=prims();
printf("\nspanning tree matrix:\n");
for(i=0;i<n;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("%d\t",spanning[i][j]);
}
printf("\n\nTotal cost of spanning tree=%d",total_cost);
return 0;
}
int prims()
{
int cost[MAX][MAX];
int u,v,min_distance,distance[MAX],from[MAX];
int visited[MAX],no_of_edges,i,min_cost,j;
//create cost[][] matrix,spanning[][]
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
if(G[i][j]==0)
cost[i][j]=infinity;
else
cost[i][j]=G[i][j];
spanning[i][j]=0;
}
//initialise visited[],distance[] and from[]
distance[0]=0;
visited[0]=1;
for(i=1;i<n;i++)
{
distance[i]=cost[0][i];
from[i]=0;
visited[i]=0;
}
min_cost=0; //cost of spanning tree
no_of_edges=n-1; //no. of edges to be added
while(no_of_edges>0)
{
//find the vertex at minimum distance from the tree
min_distance=infinity;
for(i=1;i<n;i++)
if(visited[i]==0&&distance[i]<min_distance)
{
v=i;
min_distance=distance[i];
}
u=from[v];
//insert the edge in spanning tree
spanning[u][v]=distance[v];
spanning[v][u]=distance[v];
no_of_edges--;
visited[v]=1;
//updated the distance[] array
for(i=1;i<n;i++)
if(visited[i]==0&&cost[i][v]<distance[i])
{
distance[i]=cost[i][v];
from[i]=v;
}
min_cost=min_cost+cost[u][v];
}
return(min_cost);
}
OUTPUT
031000
300030
100004
000002
030000
004200
RESULT:
Thus the C program to implement the Prims algorithm was done successfully.
Ex. No. 11A IMPLEMENTATION OF LINEAR SEARCH
Date:
Aim
To implement Linear search using C
Algorithm
Program
#include<stdio.h>
void main()
{
int array[100],s
search,c,n;
printf("Enter the Number of elements\n");
scanf("%d",&n);
printf("Enter the Elements\n");
for (c=0; c<n;c++)
scanf("%d", &array[c]);
printf("Enter the number to search\n");
scanf("%d", &search);
for(c=0;c<n;c++)
{
if(array[c] == search)
{
printf("%d is present at location %d.\n",search,c+1); break;
}
}
if(c==n)
{
printf("%d is not present in array.\n",search);
}
//return 0;
}
OUTPUT
RESULT:
Thus the above c program to implement linear search is executed successfully.
Ex. No. 11B IMPLEMENTATION OF BINARY SEARCH
Date:
Aim
To implement Binary Search in C
Algorithm
PROGRAM CODE
#include<stdio.h>
int BinarySearch(int *array, int n, int key)
{
int low = 0, high = n-1,
mid; while(low <= high)
{
mid = (low + high)/2;
if(array[mid] < key)
{
low = mid + 1;
}
else if(array[mid] == key)
{
return mid;
}
else if(array[mid] > key)
{
high = mid-1;
}
}
return -1;
}
int main()
{
int n=5;
int array[n];
int
i,key,index;
printf("\nEnter the 5 elements");
//scanf("%d",&n);
printf("\nEnter the
elements");for(i = 0;i < n;i++)
{
scanf("%d",&array[i]);
}
for(i = 1;i < n;i++)
{
if(array[i] < array[i - 1])
{
printf("Given input is not
sorted\n"); return 0;
}
}
printf("Enter the key to be
searched"); scanf("%d",&key);
index =
BinarySearch(array,n,key);
if(index==-1)
{
printf("Element not found\n");
}
else
{
printf("Element is at index %d\n",index);
}
return 0;
}
OUTPUT
RESULT
Thus the program to implement binary Search was executed successfully.
Ex. No. 12A IMPLEMENTATION OF INSERTION SORT
Date:
Aim
To implement insertion sort using C
Algorithm
Step 1 − If it is the first element, it is already
sorted. return 1; Step 2 − Pick next element
Step 3 − Compare with all elements in the sorted sub-list
Step 4 − Shift all the elements in the sorted sub-list that is greater than the
value to be sorted
Step 5 − Insert the value
Step 6 − Repeat until list is sorted
PROGRAM CODE
#include<stdio.h>
int main()
{
int data[100],n,temp,i,j;
printf("Enter number of terms(should be less than 100): ");
scanf("%d",&n);
printf("Enter elements: ");
for(i=0;i<n;i++)
{
scanf("%d",&data[i]);
}
for(i=1;i<n;i++)
{
temp = data[i];
j=i-1;
while(temp<data[j] && j>=0)
/*To sort elements in descending order, change temp<data[j] to temp>data[j] in above line.*/
{
data[j+1] = data[j];
--j;
}
data[j+1]=temp;
}
printf("In ascending order: ");
for(i=0; i<n; i++)
printf("%d\t",data[i]);
return 0;
}
OUTPUT :
RESULT:
The given program was executed and the output of the program was verified.
Ex. No. 12A IMPLEMENTATION OF SELECTION SORT
Date:
Aim
To implement selection sort using C
Algorithm
Step 3 – swap the first location with the minimum value in the array
PROGRAM CODE
#include <stdio.h>
int main()
{
int a[100], n, i, j, position, swap;
printf("Enter number of elementsn");
scanf("%d", &n);
printf("Enter %d Numbersn", n);
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
for(i = 0; i < n - 1; i++)
{
position=i;
for(j = i + 1; j < n; j++)
{
if(a[position] > a[j])
position=j;
}
if(position != i)
{
swap=a[i];
a[i]=a[position];
a[position=swap;
}
}
printf("Sorted Array:n");
for(i = 0; i < n; i++)
printf("%dn", a[i]);
return 0;
}
OUTPUT
RESULT:
The given program was executed and the output of the program was verified.
Ex. No. 13 IMPLEMENTATION OF MERGE SORT
Date:
Aim
To implement merge sort using C
Algorithm
Step 1: Declare left variable to 0 and right variable to n-1
Step 2: Find mid by medium formula. mid = (left+right)/2
Step 3: Call merge sort on (left,mid)
Step 4:Call merge sort on (mid+1,rear)
Step 5:Continue till left is less than right
Step 6:Then call merge function to perform merge sort.
PROGRAM CODE
#include <stdio.h>
#define max 10
int a[11] = { 10, 14, 19, 26, 27, 31, 33, 35, 42, 44, 0 };
int b[10];
for(l1 = low, l2 = mid + 1, i = low; l1 <= mid && l2 <= high; i++) {
if(a[l1] <= a[l2])
b[i] = a[l1++];
else
b[i] = a[l2++];
}
int main() {
int i;
sort(0, max);
OUTPUT
RESULT
The given program was executed and the output of the program was verified.
Ex. No. 14 IMPLEMENTATION OF HASHING USING OPEN ADDRESSING
Date:
Aim
To implement HASHING USING OPEN ADDRESSING using C.
Algorithm
PROGRAM CODE
#include
<stdio.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 ;
for (i=0;i<tsize;i++)
hash[i]=-1 ;
printf ("Enter Elements:
"); for (i=0;i<n;i++)
scanf("%d",&arr[i]);
do
{
printf("\n\[Link] Probing\[Link] Probing \[Link] \nEnter your option: ");
scanf("%d",&op
); switch(op)
{
case
1: for
(i=0;i<tsize;i++)
hash[i]=-1 ;
for(k=0;k<n;k++)
{
key=arr[k] ;
i = hasht(key); while (hash[i]!=-
1)
{
i = rehashl(i);
}
hash[i]=key ;
}
printf("\nThe elements in the array are: "); for
(i=0;i<tsize;i++)
printf("\n Element at position %d:%d",i,hash[i]); break ;
case 2:
for (i=0;i<tsize;i++)
hash[i]=-1 ;
for(k=0;k<n;k++)
{
j=1;
key=arr[k] ;
i = hasht(key); while (hash[i]!=-
1)
{
i = rehashq(i,j); j++ ;
}
hash[i]=key ;
}
printf("\nThe elements in the array are: "); for
(i=0;i<tsize;i++)
{
printf("\n Element at position %d: %d",i,hash[i]);
}
break ;
}
}while(op!=3);
Output:
number of elements: 7
Enter Elements: 110 200 1001 2001 30 25 1
[Link] Probing [Link]
Probing [Link]
Enter your option: 1
Result:
Thus the above c program to implement Hashing using Linear and Quatratic Probing is executed
successfully.