Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

DSA Practical File

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

A

Practical File
On

Data Structures and Algorithm Lab


Submitted In Partial Fulfilment of the requirements for the award of degree of
Bachelor of Technology
In
Computer Science & Engineering
From

Engineering College Bikaner

Affiliated to

Bikaner Technical University, Bikaner


(Session:2022-2026)

Submitted to
Submitted by: Name: Priyanshu Kumar Dr. Rituraj Soni
University Roll No: 22EEBCS099 Assistant Professor
Department of CSE
DSA Practical File Session 2020-24

Program Specific Outcomes (PSOs):


PSO1: Technological Skill: The ability to understand, analyze and develop computer programs in
the areas related to algorithms, system software, multimedia, web design, big data analytics, and
networking for efficient design of computer-based systems of varying complexity.
PSO2: Strategy Development Skill: The ability to apply standard practices and strategies in
software project development using open-ended programming environments to deliver a quality
product for business success.
PSO3: Research Skill: Be able to route their talents in to post graduate and research programs,
promoting remarkable advancements in emerging areas.
PSO4: Social Enhancement: The ability to apply the knowledge of the technology for social
enhancement and self-improvement.

Course Outcomes (COs)


CO1 Be able to design and analyze the time and space efficiency of the data structure.
CO2 Be capable to identity the appropriate data structure for given problem.
CO3 Have practical knowledge on the applications of data structures.
CO4 To design and implementation of various basic and advanced data structures.

CO5 To introduce various techniques for representation of the data in the real world.

1
DSA Practical File Session 2020-24

INDEX

S. N Name of Practical Date Signature


1. Write an C code for insertion and deletion of element in 1-D Array.
2. Let A and B be two 2D Arrays
a. Write a C Code for adding elements of arrays A and B.
b. Write C Code for subtracting elements of arrays A and B.
c. Write C Code for multiplication of elements of Arrays A and B.
3. Write algorithm and C Program to implement for the following sorting.
Also write the time and space complexity of each algorithm.
a) Bubble Sort
b) Insertion Sort
c) Shell Sort
d) Selection Sort
e) Merge Sort
f) Quick Sort
g) Heap Sort
h) Radix Sort
i) Counting Sort
4. Write a C Code to implement Linear Search in Array.
5. Write a C Code to implement Binary Search in Array.
6. Write a program in C to implement PUSH and POP in stack using
arrays.
7. Write a program in C to implement stack using Linked List.
8. Write a program for factorial calculation and Fibonacci series
calculation using recursion.
9. Write a C program to convert infix expression in postfix and prefix
using stack.
10. Write a C program to evaluate postfix expression using Stack.
11. Write a C Program for insertion and deletion in Linear Queue.
12. Write a C program for insertion and deletion elements in Circular
Queue.
13. Write a program in C to implement Linear Queue using Linked List.
14. Write a C Program to insertion and deletion operation in single linked
List.
15. Write a C Program to insertion and deletion operation in double linked
List.
16. Write a C program for creating, insertion, deletion and searching in
Binary search tree
17. Write a C Program to implement BFS algorithm in Graph.
18. Write a C Program to implement DFS algorithm in Graph.
19. Write a C Program to implement Kruskal Algorithm in Graph.
20. Write a C Program to implement Prims Algorithm in Graph.

2
DSA Practical File Session 2020-24

Program 1: Write an C code for insertion and deletion of element in 1-D Array.

#include <stdio.h>

#define MAX_SIZE 100

void displayArray(int arr[], int size) {


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

int insertElement(int arr[ ], int size, int element, int position) {


if (size >= MAX_SIZE) {
printf("Array is full. Insertion failed.\n");
return size;
}

if (position < 0 || position > size) {


printf("Invalid position for insertion.\n");
return size;
}

for (int i = size; i > position; i--) {


arr[i] = arr[i - 1];
}

arr[position] = element;
return size + 1;
}

int deleteElement(int arr[], int size, int position) {


if (size <= 0) {
printf("Array is empty. Deletion failed.\n");
return size;
}

if (position < 0 || position >= size) {


printf("Invalid position for deletion.\n");
return size;
}

for (int i = position; i < size - 1; i++) {


arr[i] = arr[i + 1];
}

return size - 1;
}

int main() {
int array[MAX_SIZE] = {1, 2, 3, 4, 5};
int size = 5;

3
DSA Practical File Session 2020-24

displayArray(array, size);

// Insertion
size = insertElement(array, size, 10, 2);
displayArray(array, size);

// Deletion
size = deleteElement(array, size, 3);
displayArray(array, size);

return 0;
}

Output:

Array: 1 2 3 4 5
Array: 1 2 10 3 4 5
Array: 1 2 10 4 5

4
DSA Practical File Session 2020-24

Program 2: Let A and B be two 2D Arrays.

a. Write a C Code for adding elements of arrays A and B.

#include <stdio.h>

#define ROWS 3
#define COLS 3

void displayMatrix(int mat[][COLS]) {


printf("Matrix:\n");
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
printf("%d ", mat[i][j]);
}
printf("\n");
}
}

void addMatrices(int a[][COLS], int b[][COLS], int result[][COLS]) {


for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
result[i][j] = a[i][j] + b[i][j];
}
}
}

int main() {
int a[ROWS][COLS] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int b[ROWS][COLS] = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
int result[ROWS][COLS];

printf("Matrix A:\n");
displayMatrix(a);

printf("Matrix B:\n");
displayMatrix(b);

addMatrices(a, b, result);

printf("Sum of Matrices A and B:\n");


displayMatrix(result);

return 0;
}

Output:

Matrix A:
Matrix:
123
456
789
Matrix B:
5
DSA Practical File Session 2020-24

Matrix:
987
654
321
Sum of Matrices A and B:
Matrix:
10 10 10
10 10 10
10 10 10

6
DSA Practical File Session 2020-24

b. Write a C Code for subtracting elements of arrays A and B.

#include <stdio.h>

#define ROWS 3
#define COLS 3

void displayMatrix(int mat[][COLS]) {


printf("Matrix:\n");
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
printf("%d ", mat[i][j]);
}
printf("\n");
}
}

void subtractMatrices(int a[][COLS], int b[][COLS], int result[][COLS]) {


for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
result[i][j] = a[i][j] - b[i][j];
}
}
}

int main() {
int a[ROWS][COLS] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int b[ROWS][COLS] = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
int result[ROWS][COLS];

printf("Matrix A:\n");
displayMatrix(a);

printf("Matrix B:\n");
displayMatrix(b);

subtractMatrices(a, b, result);

printf("Difference of Matrices A and B:\n");


displayMatrix(result);

return 0;
}

Output:

Matrix A:
Matrix:
123
456
789
Matrix B:
Matrix:
987
654
7
DSA Practical File Session 2020-24

321
Difference of Matrices A and B:
Matrix:
-8 -6 -4
-2 0 2
468

8
DSA Practical File Session 2020-24

c. Write a C Code for multiplication of elements of Arrays A and B.

#include <stdio.h>

const int ROWS = 3;


const int COLS = 3; // Adjust the size as needed

