DS&CA Lab Manual

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

DATA STRUCTURES AND ALGORITHMS LAB FEBRUARY 2024

S.NO DATE PROGRAM NAME PAGENO SIGN

Data structures and algorithms

1. Array implementation of stacks 03

2. Array implementation of Queues 07

3. Linked List Implementation of stacks 11

4. Linked List implementation of Queues 16

5. Binary Tree Traversals 22


(Inorder, Preorder, Postorder)

6. Implementation of Linear search and 26


binary search

7. Implementation Insertion sort, Quick sort 30


and Merge sort

8. Implementation of DFS & BFS of Graphs 36

9. Finding all pairs of Shortest Path of a 42


Graph

10. Finding single source shortest Path of a 46


Graph
DATA STRUCTURES& ALGORITHMS LAB FEBRUARY 2024

Data structure
&
Algorithms

2 SACWC
DATA STRUCTURES& ALGORITHMS LAB FEBRUARY 2024

Ex no:01
Array Implementation of Stack

Aim:
To write a program for the array implementation of Stack in C.

Algorithm:
1) Start the Program.
2) Type the codings in Turbo C.
3) Define a array stack of size max = 5
4) Display a menu listing stack operations.
5) Use if..else statement to check the conditions.
6) Compile the program filename.cpp.
7) Run the program.
8) Save the program with extension .cpp.
9) Stop the program.

3 SACWC
DATA STRUCTURES& ALGORITHMS LAB FEBRUARY 2024

Source code:
#include<stdio.h>
int stack[100],choice,n,top,x,i;
void push(void);
void pop(void);
void display(void);
int main()
{
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:
{
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)");
}

4 SACWC
DATA STRUCTURES& ALGORITHMS LAB FEBRUARY 2024

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

5 SACWC
DATA STRUCTURES& ALGORITHMS LAB FEBRUARY 2024

Output:
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
Result:
Thus the program has been successfully obtained and the output is verified.

6 SACWC
DATA STRUCTURES& ALGORITHMS LAB FEBRUARY 2024

Ex no:02
ARRAY Implementation of Queues

Aim:
To write a program for the array implementation of Queues in C.

Algorithm:
1) Start the Program.
2) Type the codings in Turbo C.
3) Define a array stack of size max = 5
4) Display a menu listing queue operations.
5) Use if..else statement to check the conditions.
6) Compile the program filename.cpp.
7) Run the program.
8) Save the program with extension .cpp.
9) Stop the program.

7 SACWC
DATA STRUCTURES& ALGORITHMS LAB FEBRUARY 2024

Source code:
#include<stdio.h>
#define n 5
int main()
{
int queue[n],ch=1,front=0,rear=0,i,j=1,x=n;
printf("Queue using Array");
printf("\n1.Insertion \n2.Deletion \n3.Display \n4.Exit");
while(ch)
{
printf("\nEnter the Choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
if(rear==x)
printf("\n Queue is Full");
else
{
printf("\n Enter no %d:",j++);
scanf("%d",&queue[rear++]);
}
break;
case 2:
if(front==rear)
{
printf("\n Queue is empty");
}
else
{
printf("\n Deleted Element is %d",queue[front++]);
x++;
}
break;
case 3:
printf("\nQueue Elements are:\n ");
if(front==rear)
printf("\n Queue is Empty");
else
{
for(i=front; i<rear; i++)
{
printf("%d",queue[i]);
printf("\n");
}
break;

8 SACWC
DATA STRUCTURES& ALGORITHMS LAB FEBRUARY 2024

case 4:
exit(0);
default:
printf("Wrong Choice: please see the options");
}
}
}
return 0;
}

9 SACWC
DATA STRUCTURES& ALGORITHMS LAB FEBRUARY 2024

Output:
Queue using Array

1.Insertion
2.Deletion
3.Display
4.Exit

Enter the Choice:1


Enter no 1:10

Enter the Choice:1


Enter no 2:54

Enter the Choice:1


Enter no 3:98

Enter the Choice:1


Enter no 4:234

Enter the Choice:3

Queue Elements are:


10
54
98
234

Enter the Choice:2

Deleted Element is 10
Enter the Choice:3

Queue Elements are:


54
98
234

Result:
Thus the program has been successfully obtained and the output is verified.

10 SACWC
DATA STRUCTURES& ALGORITHMS LAB FEBRUARY 2024

Ex no:03
LINKED LIST Implementation of STACKS

Aim:
To write a program for the linked list implementation of stacks in C.

Algorithm:
1) Start the Program.
2) Type the codings in Turbo C.
3) Define a array stack of size max = 5
4) Display a menu listing stack operations.
5) Use if..else statement to check the conditions.
6) Compile the program filename.cpp.
7) Run the program.
8) Save the program with extension .cpp.
9) Stop the program.

11 SACWC
DATA STRUCTURES& ALGORITHMS LAB FEBRUARY 2024

Source code:
#include <stdio.h>
#include <stdlib.h>

// Structure to create a node with data and the next pointer


struct node {
int info;
struct node *ptr;
}*top,*top1,*temp;

int count = 0;
// Push() operation on a stack
void push(int data) {
if (top == NULL)
{
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++;
printf("Node is Inserted\n\n");
}

int pop() {
top1 = top;

if (top1 == NULL)
{
printf("\nStack Underflow\n");
return -1;
}
else
top1 = top1->ptr;
int popped = top->info;
free(top);
top = top1;
count--;
return popped;
}

12 SACWC
DATA STRUCTURES& ALGORITHMS LAB FEBRUARY 2024

void display() {
// Display the elements of the stack
top1 = top;

if (top1 == NULL)
{
printf("\nStack Underflow\n");
return;
}

printf("The stack is \n");


while (top1 != NULL)
{
printf("%d--->", top1->info);
top1 = top1->ptr;
}
printf("NULL\n\n");
}

int main() {
int choice, value;
printf("\nImplementation of Stack using Linked List\n");
while (1) {
printf("\n1. Push\n2. Pop\n3. Display\n4. Exit\n");
printf("\nEnter your choice : ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("\nEnter the value to insert: ");
scanf("%d", &value);
push(value);
break;
case 2:
printf("Popped element is :%d\n", pop());
break;
case 3:
display();
break;
case 4:
exit(0);
break;
default:
printf("\nWrong Choice\n");
}
}
}

13 SACWC
DATA STRUCTURES& ALGORITHMS LAB FEBRUARY 2024

Output:
Push Operation:

Implementation of Stack using Linked List


1. Push
2. Pop
3. Display
4. Exit

Enter your choice : 1


Enter the value to insert: 12

Node is Inserted

1. Push
2. Pop
3. Display
4. Exit

Enter your choice : 1


Enter the value to insert: 45

Node is Inserted

1. Push
2. Pop
3. Display
4. Exit

Enter your choice : 1


Enter the value to insert: 56

Node is Inserted

1. Push
2. Pop
3. Display
4. Exit

Enter your choice : 3


The stack is 56--->45--->12--->NULL

14 SACWC
DATA STRUCTURES& ALGORITHMS LAB FEBRUARY 2024

Pop Operation:

The stack is
56--->45--->12--->NULL

1. Push
2. Pop
3. Display
4. Exit

Enter your choice : 2


Popped element is : 56

1. Push
2. Pop
3. Display
4. Exit

Enter your choice : 2


Popped element is : 45

1. Push
2. Pop
3. Display
4. Exit

Enter your choice : 3


The stack is
12--->NULL

1. Push
2. Pop
3. Display
4. Exit

Enter your choice : 2


Popped element is : 12

1. Push
2. Pop
3. Display
4. Exit

RESULT:
Thus the program has been successfully obtained and the output is verified.

15 SACWC
DATA STRUCTURES& ALGORITHMS LAB FEBRUARY 2024

Ex no:04
Linked list Implementation of Queues

Aim:
To write a program for the implementation of Queue using Linked list in C.

Algorithm:
1) Start the Program.
2) Type the codings in Turbo C.
3) Define a array stack of size max = 5
4) Display a menu listing Queues operations.
5) Use if..else statement to check the conditions.
6) Compile the program filename.cpp.
7) Run the program.
8) Save the program with extension .cpp.
9) Stop the program.

16 SACWC
DATA STRUCTURES& ALGORITHMS LAB FEBRUARY 2024

Source code:
#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();
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;

17 SACWC
DATA STRUCTURES& ALGORITHMS LAB FEBRUARY 2024

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

18 SACWC
DATA STRUCTURES& ALGORITHMS LAB FEBRUARY 2024