void multiplyArrays2D(const int a[][COLS], const int b[][COLS], int result[][COLS], int rows, int cols) {
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
result[i][j] = a[i][j] * b[i][j];
}
}
}

void displayMatrix(const int mat[][COLS], int rows, int cols) {


for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
printf("%d ", mat[i][j]);
}
printf("\n");
}
}

int main() {
int a[ROWS][COLS] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};

int b[ROWS][COLS] = {{10, 11, 12},


{13, 14, 15},
{16, 17, 18}};

int result[ROWS][COLS];

multiplyArrays2D(a, b, result, ROWS, COLS);

printf("Matrix A:\n");
displayMatrix(a, ROWS, COLS);

printf("Matrix B:\n");
displayMatrix(b, ROWS, COLS);

printf("Resultant matrix after multiplication:\n");


displayMatrix(result, ROWS, COLS);

return 0;
}

Output:

Matrix A:
123
456
789
9
DSA Practical File Session 2020-24

Matrix B:
10 11 12
13 14 15
16 17 18
Resultant matrix after multiplication:
10 22 36
52 70 90
112 136 162

10
DSA Practical File Session 2020-24

Program 3: Write algorithm and C program to implement for the following sorting. Also write the time
and space complexity of each algorithm.

a) Bubble Sort

Algorithm:
1. Start from the beginning of the array.
2. Compare each pair of adjacent elements.
3. If they are in the wrong order, swap them.
4. Continue this process until the entire array is sorted.
5. Repeat the process for each element in the array.

#include <stdio.h>

void swap(int *a, int *b) {


int temp = *a;
*a = *b;
*b = temp;
}

void bubbleSort(int arr[], int n) {


for (int i = 0; i < n-1; ++i) {
for (int j = 0; j < n-i-1; ++j) {
if (arr[j] > arr[j+1]) {
swap(&arr[j], &arr[j+1]);
}
}
}
}

int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);

bubbleSort(arr, n);

printf("Sorted array: ");


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

return 0;
}

Output:

Sorted array: 11 12 22 25 34 64 90

Time Complexity:
 Best Case: O(n)
 Average Case: O(n^2)
 Worst Case: O(n^2)
Space Complexity:
 O (1)
11
DSA Practical File Session 2020-24

b) Insertion Sort:

Algorithm:

1. Start from the second element.


2. Compare the current element with the previous elements.
3. If the current element is smaller, shift the larger elements to the right.
4. Insert the current element into its current position.
5. Repeat this process for each element in the array.

#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[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);

insertionSort(arr, n);

printf("Sorted array: ");


for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}

Output:

Sorted array: 11 12 22 25 34 64 90

Time Complexity:
 Best Case: O(n)
 Average Case: O(n^2)
 Worst Case: O(n^2)

Space Complexity:
 O(1)

12
DSA Practical File Session 2020-24

c) Shell Sort

Algorithm:

1. Start with a large gap and reduce it in each iteration.


2. Perform an insertion sort for elements at the current gap.
3. Repeat until the gap becomes 1.

#include <stdio.h>

void shellSort(int arr[], int n) {


for (int gap = n / 2; gap > 0; gap /= 2) {
for (int i = gap; i < n; i += 1) {
int temp = arr[i];
int j;
for (j = i; j >= gap && arr[j - gap] > temp; j -= gap)
arr[j] = arr[j - gap];
arr[j] = temp;
}
}
}

int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);

shellSort(arr, n);

printf("Sorted array: ");


for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}

Output:

Sorted array: 11 12 22 25 34 64 90

Time Complexity:
 Best case: O(n log n)(depends on the gap sequence)
 Average Case: O(n^1.5)
 Worst Case: O(n^2)

Space Complexity:
 O(1)

13
DSA Practical File Session 2020-24

d) Selection Sort:

Algorithm:

1. Find the minimum element in the unsorted part of the array.


2. Swap it with the first element of the unsorted part.
3. Move the boundary between the sorted and unsorted parts.
4. Repeat until the entire array is sorted.

#include <stdio.h>

void swap(int *a, int *b) {


int temp = *a;
*a = *b;
*b = temp;
}

void selectionSort(int arr[], int n) {


int i, j, min_idx;
for (i = 0; i < n-1; i++) {
min_idx = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;

swap(&arr[min_idx], &arr[i]);
}
}

int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);

selectionSort(arr, n);

printf("Sorted array: ");


for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}

Output:

Sorted array: 11 12 22 25 34 64 90

Time Complexity:
 Best Case: O(n^2)
 Average Case: O(n^2)
 Worst Case: O(n^2)

Space Complexity:
 O(1)

14
DSA Practical File Session 2020-24

e) Merge Sort:

Algorithm:

1. Divide the unsorted list into n sub-lists, each containing one element (base case).
2. Repeatedly merge sub-lists to produce new sorted sub-lists until there is only one sub-list remaining.

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

void merge(int arr[], int left, int mid, int right) {


int i, j, k;
int n1 = mid - left + 1;
int n2 = right - mid;

int L[n1], R[n2];

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


L[i] = arr[left + i];
for (j = 0; j < n2; j++)
R[j] = arr[mid + 1 + j];

i = 0;
j = 0;
k = left;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}

while (i < n1) {


arr[k] = L[i];
i++;
k++;
}

while (j < n2) {


arr[k] = R[j];
j++;
k++;
}
}

void mergeSort(int arr[], int left, int right) {


if (left < right) {
int mid = left + (right - left) / 2;

mergeSort(arr, left, mid);


mergeSort(arr, mid + 1, right);
15
DSA Practical File Session 2020-24

merge(arr, left, mid, right);


}
}

int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);

mergeSort(arr, 0, n - 1);

printf("Sorted array: ");


for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}

Output:

Sorted array: 11 12 22 25 34 64 90

Time Complexity:
 Best Case: O(n log n )
 Average Case: O(n log n)
 Worst Case: O(n log n)

Space Complexity:
 O(n) (additional space for temporary arrays during merge)

16
DSA Practical File Session 2020-24

f) Quick Sort:

Algorithm:

1. Choose a pivot element from the array.


2. Partition the array into two sub-arrays, elements less than the pivot and elements greater than the pivot.
3. Recursively apply the quick sort algorithm to the two sub-arrays.

#include <stdio.h>

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

int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);

quickSort(arr, 0, n - 1);

printf("Sorted array: ");


for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}

Output:

Sorted array: 11 12 22 25 34 64 90
17
DSA Practical File Session 2020-24

Time Complexity:
 Best Case: O(n log n)
 Average Case: O(n log n)
 Worst Case: O(n^2) (when the pivot selection is poor)

Space Complexity:

 O(log n) (for the recursive call stack)

18
DSA Practical File Session 2020-24

g) Heap Sort:

Algorithm:

1. Build a max-heap (or min-heap) from the array.


2. Extract the root (which is the maximum element for max-heap and the minimum element for min-heap)
and place it at the end of the sorted array.
3. Repeat the process for the remaining elements in the heap.

#include <stdio.h>

void swap(int* a, int* b) {


int t = *a;
*a = *b;
*b = t;
}