else
{
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)
{
front1 = front1->ptr;
printf("\n Dequed value : %d", front->info);
free(front);

19 SACWC
DATA STRUCTURES& ALGORITHMS LAB FEBRUARY 2024

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

20 SACWC
DATA STRUCTURES& ALGORITHMS LAB FEBRUARY 2024

Output:
1 - Enque
2 - Deque
3 - Front element
4 - Empty
5 - Exit
6 - Display
7 - Queue size

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

Result:
Thus the program has been successfully obtained and the output is verified.

21 SACWC
DATA STRUCTURES& ALGORITHMS LAB FEBRUARY 2024

Ex no:05
Binary tree traversals
(inorder, preorder, postorder)

Aim:
To write a program for the binary tree traversals in C.

Algorithm:
1) Start the Program.
2) Type the codings in Turbo C.
3) Define a array stack of size max = 5
4) Display a menu listing stack operations.
5) Use if..else statement to check the conditions.
6) Compile the program filename.cpp.
7) Run the program.
8) Save the program with extension .cpp.
9) Stop the program.

22 SACWC
DATA STRUCTURES& ALGORITHMS LAB FEBRUARY 2024

Source code:
#include <stdio.h>
#include <stdlib.h>

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

/*To create a new node*/


struct node* createNode(int val)
{
struct node* Node = (struct node*)malloc(sizeof(struct node));
Node->element = val;
Node->left = NULL;
Node->right = NULL;

return (Node);
}

/*function to traverse the nodes of binary tree in preorder*/


void traversePreorder(struct node* root)
{
if (root == NULL)
return;
printf(" %d ", root->element);
traversePreorder(root->left);
traversePreorder(root->right);
}

/*function to traverse the nodes of binary tree in Inorder*/


void traverseInorder(struct node* root)
{
if (root == NULL)
return;
traverseInorder(root->left);
printf(" %d ", root->element);
traverseInorder(root->right);
}

23 SACWC
DATA STRUCTURES& ALGORITHMS LAB FEBRUARY 2024

/*function to traverse the nodes of binary tree in postorder*/


void traversePostorder(struct node* root)
{
if (root == NULL)
return;
traversePostorder(root->left);
traversePostorder(root->right);
printf(" %d ", root->element);
}

int main()
{
struct node* root = createNode(36);
root->left = createNode(26);
root->right = createNode(46);
root->left->left = createNode(21);
root->left->right = createNode(31);
root->left->left->left = createNode(11);
root->left->left->right = createNode(24);
root->right->left = createNode(41);
root->right->right = createNode(56);
root->right->right->left = createNode(51);
root->right->right->right = createNode(66);

printf("\n The Preorder traversal of given binary tree is -\n");


traversePreorder(root);

printf("\n The Inorder traversal of given binary tree is -\n");


traverseInorder(root);

printf("\n The Postorder traversal of given binary tree is -\n");


traversePostorder(root);

return 0;
}

24 SACWC
DATA STRUCTURES& ALGORITHMS LAB FEBRUARY 2024

Output:

The Preorder traversal of given binary tree is -

36 26 21 11 24 31 46 41 56 51 66

The Inorder traversal of given binary tree is -

11 21 24 26 31 36 41 46 51 56 66

The Postorder traversal of given binary tree is -

11 24 21 31 26 41 51 66 56 46 36

Result:
Thus the program has been successfully obtained and the output is verified.

25 SACWC
DATA STRUCTURES& ALGORITHMS LAB FEBRUARY 2024

Ex no:06
IMPLEMENTATION of linear search and
binary search

Aim:
To write a program for the implementation of Linear search and Binary search in C.

Algorithm:
1) Start the Program.
2) Type the codings in Turbo C.
3) Read number of array elements n.
4) Define array elements Ai, i = 0,1,2,…n–1.
5) Declare if Ai = search then found = 1.
6) Use if..else statement to check the conditions.
7) Compile the program filename.cpp.
8) Run the program.
9) Save the program with extension .cpp.
10) Stop the program.

26 SACWC
DATA STRUCTURES& ALGORITHMS LAB FEBRUARY 2024

Source code:
Linear search
/* Implementation of linear search */
#include<stdio.h>
int ILS ( int A [ ] , int n , int key )
{
int i ;
for ( i = 0 ; i < n ; i++ )
{
if ( key == A [ i ] )
{
return i ;
}
}
return - 1 ;
}

void main()
{
int A [ 30 ] ;
int key , n , i , x ;
printf ( " Enter size of array : " ) ;
scanf ( "%d" , &n ) ;
printf ( "Enter Array \n " ) ;
for ( i = 0 ; i < n ; i++ )
{
scanf ( "%d" , &A [ i ] ) ;
}
printf ( " Enter value to search : " ) ;
scanf("%d" , &key ) ;
x = ILS ( A , n , key ) ;
if ( x != -1 )
{
printf ( " Value present at index : %d " , x ) ;
}
else
{
printf ( " Value not found ! \n ") ;
}
}

27 SACWC
DATA STRUCTURES& ALGORITHMS LAB FEBRUARY 2024

Output:

Enter the size of an array: 10

Enter Array
12
13
15
8
7
9
6
11
10
4

Enter the value to search: 7

Value present at index: 4

B)binary search

\*Implementation Binary search */


#include<stdio.h>
int IBS ( int A [ ] , int l , int h , int key )
{
int mid ;
while ( l <= h )
{
mid = l + ( h - l ) / 2 ;
if ( A [ mid ] == key )
{
return mid ;
}
if ( A [ mid ] < key )
l = mid + 1 ;
else
h = mid - 1 ;
}
return - 1 ;
}
void main()
{
int A [ 30 ] ;

28 SACWC
DATA STRUCTURES& ALGORITHMS LAB FEBRUARY 2024

int key , l , h , n , i , x ;
printf ( " Enter size of array : " ) ;
scanf ( "%d" , &n ) ;
h=n-1;
l=0;
printf ( " Enter sorted array : \n " ) ;
for ( i = 0 ; i < n ; i++ )
{
scanf ( "%d" , &A [ i ] ) ;
}
printf ( " Enter value to search : " ) ;
scanf ( "%d" , &key ) ;
x = IBS ( A , l , h , key ) ;
if ( x != - 1 )
{
printf ( " Value present at index : %d " , x ) ;
}
else
{
printf ( " Value is not present \n " ) ;
}
}

Output:
Enter the size of an array: 10
Enter Sorted Array
12
13
15
18
20
22
26
30
40
44
Enter the value to search: 20
Value present at index: 4

Result:
Thus the program has been successfully obtained and the output is verified.

29 SACWC
DATA STRUCTURES& ALGORITHMS LAB FEBRUARY 2024

Ex no:07
IMPLEMENTATION insertion sort, quick
sort and merge sort

Aim:
To write a program for the implementation of Insertion sort, Quick sort, Merge sort in C.

Algorithm:
1. Start the program.
2. Read number of array elements n.
3. Read array elements Ai.
4. Outer index i varies from second element to last element.
5. Inner index j is used to compare elements to left of outer index.
6. Divide the array into 3 sequences: elements < x, x, elements >x.
7. Merge the sorted sub-arrays on to a single sorted array.
8. Insert the element into the appropriate position.
9. Display the array elements after each pass.
10. Display the sorted array elements.
11. Stop the program.

30 SACWC
DATA STRUCTURES& ALGORITHMS LAB FEBRUARY 2024