void heapify(int arr[], int n, int i) {


int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;

if (left < n && arr[left] > arr[largest])


largest = left;

if (right < n && arr[right] > arr[largest])


largest = right;

if (largest != i) {
swap(&arr[i], &arr[largest]);
heapify(arr, n, largest);
}
}

void heapSort(int arr[], int n) {


for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);

for (int i = n - 1; i > 0; i--) {


swap(&arr[0], &arr[i]);
heapify(arr, i, 0);
}
}

int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);

heapSort(arr, n);

printf("Sorted array: ");


for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
19
DSA Practical File Session 2020-24

Output:

Sorted array: 11 12 22 25 34 64 90

Time Complexity:

 Best Case: O(n log n)


 Average Case: O(n log n)
 Worst Case: O(n log n)

Space Complexity:

 O(1)

20
DSA Practical File Session 2020-24

h) Radix Sort:

Algorithm:

1. Choose a digit place value (starting from the least significant digit).
2. Sort the array using stable sorting (like counting sort) based on that digit.
3. Repeat the process for each digit place value, moving from the least significant to the most significant.

#include <stdio.h>

// Function to find the maximum number in the array


int getMax(int arr[], int n) {
int max = arr[0];
for (int i = 1; i < n; i++)
if (arr[i] > max)
max = arr[i];
return max;
}

// Using counting sort to sort the elements based on significant places


void countingSort(int arr[], int n, int exp) {
const int RANGE = 10; // 0 to 9
int output[n];
int count[RANGE] = {0};

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


count[(arr[i] / exp) % RANGE]++;

for (int i = 1; i < RANGE; i++)


count[i] += count[i - 1];

for (int i = n - 1; i >= 0; i--) {


output[count[(arr[i] / exp) % RANGE] - 1] = arr[i];
count[(arr[i] / exp) % RANGE]--;
}

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


arr[i] = output[i];
}

void radixSort(int arr[], int n) {


int max = getMax(arr, n);

for (int exp = 1; max / exp > 0; exp *= 10)


countingSort(arr, n, exp);
}

int main() {
int arr[] = {170, 45, 75, 90, 802, 24, 2, 66};
int n = sizeof(arr) / sizeof(arr[0]);

radixSort(arr, n);

printf("Sorted array: ");


for (int i = 0; i < n; i++)
21
DSA Practical File Session 2020-24

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


return 0;
}

Output:

Sorted array: 2 24 45 66 75 90 170 802

Time Complexity:

 Best Case: O(nk) (k is the number of digits in the maximum number)


 Average Case: O(nk)
 Worst Case: O(nk)

Space Complexity:

 O(n +k) (for counting sort)

22
DSA Practical File Session 2020-24

i) Counting Sort:

Algorithm:

1. Count the occurrences of each element in the array.


2. Calculate the cumulative count for each element.
3. Place each element at its correct position in the sorted output array.
4. Update the cout array during the placement to handle duplicates.

#include <stdio.h>

void countingSort(int arr[], int n) {


int max = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > max) {
max = arr[i];
}
}

int count[max + 1];


int output[n];

// Initialize count array with zeros


for (int i = 0; i <= max; i++) {
count[i] = 0;
}

// Count the occurrences of each element


for (int i = 0; i < n; i++) {
count[arr[i]]++;
}

// Calculate the cumulative count


for (int i = 1; i <= max; i++) {
count[i] += count[i - 1];
}

// Place each element at its correct position in the sorted output array
for (int i = n - 1; i >= 0; i--) {
output[count[arr[i]] - 1] = arr[i];
count[arr[i]]--;
}

// Copy the sorted elements back to the original array


for (int i = 0; i < n; i++) {
arr[i] = output[i];
}
}

int main() {
int arr[] = {4, 2, 2, 8, 3, 3, 1};
int n = sizeof(arr) / sizeof(arr[0]);

countingSort(arr, n);

23
DSA Practical File Session 2020-24

printf("Sorted array: ");


for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}

Output:

Sorted array: 1 2 2 3 3 4 8

Time Complexity:

 Best Case: O(n+k) (k is the range of input)


 Average Case: O(n+k)
 Worst Case: O(n+k)

Space Complexity:

 O(n+k)

24
DSA Practical File Session 2020-24

Program 4: Write a C Code to implement Linear Search in Array.

#include <stdio.h>

int linearSearch(int arr[], int size, int target) {


for (int i = 0; i < size; i++) {
if (arr[i] == target) {
return i; // Element found at index i
}
}
return -1; // Element not found
}

int main() {
int array[] = {2, 5, 8, 12, 16, 23, 31, 42, 50};
int size = sizeof(array) / sizeof(array[0]);

int target = 16;


int result = linearSearch(array, size, target);

if (result != -1) {
printf("Element %d found at index %d.\n", target, result);
} else {
printf("Element %d not found in the array.\n", target);
}

return 0;
}

Output:

Element 16 found at index 4.

25
DSA Practical File Session 2020-24

Program 5: Write a C Code to implement Binary Search in Array.

#include <stdio.h>

int binarySearch(int arr[], int size, int target) {


int left = 0;
int right = size - 1;

while (left <= right) {


int mid = left + (right - left) / 2;

if (arr[mid] == target) {
return mid; // Element found at index mid
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}

return -1; // Element not found


}

int main() {
int array[] = {2, 5, 8, 12, 16, 23, 31, 42, 50};
int size = sizeof(array) / sizeof(array[0]);

int target = 16;


int result = binarySearch(array, size, target);

if (result != -1) {
printf("Element %d found at index %d.\n", target, result);
} else {
printf("Element %d not found in the array.\n", target);
}

return 0;
}

Output:

Element 16 found at index 4.

26
DSA Practical File Session 2020-24

Program 6: Write a program in C to implement PUSH and POP in stack using arrays.

#include <stdio.h>

#define MAX_SIZE 10

struct Stack {
int arr[MAX_SIZE];
int top;
};

void initializeStack(struct Stack *stack) {


stack->top = -1;
}

int isFull(struct Stack *stack) {


return stack->top == MAX_SIZE - 1;
}

int isEmpty(struct Stack *stack) {


return stack->top == -1;
}

void push(struct Stack *stack, int value) {


if (isFull(stack)) {
printf("Stack overflow. Cannot push %d.\n", value);
return;
}

stack->arr[++stack->top] = value;
printf("Pushed %d to the stack.\n", value);
}

int pop(struct Stack *stack) {


if (isEmpty(stack)) {
printf("Stack underflow. Cannot pop from an empty stack.\n");
return -1; // indicating an error value
}

int poppedValue = stack->arr[stack->top--];


printf("Popped %d from the stack.\n", poppedValue);
return poppedValue;
}

int main() {
struct Stack stack;
initializeStack(&stack);

push(&stack, 10);
push(&stack, 20);
push(&stack, 30);

pop(&stack);
pop(&stack);
pop(&stack);
27
DSA Practical File Session 2020-24

pop(&stack); // Trying to pop from an empty stack

return 0;
}

Output:

Pushed 10 to the stack.


Pushed 20 to the stack.
Pushed 30 to the stack.
Popped 30 from the stack.
Popped 20 from the stack.
Popped 10 from the stack.
Stack underflow. Cannot pop from an empty stack.

28
DSA Practical File Session 2020-24

Program 7: Write a program in C to implement stack using Linked List.

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

struct Node {
int data;
struct Node* next;
};

struct Stack {
struct Node* top;
};

void initializeStack(struct Stack* stack) {


stack->top = NULL;
}

int isEmpty(struct Stack* stack) {


return stack->top == NULL;
}

void push(struct Stack* stack, int value) {


struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("Memory allocation failed. Cannot push %d.\n", value);
return;
}

newNode->data = value;
newNode->next = stack->top;
stack->top = newNode;

printf("Pushed %d to the stack.\n", value);


}

int pop(struct Stack* stack) {


if (isEmpty(stack)) {
printf("Stack underflow. Cannot pop from an empty stack.\n");
return -1; // indicating an error value
}

struct Node* poppedNode = stack->top;


int poppedValue = poppedNode->data;

stack->top = poppedNode->next;
free(poppedNode);

printf("Popped %d from the stack.\n", poppedValue);


return poppedValue;
}

int main() {
struct Stack stack;
initializeStack(&stack);
29
DSA Practical File Session 2020-24

push(&stack, 10);
push(&stack, 20);
push(&stack, 30);

pop(&stack);
pop(&stack);
pop(&stack);
pop(&stack); // Trying to pop from an empty stack

return 0;
}

Output:

Pushed 10 to the stack.


Pushed 20 to the stack.
Pushed 30 to the stack.
Popped 30 from the stack.
Popped 20 from the stack.
Popped 10 from the stack.
Stack underflow. Cannot pop from an empty stack.

30
DSA Practical File Session 2020-24

Program 8: Write a program for factorial calculation and Fibonacci series calculation using
recursion.

#include <stdio.h>

// Function to calculate factorial using recursion


int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}

// Function to generate Fibonacci series using recursion


int fibonacci(int n) {
if (n <= 1) {
return n;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}

int main() {
// Calculate factorial
int num_factorial = 5;
printf("Factorial of %d is: %d\n", num_factorial, factorial(num_factorial));

// Generate Fibonacci series


int num_fibonacci = 6;
printf("Fibonacci series up to %d terms:\n", num_fibonacci);
for (int i = 0; i < num_fibonacci; i++) {
printf("%d ", fibonacci(i));
}
printf("\n");

return 0;
}

Output:

Factorial of 5 is: 120.


Fibonacci series up to 6 terms:
011235

31
DSA Practical File Session 2020-24

Program 9: Write a C program to convert infix expression in postfix and prefix using stack.

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

#define MAX_SIZE 100

struct Stack {
int top;
char arr[MAX_SIZE];
};

void initializeStack(struct Stack* stack) {


stack->top = -1;
}

int isEmpty(struct Stack* stack) {


return stack->top == -1;
}

int isFull(struct Stack* stack) {


return stack->top == MAX_SIZE - 1;
}

void push(struct Stack* stack, char value) {


if (isFull(stack)) {
printf("Stack overflow. Cannot push %c.\n", value);
return;
}

stack->arr[++stack->top] = value;
}

char pop(struct Stack* stack) {


if (isEmpty(stack)) {
printf("Stack underflow. Cannot pop from an empty stack.\n");
return '\0'; // indicating an error value
}

return stack->arr[stack->top--];
}

int isOperator(char ch) {


return (ch == '+' || ch == '-' || ch == '*' || ch == '/');
}

int getPrecedence(char ch) {


if (ch == '+' || ch == '-')
return 1;
else if (ch == '*' || ch == '/')
return 2;
else
return 0; // For non-operators
}
32
DSA Practical File Session 2020-24

void infixToPostfix(char infix[], char postfix[]) {


struct Stack stack;
initializeStack(&stack);

int i, j;
i = j = 0;

while (infix[i] != '\0') {


if (infix[i] >= 'A' && infix[i] <= 'Z' || infix[i] >= 'a' && infix[i] <= 'z' || infix[i] >= '0' && infix[i] <= '9') {
postfix[j++] = infix[i++];
} else if (infix[i] == '(') {
push(&stack, infix[i++]);
} else if (infix[i] == ')') {
while (!isEmpty(&stack) && stack.arr[stack.top] != '(') {
postfix[j++] = pop(&stack);
}
if (!isEmpty(&stack) && stack.arr[stack.top] != '(')
printf("Invalid infix expression.\n");
else
pop(&stack);
i++;
} else {
while (!isEmpty(&stack) && getPrecedence(infix[i]) <= getPrecedence(stack.arr[stack.top])) {
postfix[j++] = pop(&stack);
}
push(&stack, infix[i++]);
}
}

while (!isEmpty(&stack)) {
postfix[j++] = pop(&stack);
}

postfix[j] = '\0';
}

void infixToPrefix(char infix[], char prefix[]) {


// Reverse the infix expression, get the postfix, and then reverse it again
char reversedInfix[MAX_SIZE];
int len = strlen(infix);

for (int i = 0; i < len; i++) {


reversedInfix[i] = infix[len - 1 - i];
}
reversedInfix[len] = '\0';

char reversedPostfix[MAX_SIZE];
infixToPostfix(reversedInfix, reversedPostfix);

int j = 0;
for (int i = strlen(reversedPostfix) - 1; i >= 0; i--) {
prefix[j++] = reversedPostfix[i];
}

prefix[j] = '\0';
33
DSA Practical File Session 2020-24

int main() {
char infix[MAX_SIZE], postfix[MAX_SIZE], prefix[MAX_SIZE];

printf("Enter the infix expression: ");


gets(infix);

infixToPostfix(infix, postfix);
printf("Postfix expression: %s\n", postfix);

infixToPrefix(infix, prefix);
printf("Prefix expression: %s\n", prefix);

return 0;
}

Output:

Enter the infix expression: a+b*c


Postfix expression: abc*+
Prefix expression: +a*bc

34
DSA Practical File Session 2020-24

Program 10: Write a C program to evaluate postfix expression using Stack.

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

#define MAX_SIZE 100

struct Stack {
int top;
int arr[MAX_SIZE];
};

void initializeStack(struct Stack* stack) {


stack->top = -1;
}

int isEmpty(struct Stack* stack) {


return stack->top == -1;
}

int isFull(struct Stack* stack) {


return stack->top == MAX_SIZE - 1;
}

void push(struct Stack* stack, int value) {


if (isFull(stack)) {
printf("Stack overflow. Cannot push %d.\n", value);
return;
}

stack->arr[++stack->top] = value;
}

int pop(struct Stack* stack) {


if (isEmpty(stack)) {
printf("Stack underflow. Cannot pop from an empty stack.\n");
return -1; // indicating an error value
}

return stack->arr[stack->top--];
}

int evaluatePostfix(char postfix[]) {


struct Stack stack;
initializeStack(&stack);

int len = strlen(postfix);

for (int i = 0; i < len; i++) {


if (isdigit(postfix[i])) {
push(&stack, postfix[i] - '0');
} else {
int operand2 = pop(&stack);
35
DSA Practical File Session 2020-24

int operand1 = pop(&stack);

switch (postfix[i]) {
case '+':
push(&stack, operand1 + operand2);
break;
case '-':
push(&stack, operand1 - operand2);
break;
case '*':
push(&stack, operand1 * operand2);
break;
case '/':
if (operand2 != 0) {
push(&stack, operand1 / operand2);
} else {
printf("Error: Division by zero.\n");
exit(EXIT_FAILURE);
}
break;
default:
printf("Invalid postfix expression.\n");
exit(EXIT_FAILURE);
}
}
}

return pop(&stack);
}

int main() {
char postfix[MAX_SIZE];

printf("Enter the postfix expression: ");


gets(postfix);

int result = evaluatePostfix(postfix);


printf("Result of postfix expression: %d\n", result);

return 0;
}

Output:

Enter the postfix expression: 245+*


Result of postfix expression: 18

36
DSA Practical File Session 2020-24

Program 11: Write a C Program for insertion and deletion in Linear Queue.

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

#define MAX_SIZE 5

struct Queue {
int front, rear;
int arr[MAX_SIZE];
};

void initializeQueue(struct Queue* queue) {


queue->front = -1;
queue->rear = -1;
}

int isFull(struct Queue* queue) {


return (queue->rear == MAX_SIZE - 1 && queue->front == 0) || (queue->rear + 1 == queue->front);
}

int isEmpty(struct Queue* queue) {


return queue->front == -1;
}

void enqueue(struct Queue* queue, int value) {


if (isFull(queue)) {
printf("Queue is full. Cannot enqueue %d.\n", value);
return;
}

if (isEmpty(queue)) {
queue->front = 0;
queue->rear = 0;
} else {
queue->rear = (queue->rear + 1) % MAX_SIZE;
}

queue->arr[queue->rear] = value;
printf("Enqueued %d to the queue.\n", value);
}

int dequeue(struct Queue* queue) {


if (isEmpty(queue)) {
printf("Queue is empty. Cannot dequeue.\n");
return -1; // indicating an error value
}

int dequeuedValue = queue->arr[queue->front];

if (queue->front == queue->rear) {
// Last element in the queue
initializeQueue(queue);
} else {
queue->front = (queue->front + 1) % MAX_SIZE;
37
DSA Practical File Session 2020-24

printf("Dequeued %d from the queue.\n", dequeuedValue);


return dequeuedValue;
}

void displayQueue(struct Queue* queue) {


if (isEmpty(queue)) {
printf("Queue is empty.\n");
return;
}

printf("Queue: ");
int i = queue->front;
while (i != queue->rear) {
printf("%d ", queue->arr[i]);
i = (i + 1) % MAX_SIZE;
}
printf("%d\n", queue->arr[queue->rear]);
}

int main() {
struct Queue queue;
initializeQueue(&queue);

enqueue(&queue, 10);
enqueue(&queue, 20);
enqueue(&queue, 30);

displayQueue(&queue);

dequeue(&queue);
dequeue(&queue);
dequeue(&queue);
dequeue(&queue); // Trying to dequeue from an empty queue

return 0;
}

Output:

Enqueued 20 to the queue.


Enqueued 30 to the queue.
Queue: 10 20 30
Dequeued 10 from the queue.
Dequeued 20 from the queue.
Dequeued 30 from the queue.
Queue is empty. Cannot dequeue.

38
DSA Practical File Session 2020-24

Program 12: Write a C program for insertion and deletion elements in Circular Queue.

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

#define MAX_SIZE 5

struct CircularQueue {
int front, rear;
int arr[MAX_SIZE];
};

void initializeCircularQueue(struct CircularQueue* queue) {


queue->front = -1;
queue->rear = -1;
}

int isFull(struct CircularQueue* queue) {


return (queue->front == 0 && queue->rear == MAX_SIZE - 1) || (queue->rear + 1 == queue->front);
}

int isEmpty(struct CircularQueue* queue) {


return queue->front == -1;
}

void enqueue(struct CircularQueue* queue, int value) {


if (isFull(queue)) {
printf("Queue is full. Cannot enqueue %d.\n", value);
return;
}

if (isEmpty(queue)) {
queue->front = 0;
queue->rear = 0;
} else {
queue->rear = (queue->rear + 1) % MAX_SIZE;
}

queue->arr[queue->rear] = value;
printf("Enqueued %d to the circular queue.\n", value);
}

int dequeue(struct CircularQueue* queue) {


if (isEmpty(queue)) {
printf("Queue is empty. Cannot dequeue.\n");
return -1; // indicating an error value
}

int dequeuedValue = queue->arr[queue->front];

if (queue->front == queue->rear) {
// Last element in the queue
initializeCircularQueue(queue);
} else {
queue->front = (queue->front + 1) % MAX_SIZE;
39
DSA Practical File Session 2020-24

printf("Dequeued %d from the circular queue.\n", dequeuedValue);


return dequeuedValue;
}

void displayCircularQueue(struct CircularQueue* queue) {


if (isEmpty(queue)) {
printf("Circular queue is empty.\n");
return;
}

printf("Circular Queue: ");


int i = queue->front;
do {
printf("%d ", queue->arr[i]);
i = (i + 1) % MAX_SIZE;
} while (i != (queue->rear + 1) % MAX_SIZE);
printf("\n");
}

int main() {
struct CircularQueue cQueue;
initializeCircularQueue(&cQueue);

enqueue(&cQueue, 10);
enqueue(&cQueue, 20);
enqueue(&cQueue, 30);

displayCircularQueue(&cQueue);

dequeue(&cQueue);
dequeue(&cQueue);
dequeue(&cQueue);
dequeue(&cQueue); // Trying to dequeue from an empty circular queue

return 0;
}

Output:

Enqueued 10 to the circular queue.


Enqueued 20 to the circular queue.
Enqueued 30 to the circular queue.
Circular Queue: 10 20 30
Dequeued 10 from the circular queue.
Dequeued 20 from the circular queue.
Dequeued 30 from the circular queue.
Queue is empty. Cannot dequeue.

40
DSA Practical File Session 2020-24

Program 13: Write a program in C to implement Linear Queue using Linked List.

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

struct Node {
int data;
struct Node* next;
};

struct Queue {
struct Node* front;
struct Node* rear;
};

void initializeQueue(struct Queue* queue) {


queue->front = NULL;
queue->rear = NULL;
}

int isEmpty(struct Queue* queue) {


return queue->front == NULL;
}

void enqueue(struct Queue* queue, int value) {


struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("Memory allocation failed. Cannot enqueue %d.\n", value);
return;
}

newNode->data = value;
newNode->next = NULL;

if (isEmpty(queue)) {
queue->front = newNode;
queue->rear = newNode;
} else {
queue->rear->next = newNode;
queue->rear = newNode;
}

printf("Enqueued %d to the queue.\n", value);


}

int dequeue(struct Queue* queue) {


if (isEmpty(queue)) {
printf("Queue is empty. Cannot dequeue.\n");
return -1; // indicating an error value
}

struct Node* frontNode = queue->front;


int dequeuedValue = frontNode->data;

if (queue->front == queue->rear) {
41
DSA Practical File Session 2020-24

// Last element in the queue


initializeQueue(queue);
} else {
queue->front = frontNode->next;
}

free(frontNode);
printf("Dequeued %d from the queue.\n", dequeuedValue);
return dequeuedValue;
}

void displayQueue(struct Queue* queue) {


if (isEmpty(queue)) {
printf("Queue is empty.\n");
return;
}

printf("Queue: ");
struct Node* current = queue->front;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}

int main() {
struct Queue queue;
initializeQueue(&queue);

enqueue(&queue, 10);
enqueue(&queue, 20);
enqueue(&queue, 30);

displayQueue(&queue);

dequeue(&queue);
dequeue(&queue);
dequeue(&queue);
dequeue(&queue); // Trying to dequeue from an empty queue

return 0;
}

Output:

Enqueued 10 to the queue.


Enqueued 20 to the queue.
Enqueued 30 to the queue.
Queue: 10 20 30
Dequeued 10 from the queue.
Dequeued 20 from the queue.
Dequeued 30 from the queue.
Queue is empty. Cannot dequeue.

42
DSA Practical File Session 2020-24

Program 14: Write a C Program to insertion and deletion operation in single linked List.

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

struct Node {
int data;
struct Node* next;
};

// Function to create a new node


struct Node* createNode(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("Memory allocation failed.\n");
exit(EXIT_FAILURE);
}
newNode->data = value;
newNode->next = NULL;
return newNode;
}

// Function to insert a node at the end of the linked list


void insertAtEnd(struct Node** head, int value) {
struct Node* newNode = createNode(value);

if (*head == NULL) {
*head = newNode;
} else {
struct Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}

printf("Inserted %d at the end of the linked list.\n", value);


}

// Function to delete a node with a given value from the linked list
void deleteNode(struct Node** head, int value) {
if (*head == NULL) {
printf("Linked list is empty. Cannot delete.\n");
return;
}

struct Node* current = *head;


struct Node* prev = NULL;

while (current != NULL && current->data != value) {


prev = current;
current = current->next;
}

if (current == NULL) {
43
DSA Practical File Session 2020-24

printf("Value %d not found in the linked list. Cannot delete.\n", value);


return;
}

if (prev == NULL) {
// Deleting the first node
*head = current->next;
} else {
prev->next = current->next;
}

free(current);
printf("Deleted node with value %d from the linked list.\n", value);
}

// Function to display the linked list


void displayLinkedList(struct Node* head) {
printf("Linked List: ");
struct Node* current = head;
while (current != NULL) {
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL\n");
}

int main() {
struct Node* head = NULL;

insertAtEnd(&head, 10);
insertAtEnd(&head, 20);
insertAtEnd(&head, 30);

displayLinkedList(head);

deleteNode(&head, 20);
displayLinkedList(head);

deleteNode(&head, 40); // Trying to delete a non-existent node


displayLinkedList(head);

return 0;
}

Output:

Inserted 10 at the end of the linked list.


Inserted 20 at the end of the linked list.
Inserted 30 at the end of the linked list.
Linked List: 10 -> 20 -> 30 -> NULL
Deleted node with value 20 from the linked list.
Linked List: 10 -> 30 -> NULL
Value 40 not found in the linked list. Cannot delete.
Linked List: 10 -> 30 -> NULL

44
DSA Practical File Session 2020-24

Program 15: Write a C Program to insertion and deletion operation in double linked List.

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

struct Node {
int data;
struct Node* prev;
struct Node* next;
};

// Function to create a new node


struct Node* createNode(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("Memory allocation failed.\n");
exit(EXIT_FAILURE);
}
newNode->data = value;
newNode->prev = NULL;
newNode->next = NULL;
return newNode;
}

// Function to insert a node at the end of the doubly linked list


void insertAtEnd(struct Node** head, int value) {
struct Node* newNode = createNode(value);

if (*head == NULL) {
*head = newNode;
} else {
struct Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
newNode->prev = current;
}

printf("Inserted %d at the end of the doubly linked list.\n", value);


}

// Function to delete a node with a given value from the doubly linked list
void deleteNode(struct Node** head, int value) {
if (*head == NULL) {
printf("Doubly linked list is empty. Cannot delete.\n");
return;
}

struct Node* current = *head;

while (current != NULL && current->data != value) {


current = current->next;
}

45
DSA Practical File Session 2020-24

if (current == NULL) {
printf("Value %d not found in the doubly linked list. Cannot delete.\n", value);
return;
}

if (current->prev != NULL) {
current->prev->next = current->next;
} else {
// Deleting the first node
*head = current->next;
}

if (current->next != NULL) {
current->next->prev = current->prev;
}

free(current);
printf("Deleted node with value %d from the doubly linked list.\n", value);
}

// Function to display the doubly linked list in both forward and reverse order
void displayDoublyLinkedList(struct Node* head) {
printf("Doubly Linked List (Forward): ");
struct Node* current = head;
while (current != NULL) {
printf("%d <-> ", current->data);
current = current->next;
}
printf("NULL\n");

printf("Doubly Linked List (Reverse): ");


current = head;
while (current != NULL && current->next != NULL) {
current = current->next;
}
while (current != NULL) {
printf("%d <-> ", current->data);
current = current->prev;
}
printf("NULL\n");
}

int main() {
struct Node* head = NULL;

insertAtEnd(&head, 10);
insertAtEnd(&head, 20);
insertAtEnd(&head, 30);

displayDoublyLinkedList(head);

deleteNode(&head, 20);
displayDoublyLinkedList(head);

deleteNode(&head, 40); // Trying to delete a non-existent node


displayDoublyLinkedList(head);
46
DSA Practical File Session 2020-24

return 0;
}

Output:

Inserted 10 at the end of the doubly linked list.


Inserted 20 at the end of the doubly linked list.
Inserted 30 at the end of the doubly linked list.
Doubly Linked List (Forward): 10 <-> 20 <-> 30 <-> NULL
Doubly Linked List (Reverse): 30 <-> 20 <-> 10 <-> NULL
Deleted node with value 20 from the doubly linked list.
Doubly Linked List (Forward): 10 <-> 30 <-> NULL
Doubly Linked List (Reverse): 30 <-> 10 <-> NULL
Value 40 not found in the doubly linked list. Cannot delete.
Doubly Linked List (Forward): 10 <-> 30 <-> NULL
Doubly Linked List (Reverse): 30 <-> 10 <-> NULL

47
DSA Practical File Session 2020-24

Program 16: Write a C program for creating, insertion, deletion and searching in
Binary search tree

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

struct Node {
int data;
struct Node* left;
struct Node* right;
};

// Function to create a new node


struct Node* createNode(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("Memory allocation failed.\n");
exit(EXIT_FAILURE);
}
newNode->data = value;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}

// Function to insert a value into the binary search tree


struct Node* insert(struct Node* root, int value) {
if (root == NULL) {
return createNode(value);
}

if (value < root->data) {


root->left = insert(root->left, value);
} else if (value > root->data) {
root->right = insert(root->right, value);
}

return root;
}

// Function to find the minimum value node in a BST


struct Node* findMin(struct Node* root) {
while (root->left != NULL) {
root = root->left;
}
return root;
}

// Function to delete a value from the binary search tree


struct Node* deleteNode(struct Node* root, int value) {
if (root == NULL) {
return root;
}

if (value < root->data) {


48
DSA Practical File Session 2020-24

root->left = deleteNode(root->left, value);


} else if (value > root->data) {
root->right = deleteNode(root->right, value);
} else {
// Node with one child or no child
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;
}

// Node with two children


struct Node* temp = findMin(root->right);
root->data = temp->data;
root->right = deleteNode(root->right, temp->data);
}

return root;
}