Source code:
Insertion sort
#include <stdio.h>
void insertionSort(int arr[], int n) {
int i, key, j;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;

while (j >= 0 && arr[j] > key) {


arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}

int main() {
int arr[] = { 12, 11, 13, 5, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
insertionSort(arr, n);
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
return 0;
}

Output:

Insertion sort-

5 6 11 12 13

31 SACWC
DATA STRUCTURES& ALGORITHMS LAB FEBRUARY 2024

quick sort

#include <stdio.h>
// Function to swap two elements
void swap(int* a, int* b) {
int t = *a;
*a = *b;
*b = t;
}
int partition(int arr[], int low, int high) {
int pivot = arr[high];
int i = (low - 1);

for (int j = low; j <= high - 1; j++) {


if (arr[j] < pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}
void quickSort(int arr[], int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}

// Function to print the array


void printArray(int arr[], int size) {
int i;
for (i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}

int main() {
int arr[] = { 12, 17, 6, 25, 1, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
quickSort(arr, 0, n - 1);
printf("Sorted array: \n");
printArray(arr, n);
return 0;

32 SACWC
DATA STRUCTURES& ALGORITHMS LAB FEBRUARY 2024

Output:

Quick sorted array:

1 5 6 12 17 25

merge sort
#include <stdio.h>
/* Function to merge the subarrays of a[] */
void merge(int a[], int beg, int mid, int end)
{
int i, j, k;
int n1 = mid - beg + 1;
int n2 = end - mid;

int LeftArray[n1], RightArray[n2]; //temporary arrays

/* copy data to temp arrays */


for (int i = 0; i < n1; i++)
LeftArray[i] = a[beg + i];
for (int j = 0; j < n2; j++)
RightArray[j] = a[mid + 1 + j];

i = 0; /* initial index of first sub-array */


j = 0; /* initial index of second sub-array */
k = beg; /* initial index of merged sub-array */

while (i < n1 && j < n2)


{
if(LeftArray[i] <= RightArray[j])
{
a[k] = LeftArray[i];
i++;
}
else
{
a[k] = RightArray[j];
j++;
}
k++;

33 SACWC
DATA STRUCTURES& ALGORITHMS LAB FEBRUARY 2024

}
while (i<n1)
{
a[k] = LeftArray[i];
i++;
k++;
}

while (j<n2)
{
a[k] = RightArray[j];
j++;
k++;
}
}

void mergeSort(int a[], int beg, int end)


{
if (beg < end)
{
int mid = (beg + end) / 2;
mergeSort(a, beg, mid);
mergeSort(a, mid + 1, end);
merge(a, beg, mid, end);
}
}

/* Function to print the array */


void printArray(int a[], int n)
{
int i;
for (i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\n");
}

int main()
{
int a[] = { 12, 31, 25, 8, 32, 17, 40, 42 };
int n = sizeof(a) / sizeof(a[0]);
printf("Before sorting array elements are - \n");
printArray(a, n);
mergeSort(a, 0, n - 1);
printf("After sorting array elements are - \n");
printArray(a, n);
return 0;
}

34 SACWC
DATA STRUCTURES& ALGORITHMS LAB FEBRUARY 2024

Output:

Before sorting array elements are –

12 31 25 8 32 17 40 42

After sorting array elements are –

8 12 17 25 31 32 40 42

Result:
Thus the program has been successfully obtained and the output is verified.

35 SACWC
DATA STRUCTURES& ALGORITHMS LAB FEBRUARY 2024

Ex no:08
Implementation of DFS &
bfs of graphs

Aim:
To write a program for the implementation of DFS & BFS in C.

Algorithm:
1. Start the Program.
2. Type the codings in Turbo C.
3. Read number of array elements n.
4. Define array elements Ai, i = 0,1,2,…n–1.
5. Use if..else statement to check the conditions.
6. Compile the program filename.cpp.
7. Run the program.
8. Save the program with extension .cpp.
9. Stop the program.

36 SACWC
DATA STRUCTURES& ALGORITHMS LAB FEBRUARY 2024

Source code:
#include<stdio.h>

int q[20],top=-1,front=-1,rear=-1,a[20][20],vis[20],stack[20];
int delete();
void add(int item);
void bfs(int s,int n);
void dfs(int s,int n);
void push(int item);
int pop();

void main()
{
int n,i,s,ch,j;
char c,dummy;
printf("ENTER THE NUMBER VERTICES ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("ENTER 1 IF %d HAS A NODE WITH %d ELSE 0 ",i,j);
scanf("%d",&a[i][j]);
}
}
printf("THE ADJACENCY MATRIX IS\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf(" %d",a[i][j]);
}
printf("\n");
}

do
{
for(i=1;i<=n;i++)
vis[i]=0;
printf("\nMENU");
printf("\n1.B.F.S");
printf("\n2.D.F.S");
printf("\nENTER YOUR CHOICE");
scanf("%d",&ch);
printf("ENTER THE SOURCE VERTEX :");
scanf("%d",&s);

37 SACWC
DATA STRUCTURES& ALGORITHMS LAB FEBRUARY 2024

switch(ch)
{
case 1:bfs(s,n);
break;
case 2:
dfs(s,n);
break;
}
printf("DO U WANT TO CONTINUE(Y/N) ? ");
scanf("%c",&dummy);
scanf("%c",&c);
}while((c=='y')||(c=='Y'));
}

//**************BFS(breadth-first search) code**************//


void bfs(int s,int n)
{
int p,i;
add(s);
vis[s]=1;
p=delete();
if(p!=0)
printf(" %d",p);
while(p!=0)
{
for(i=1;i<=n;i++)
if((a[p][i]!=0)&&(vis[i]==0))
{
add(i);
vis[i]=1;
}
p=delete();
if(p!=0)
printf(" %d ",p);
}
for(i=1;i<=n;i++)
if(vis[i]==0)
bfs(i,n);
}

void add(int item)


{
if(rear==19)
printf("QUEUE FULL");

38 SACWC
DATA STRUCTURES& ALGORITHMS LAB FEBRUARY 2024

else
{
if(rear==-1)
{
q[++rear]=item;
front++;
}
else
q[++rear]=item;
}
}
int delete()
{
int k;
if((front>rear)||(front==-1))
return(0);
else
{
k=q[front++];
return(k);
}
}

//***************DFS(depth-first search) code******************//


void dfs(int s,int n)
{
int i,k;
push(s);
vis[s]=1;
k=pop();
if(k!=0)
printf(" %d ",k);
while(k!=0)
{
for(i=1;i<=n;i++)
if((a[k][i]!=0)&&(vis[i]==0))
{
push(i);
vis[i]=1;
}
k=pop();
if(k!=0)
printf(" %d ",k);
}
for(i=1;i<=n;i++)
if(vis[i]==0)

39 SACWC
DATA STRUCTURES& ALGORITHMS LAB FEBRUARY 2024

dfs(i,n);
}
void push(int item)
{
if(top==19)
printf("Stack overflow ");
else
stack[++top]=item;
}
int pop()
{
int k;
if(top==-1)
return(0);
else
{
k=stack[top--];
return(k);
}
}

40 SACWC
DATA STRUCTURES& ALGORITHMS LAB FEBRUARY 2024

Output:
ENTER THE NUMBER VERTICES 3

ENTER 1 IF 1 HAS A NODE WITH 1 ELSE 0 1


ENTER 1 IF 1 HAS A NODE WITH 2 ELSE 0 1
ENTER 1 IF 1 HAS A NODE WITH 3 ELSE 0 0
ENTER 1 IF 2 HAS A NODE WITH 1 ELSE 0 1
ENTER 1 IF 2 HAS A NODE WITH 2 ELSE 0 0
ENTER 1 IF 2 HAS A NODE WITH 3 ELSE 0 1
ENTER 1 IF 3 HAS A NODE WITH 1 ELSE 0 0
ENTER 1 IF 3 HAS A NODE WITH 2 ELSE 0 1
ENTER 1 IF 3 HAS A NODE WITH 3 ELSE 0 1

THE ADJACENCY MATRIX IS


110
101
011

MENU
1.B.F.S
2.D.F.S

ENTER YOUR CHOICE 1


1

ENTER THE SOURCE VERTEX :2


2 1 3 DO U WANT TO CONTINUE(Y/N) ? y

MENU
1.B.F.S
2.D.F.S

ENTER YOUR CHOICE 2


2

ENTER THE SOURCE VERTEX :1


1 2 3 DO U WANT TO CONTINUE(Y/N) ?

Result:
Thus the program has been successfully obtained and the output is verified.

41 SACWC
DATA STRUCTURES& ALGORITHMS LAB FEBRUARY 2024

Ex no:09
Finding all pairs of shortest path of a
graph

Aim:
To write a program for the implementation finding shortest path of a graph in C.

Algorithm:
1. Start the Program.
2. Type the codings in Turbo C.
3. Read number of array elements n.
4. Define array elements Ai, i = 0,1,2,…n–1.
5. Use if..else statement to check the conditions.
6. Compile the program filename.cpp.
7. Run the program.
8. Save the program with extension .cpp.
9. Stop the program.

42 SACWC
DATA STRUCTURES& ALGORITHMS LAB FEBRUARY 2024

Source code:
/*To find the shortest path between two vertices in a graph
* using the Floyd-Warshall algorithm
*/

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

void floydWarshall(int **graph, int n)


{
int i, j, k;
for (k = 0; k < n; k++)
{
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
if (graph[i][j] > graph[i][k] + graph[k][j])
graph[i][j] = graph[i][k] + graph[k][j];
}
}
}
}

int main(void)
{
int n, i, j;
printf("Enter the number of vertices: ");
scanf("%d", &n);
int **graph = (int **)malloc((long unsigned) n * sizeof(int *));
for (i = 0; i < n; i++)
{
graph[i] = (int *)malloc((long unsigned) n * sizeof(int));
}
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
if (i == j)
graph[i][j] = 0;
else
graph[i][j] = 100;
}
}
printf("Enter the edges: \n");
for (i = 0; i < n; i++)

43 SACWC
DATA STRUCTURES& ALGORITHMS LAB FEBRUARY 2024

{
for (j = 0; j < n; j++)
{
printf("[%d][%d]: ", i, j);
scanf("%d", &graph[i][j]);
}
}
printf("The original graph is:\n");
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
printf("%d ", graph[i][j]);
}
printf("\n");
}
floydWarshall(graph, n);
printf("The shortest path matrix is:\n");
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
printf("%d ", graph[i][j]);
}
printf("\n");
}
return 0;
}