// Function to search for a value in the binary search tree


struct Node* search(struct Node* root, int value) {
if (root == NULL || root->data == value) {
return root;
}

if (value < root->data) {


return search(root->left, value);
}

return search(root->right, value);


}

// Function to display the binary search tree (inorder traversal)


void displayBST(struct Node* root) {
if (root != NULL) {
displayBST(root->left);
printf("%d ", root->data);
displayBST(root->right);
}
}

int main() {
struct Node* root = NULL;

// Insert values into the BST


root = insert(root, 50);
insert(root, 30);
insert(root, 20);
insert(root, 40);
insert(root, 70);
insert(root, 60);
49
DSA Practical File Session 2020-24

insert(root, 80);

// Display the initial BST


printf("Binary Search Tree (Inorder): ");
displayBST(root);
printf("\n");

// Search for a value in the BST


int searchValue = 40;
struct Node* searchResult = search(root, searchValue);
if (searchResult != NULL) {
printf("Value %d found in the BST.\n", searchValue);
} else {
printf("Value %d not found in the BST.\n", searchValue);
}

// Delete a value from the BST


int deleteValue = 30;
root = deleteNode(root, deleteValue);

// Display the updated BST


printf("Binary Search Tree after deleting %d (Inorder): ", deleteValue);
displayBST(root);
printf("\n");

return 0;
}

Output:

Binary Search Tree (Inorder): 20 30 40 50 60 70 80


Value 40 found in the BST.
Binary Search Tree after deleting 30 (Inorder): 20 40 50 60 70 80

50
DSA Practical File Session 2020-24

Program 17: Write a C Program to implement BFS algorithm in Graph.

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

// Structure to represent a node in the graph


struct Node {
int data;
struct Node* next;
};

// Structure to represent the graph


struct Graph {
int vertices;
struct Node** adjacencyList;
int* visited;
};

// Function to create a new node in the graph


struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("Memory allocation failed.\n");
exit(EXIT_FAILURE);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}

// Function to create a graph with a given number of vertices


struct Graph* createGraph(int vertices) {
struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));
if (graph == NULL) {
printf("Memory allocation failed.\n");
exit(EXIT_FAILURE);
}
graph->vertices = vertices;
graph->adjacencyList = (struct Node**)malloc(vertices * sizeof(struct Node*));
graph->visited = (int*)malloc(vertices * sizeof(int));

if (graph->adjacencyList == NULL || graph->visited == NULL) {


printf("Memory allocation failed.\n");
exit(EXIT_FAILURE);
}

for (int i = 0; i < vertices; i++) {


graph->adjacencyList[i] = NULL;
graph->visited[i] = 0; // Mark all vertices as not visited
}