44 SACWC
DATA STRUCTURES& ALGORITHMS LAB FEBRUARY 2024

Output:
Enter the number of vertices: 4

Enter the edges:


[0][0]: 0
[0][1]: 12
[0][2]: 45
[0][3]: 2
[1][0]: 1
[1][1]: 0
[1][2]: 45
[1][3]: 32
[2][0]: 77
[2][1]: 43
[2][2]: 0
[2][3]: 2
[3][0]: 42
[3][1]: 3
[3][2]: 88
[3][3]: 0

The original graph is:


0 12 45 2
1 0 45 32
77 43 0 2
42 3 88 0

The shortest path matrix is:


0 5 45 2
1 0 45 3
6502
4 3 48 0

Result:
Thus the program has been successfully obtained and the output is verified.

45 SACWC
DATA STRUCTURES& ALGORITHMS LAB FEBRUARY 2024

Ex no:10
Finding single source shortest path of a
graph

Aim:
To write a program for single source shortest path a graph in C.

Algorithm:
1. Start the Program.
2. Type the codings in Turbo C.
3. Read number of array elements n.
4. Define array elements Ai, i = 0,1,2,…n–1.
5. Use if..else statement to check the conditions.
6. Compile the program filename.cpp.
7. Run the program.
8. Save the program with extension .cpp.
9. Stop the program.