return graph;
}

// Function to add an edge to the graph


void addEdge(struct Graph* graph, int src, int dest) {
51
DSA Practical File Session 2020-24

// Add edge from source to destination


struct Node* newNode = createNode(dest);
newNode->next = graph->adjacencyList[src];
graph->adjacencyList[src] = newNode;

// Add edge from destination to source (for undirected graph)


newNode = createNode(src);
newNode->next = graph->adjacencyList[dest];
graph->adjacencyList[dest] = newNode;
}

// Function to perform Breadth-First Search (BFS) in the graph


void BFS(struct Graph* graph, int startVertex) {
// Create a queue for BFS
int* queue = (int*)malloc(graph->vertices * sizeof(int));
int front = 0, rear = 0;

// Mark the start vertex as visited and enqueue it


graph->visited[startVertex] = 1;
queue[rear++] = startVertex;

while (front < rear) {


// Dequeue a vertex from the queue
int currentVertex = queue[front++];
printf("%d ", currentVertex);

// Explore adjacent vertices


struct Node* temp = graph->adjacencyList[currentVertex];
while (temp != NULL) {
int adjacentVertex = temp->data;
if (!graph->visited[adjacentVertex]) {
// Mark the adjacent vertex as visited and enqueue it
graph->visited[adjacentVertex] = 1;
queue[rear++] = adjacentVertex;
}
temp = temp->next;
}
}

// Free the memory allocated for the queue


free(queue);
}

int main() {
// Create a sample graph
struct Graph* graph = createGraph(6);
addEdge(graph, 0, 1);
addEdge(graph, 0, 2);
addEdge(graph, 1, 3);
addEdge(graph, 1, 4);
addEdge(graph, 2, 4);
addEdge(graph, 3, 5);
addEdge(graph, 4, 5);

printf("Breadth-First Search (BFS) starting from vertex 0:\n");


BFS(graph, 0);
52
DSA Practical File Session 2020-24

// Free the memory allocated for the graph


free(graph->adjacencyList);
free(graph->visited);
free(graph);

return 0;
}

Output:

Breadth-First Search (BFS) starting from vertex 0:


021435

53
DSA Practical File Session 2020-24

Program 18: Write a C Program to implement DFS algorithm in Graph.

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

// Structure to represent a node in the graph


struct Node {
int data;
struct Node* next;
};

// Structure to represent the graph


struct Graph {
int vertices;
struct Node** adjacencyList;
int* visited;
};

// Function to create a new node in the graph


struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("Memory allocation failed.\n");
exit(EXIT_FAILURE);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}

// Function to create a graph with a given number of vertices


struct Graph* createGraph(int vertices) {
struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));
if (graph == NULL) {
printf("Memory allocation failed.\n");
exit(EXIT_FAILURE);
}
graph->vertices = vertices;
graph->adjacencyList = (struct Node**)malloc(vertices * sizeof(struct Node*));
graph->visited = (int*)malloc(vertices * sizeof(int));

if (graph->adjacencyList == NULL || graph->visited == NULL) {


printf("Memory allocation failed.\n");
exit(EXIT_FAILURE);
}

for (int i = 0; i < vertices; i++) {


graph->adjacencyList[i] = NULL;
graph->visited[i] = 0; // Mark all vertices as not visited
}

return graph;
}

// Function to add an edge to the graph


54
DSA Practical File Session 2020-24

void addEdge(struct Graph* graph, int src, int dest) {


// Add edge from source to destination
struct Node* newNode = createNode(dest);
newNode->next = graph->adjacencyList[src];
graph->adjacencyList[src] = newNode;

// Add edge from destination to source (for undirected graph)


newNode = createNode(src);
newNode->next = graph->adjacencyList[dest];
graph->adjacencyList[dest] = newNode;
}

// Function to perform Depth-First Search (DFS) in the graph


void DFS(struct Graph* graph, int startVertex) {
if (graph->visited[startVertex]) {
return;
}

// Mark the current vertex as visited and print it


graph->visited[startVertex] = 1;
printf("%d ", startVertex);

// Recur for all the adjacent vertices


struct Node* temp = graph->adjacencyList[startVertex];
while (temp != NULL) {
int adjacentVertex = temp->data;
if (!graph->visited[adjacentVertex]) {
DFS(graph, adjacentVertex);
}
temp = temp->next;
}
}

int main() {
// Create a sample graph
struct Graph* graph = createGraph(6);
addEdge(graph, 0, 1);
addEdge(graph, 0, 2);
addEdge(graph, 1, 3);
addEdge(graph, 1, 4);
addEdge(graph, 2, 4);
addEdge(graph, 3, 5);
addEdge(graph, 4, 5);

printf("Depth-First Search (DFS) starting from vertex 0:\n");


DFS(graph, 0);

// Free the memory allocated for the graph


free(graph->adjacencyList);
free(graph->visited);
free(graph);

return 0;
}

55
DSA Practical File Session 2020-24

Output:

Depth-First Search (DFS) starting from vertex 0:


024531

56
DSA Practical File Session 2020-24

Program 19: Write a C Program to implement Kruskal Algorithm in Graph.

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

// Structure to represent an edge in the graph


struct Edge {
int src, dest, weight;
};

// Structure to represent a subset for union-find


struct Subset {
int parent;
int rank;
};

// Function to create a new subset


struct Subset* createSubset(int parent, int rank) {
struct Subset* subset = (struct Subset*)malloc(sizeof(struct Subset));
if (subset == NULL) {
printf("Memory allocation failed.\n");
exit(EXIT_FAILURE);
}
subset->parent = parent;
subset->rank = rank;
return subset;
}

// Function to find the set of an element using the path compression technique
int findSet(struct Subset* subsets, int i) {
if (subsets[i].parent != i) {
subsets[i].parent = findSet(subsets, subsets[i].parent); // Path compression
}
return subsets[i].parent;
}

// Function to perform union of two sets using the rank heuristic


void unionSets(struct Subset* subsets, int x, int y) {
int rootX = findSet(subsets, x);
int rootY = findSet(subsets, y);

if (subsets[rootX].rank < subsets[rootY].rank) {


subsets[rootX].parent = rootY;
} else if (subsets[rootX].rank > subsets[rootY].rank) {
subsets[rootY].parent = rootX;
} else {
subsets[rootX].parent = rootY;
subsets[rootY].rank++;
}
}

// Comparator function for sorting edges based on their weights


int compareEdges(const void* a, const void* b) {
return ((struct Edge*)a)->weight - ((struct Edge*)b)->weight;
}
57
DSA Practical File Session 2020-24

// Function to perform Kruskal's algorithm to find the minimum spanning tree


void kruskal(struct Edge* edges, int numVertices, int numEdges) {
// Sort the edges in non-decreasing order of their weights
qsort(edges, numEdges, sizeof(struct Edge), compareEdges);

// Allocate memory for subsets


struct Subset* subsets = (struct Subset*)malloc(numVertices * sizeof(struct Subset));
if (subsets == NULL) {
printf("Memory allocation failed.\n");
exit(EXIT_FAILURE);
}

// Create subsets with single elements and initialize their ranks


for (int i = 0; i < numVertices; i++) {
subsets[i] = *createSubset(i, 0);
}

int mstWeight = 0; // Weight of the minimum spanning tree

printf("Minimum Spanning Tree edges:\n");

for (int i = 0; i < numEdges; i++) {


int rootX = findSet(subsets, edges[i].src);
int rootY = findSet(subsets, edges[i].dest);

// Check if including this edge forms a cycle in the MST


if (rootX != rootY) {
printf("(%d - %d) Weight: %d\n", edges[i].src, edges[i].dest, edges[i].weight);
mstWeight += edges[i].weight;
unionSets(subsets, rootX, rootY);
}
}

printf("Total weight of the Minimum Spanning Tree: %d\n", mstWeight);

// Free the allocated memory


free(subsets);
}

int main() {
// Example graph represented by its edges
int numVertices = 6;
int numEdges = 9;
struct Edge edges[] = {
{0, 1, 4},
{0, 2, 4},
{1, 2, 2},
{1, 0, 4},
{2, 0, 4},
{2, 1, 2},
{2, 3, 3},
{2, 5, 2},
{3, 2, 3},
};

58
DSA Practical File Session 2020-24

// Perform Kruskal's algorithm


kruskal(edges, numVertices, numEdges);

return 0;
}

Output:

Minimum Spanning Tree edges:


(1 - 2) Weight: 2
(2 - 5) Weight: 2
(2 - 3) Weight: 3
(0 - 1) Weight: 4
Total weight of the Minimum Spanning Tree: 11

59
DSA Practical File Session 2020-24

Program 20: Write a C Program to implement Prims Algorithm in Graph.

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

// Number of vertices in the graph


#define V 6

// Function to find the vertex with the minimum key value


int minKey(int key[], int mstSet[]) {
int min = INT_MAX, min_index;

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


if (!mstSet[v] && key[v] < min) {
min = key[v];
min_index = v;
}
}

return min_index;
}

// Function to print the constructed MST stored in parent[]


void printMST(int parent[], int graph[V][V]) {
printf("Edge Weight\n");
for (int i = 1; i < V; i++) {
printf("%d - %d %d \n", parent[i], i, graph[i][parent[i]]);
}
}

// Function to implement Prim's algorithm for a given graph


void primMST(int graph[V][V]) {
int parent[V]; // Array to store the constructed MST
int key[V]; // Key values used to pick the minimum weight edge
int mstSet[V]; // To represent set of vertices included in MST

// Initialize all keys as INFINITE


for (int i = 0; i < V; i++) {
key[i] = INT_MAX;
mstSet[i] = 0;
}

// Always include the first vertex in MST


key[0] = 0;
parent[0] = -1; // First node is always the root of MST

// The MST will have V-1 edges


for (int count = 0; count < V - 1; count++) {
// Pick the minimum key vertex from the set of vertices not yet included in MST
int u = minKey(key, mstSet);

// Add the picked vertex to the MST set


mstSet[u] = 1;

60
DSA Practical File Session 2020-24

// Update key value and parent index of the adjacent vertices


for (int v = 0; v < V; v++) {
// Update key[v] only if the v is not yet included in MST,
// there is an edge from u to v, and the weight of the edge is less than key[v]
if (graph[u][v] && !mstSet[v] && graph[u][v] < key[v]) {
parent[v] = u;
key[v] = graph[u][v];
}
}
}

// Print the constructed MST


printMST(parent, graph);
}

int main() {
// Example graph represented by an adjacency matrix
int graph[V][V] = {
{0, 2, 0, 6, 0, 0},
{2, 0, 3, 8, 5, 0},
{0, 3, 0, 0, 7, 9},
{6, 8, 0, 0, 0, 4},
{0, 5, 7, 0, 0, 1},
{0, 0, 9, 4, 1, 0}
};

// Perform Prim's algorithm


printf("Minimum Spanning Tree using Prim's Algorithm:\n");
primMST(graph);

return 0;
}

Output:

Minimum Spanning Tree using Prim's Algorithm:


Edge Weight
0-1 2
1-2 3
5-3 4
1-4 5
4-5 1

61

You might also like