46 SACWC
DATA STRUCTURES& ALGORITHMS LAB FEBRUARY 2024

Source code:

#include <limits.h>
#include <stdbool.h>
#include <stdio.h>

#define V 9

int minDistance(int dist[], bool sptSet[])


{
int min = INT_MAX, min_index;

for (int v = 0; v < V; v++)


if (sptSet[v] == false && dist[v] <= min)
min = dist[v], min_index = v;

return min_index;
}
void printSolution(int dist[])
{
printf("Vertex \t\t Distance from Source\n");
for (int i = 0; i < V; i++)
printf("%d \t\t\t\t %d\n", i, dist[i]);
}
void dijkstra(int graph[V][V], int src)
{
int dist[V]; // The output array. dist[i] will hold the
bool sptSet[V]; // sptSet[i] will be true if vertex i is
for (int i = 0; i < V; i++)
dist[i] = INT_MAX, sptSet[i] = false;
dist[src] = 0;
for (int count = 0; count < V - 1; count++) {
int u = minDistance(dist, sptSet);
sptSet[u] = true;
for (int v = 0; v < V; v++)
if (!sptSet[v] && graph[u][v]
&& dist[u] != INT_MAX
&& dist[u] + graph[u][v] < dist[v])
dist[v] = dist[u] + graph[u][v];
}
printSolution(dist);
}
int main()
{
int graph[V][V] = { { 0, 4, 0, 0, 0, 0, 0, 8, 0 },
{ 4, 0, 8, 0, 0, 0, 0, 11, 0 },

47 SACWC
DATA STRUCTURES& ALGORITHMS LAB FEBRUARY 2024

{ 0, 8, 0, 7, 0, 4, 0, 0, 2 },
{ 0, 0, 7, 0, 9, 14, 0, 0, 0 },
{ 0, 0, 0, 9, 0, 10, 0, 0, 0 },
{ 0, 0, 4, 14, 10, 0, 2, 0, 0 },
{ 0, 0, 0, 0, 0, 2, 0, 1, 6 },
{ 8, 11, 0, 0, 0, 0, 1, 0, 7 },
{ 0, 0, 2, 0, 0, 0, 6, 7, 0 } };
dijkstra(graph, 0);

return 0;
}

Output:
Vertex Distance from Source

0 0
1 4
2 12
3 19
4 21
5 11
6 9
7 8
8 14

RESULT:
Thus the program has been successfully obtained and the output is verified.

48 SACWC

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy