0% found this document useful (0 votes)
4 views

DSA Experiment Solution-1

DSA

Uploaded by

yohey26470
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

DSA Experiment Solution-1

DSA

Uploaded by

yohey26470
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

1 Write a Program for Bubble Sort.

#include <stdio.h>

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]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}

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


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

int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, n);
printf("Sorted array: ");
printArray(arr, n);
return 0;
2 Write a Program for Insertion Sort.
#include <stdio.h>

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


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

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


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

int main() {
int arr[] = {12, 11, 13, 5, 6};
int n = sizeof(arr) / sizeof(arr[0]);
insertionSort(arr, n);
printf("Sorted array: ");
printArray(arr, n);
return 0;
}
3 Write a Program for Selection Sort.

#include <stdio.h>

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


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

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


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

int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr) / sizeof(arr[0]);
selectionSort(arr, n);
printf("Sorted array: ");
printArray(arr, n);
return 0;
}
4 Write a Program for Merge Sort.

#include <stdio.h>

void merge(int arr[], int l, int m, int r) {


int n1 = m - l + 1;
int n2 = r - m;
int L[n1], R[n2];

for (int i = 0; i < n1; i++) L[i] = arr[l + i];


for (int j = 0; j < n2; j++) R[j] = arr[m + 1 + j];

int i = 0, j = 0, k = l;
while (i < n1 && j < n2) {
arr[k++] = (L[i] <= R[j]) ? L[i++] : R[j++];
}
while (i < n1) arr[k++] = L[i++];
while (j < n2) arr[k++] = R[j++];
}

void mergeSort(int arr[], int l, int r) {


if (l < r) {
int m = l + (r - l) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
}

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


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

int main() {
int arr[] = {38, 27, 43, 3, 9, 82, 10};
int n = sizeof(arr) / sizeof(arr[0]);
mergeSort(arr, 0, n - 1);
printf("Sorted array: ");
printArray(arr, n);
return 0;
}

5 Write a Program for Quick Sort.

#include <stdio.h>

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


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

int partition(int arr[], int low, int high) {


int pivot = arr[high];
int i = low - 1;

for (int j = low; j < high; 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);
}
}

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


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

int main() {
int arr[] = {10, 7, 8, 9, 1, 5};
int n = sizeof(arr) / sizeof(arr[0]);
quickSort(arr, 0, n - 1);
printf("Sorted array: ");
printArray(arr, n);
return 0;
}

6 Write a Program for Linear Search in 1-D Array.

#include <stdio.h>
int linearSearch(int arr[], int n, int key) {
for (int i = 0; i < n; i++) {
if (arr[i] == key)
return i;
}
return -1;
}

int main() {
int arr[] = {10, 20, 30, 40, 50};
int n = sizeof(arr) / sizeof(arr[0]);
int key = 30;
int result = linearSearch(arr, n, key);
if (result != -1)
printf("Element found at index %d\n", result);
else
printf("Element not found\n");
return 0;
}

7 Write a Program for Binary Search in 1-D Array.

#include <stdio.h>

int binarySearch(int arr[], int n, int key) {


int low = 0, high = n - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == key)
return mid;
else if (arr[mid] < key)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}

int main() {
int arr[] = {10, 20, 30, 40, 50};
int n = sizeof(arr) / sizeof(arr[0]);
int key = 40;
int result = binarySearch(arr, n, key);
if (result != -1)
printf("Element found at index %d\n", result);
else
printf("Element not found\n");
return 0;
}

8 Implement Singly Linked List with the following operations:


1. Traversing 2. Insertion 1. Insert at the Beginning 2. Insert at
the End 3. Insert at the Position “n” 3. Deletion 1. Delete at the
Beginning 2. Delete at the End 3. Delete at the Position “n”

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

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

// Head pointer for the linked list


struct Node* head = NULL;

// 1. Traversing the List


void traverse() {
struct Node* temp = head;
if (temp == NULL) {
printf("List is empty\n");
return;
}
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}

// 2. Insertion at the Beginning


void insertAtBeginning(int data) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = data;
new_node->next = head;
head = new_node;
}

// 3. Insertion at the End


void insertAtEnd(int data) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = data;
new_node->next = NULL;
if (head == NULL) {
head = new_node;
return;
}

struct Node* temp = head;


while (temp->next != NULL) {
temp = temp->next;
}
temp->next = new_node;
}

// 4. Insertion at a Given Position n


void insertAtPosition(int data, int pos) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = data;

if (pos == 1) {
new_node->next = head;
head = new_node;
return;
}

struct Node* temp = head;


for (int i = 1; i < pos - 1 && temp != NULL; i++) {
temp = temp->next;
}

if (temp == NULL) {
printf("Position out of range\n");
free(new_node);
return;
}

new_node->next = temp->next;
temp->next = new_node;
}

// 5. Deletion at the Beginning


void deleteAtBeginning() {
if (head == NULL) {
printf("List is empty\n");
return;
}
struct Node* temp = head;
head = head->next;
free(temp);
}

// 6. Deletion at the End


void deleteAtEnd() {
if (head == NULL) {
printf("List is empty\n");
return;
}
if (head->next == NULL) {
free(head);
head = NULL;
return;
}

struct Node* temp = head;


while (temp->next->next != NULL) {
temp = temp->next;
}
free(temp->next);
temp->next = NULL;
}

// 7. Deletion at a Given Position n


void deleteAtPosition(int pos) {
if (head == NULL) {
printf("List is empty\n");
return;
}

if (pos == 1) {
struct Node* temp = head;
head = head->next;
free(temp);
return;
}

struct Node* temp = head;


for (int i = 1; i < pos - 1 && temp != NULL; i++) {
temp = temp->next;
}

if (temp == NULL || temp->next == NULL) {


printf("Position out of range\n");
return;
}

struct Node* to_delete = temp->next;


temp->next = to_delete->next;
free(to_delete);
}

int main() {
insertAtEnd(10);
insertAtEnd(20);
insertAtEnd(30);
printf("After inserting 10, 20, 30 at the end:\n");
traverse();

insertAtBeginning(5);
printf("After inserting 5 at the beginning:\n");
traverse();

insertAtPosition(25, 3);
printf("After inserting 25 at position 3:\n");
traverse();

deleteAtBeginning();
printf("After deleting at the beginning:\n");
traverse();

deleteAtEnd();
printf("After deleting at the end:\n");
traverse();

deleteAtPosition(2);
printf("After deleting at position 2:\n");
traverse();

return 0;
}

9 Implement Doubly Linked List with the


following operations: 1. Traversing 2. Insertion 1.
Insert at the Beginning 2. Insert at the End 3.
Insert at the Position “n” 3. Deletion 1. Delete at
the Beginning 2. Delete at the End 3. Delete at the
Position “n”

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

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

struct Node* head = NULL;

void traverse() {
struct Node* temp = head;
while (temp) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
void insert_begin(int val) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = val;
new_node->prev = NULL;
new_node->next = head;
if (head) head->prev = new_node;
head = new_node;
}

void insert_end(int val) {


struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = val;
new_node->prev = NULL;
new_node->next = NULL;
if (!head) {
head = new_node;
return;
}
struct Node* temp = head;
while (temp->next) temp = temp->next;
temp->next = new_node;
new_node->prev = temp;
}

void insert_at(int pos, int val) {


if (pos == 0) {
insert_begin(val);
return;
}
struct Node* temp = head;
for (int i = 0; temp && i < pos - 1; ++i) temp = temp->next;
if (!temp) return;
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = val;
new_node->next = temp->next;
new_node->prev = temp;
if (temp->next) temp->next->prev = new_node;
temp->next = new_node;
}

void delete_begin() {
if (!head) return;
struct Node* temp = head;
head = head->next;
if (head) head->prev = NULL;
free(temp);
}

void delete_end() {
if (!head) return;
struct Node* temp = head;
if (!temp->next) {
free(head);
head = NULL;
return;
}
while (temp->next) temp = temp->next;
temp->prev->next = NULL;
free(temp);
}

void delete_at(int pos) {


if (pos == 0) {
delete_begin();
return;
}
struct Node* temp = head;
for (int i = 0; temp && i < pos; ++i) temp = temp->next;
if (!temp) return;
if (temp->prev) temp->prev->next = temp->next;
if (temp->next) temp->next->prev = temp->prev;
free(temp);
}

int main() {
insert_begin(1);
insert_end(2);
insert_end(3);
insert_at(1, 4);
traverse();
delete_begin();
traverse();
delete_end();
traverse();
delete_at(1);
traverse();
return 0;
}

10 Implement Circular Linked List with the


following operations: 1. Traversing 2. Insertion 1.
Insert at the Beginning 2. Insert at the End 3.
Insert at the Position “n” 3. Deletion 1. Delete at
the Beginning 2. Delete at the End 3. Delete at the
Position “n”

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

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

struct Node* head = NULL;

void traverse() {
if (!head) return;
struct Node* temp = head;
do {
printf("%d ", temp->data);
temp = temp->next;
} while (temp != head);
printf("\n");
}

void insert_begin(int val) {


struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = val;
if (!head) {
new_node->next = new_node;
head = new_node;
return;
}
struct Node* temp = head;
while (temp->next != head) temp = temp->next;
new_node->next = head;
temp->next = new_node;
head = new_node;
}

void insert_end(int val) {


struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = val;
if (!head) {
new_node->next = new_node;
head = new_node;
return;
}
struct Node* temp = head;
while (temp->next != head) temp = temp->next;
temp->next = new_node;
new_node->next = head;
}

void insert_at(int pos, int val) {


if (pos == 0) {
insert_begin(val);
return;
}
struct Node* temp = head;
for (int i = 0; i < pos - 1 && temp->next != head; ++i) temp = temp->next;
if (temp->next == head && i < pos - 1) return;
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = val;
new_node->next = temp->next;
temp->next = new_node;
}

void delete_begin() {
if (!head) return;
if (head->next == head) {
free(head);
head = NULL;
return;
}
struct Node* temp = head;
while (temp->next != head) temp = temp->next;
struct Node* to_delete = head;
temp->next = head->next;
head = head->next;
free(to_delete);
}

void delete_end() {
if (!head) return;
if (head->next == head) {
free(head);
head = NULL;
return;
}
struct Node* temp = head;
while (temp->next->next != head) temp = temp->next;
struct Node* to_delete = temp->next;
temp->next = head;
free(to_delete);
}
void delete_at(int pos) {
if (pos == 0) {
delete_begin();
return;
}
struct Node* temp = head;
for (int i = 0; i < pos - 1 && temp->next != head; ++i) temp = temp->next;
if (temp->next == head) return;
struct Node* to_delete = temp->next;
temp->next = to_delete->next;
free(to_delete);
}

int main() {
insert_begin(1);
insert_end(2);
insert_end(3);
insert_at(1, 4);
traverse();
delete_begin();
traverse();
delete_end();
traverse();
delete_at(1);
traverse();
return 0;
}

11 Implement Stack with the following operations:


1. As an Array 1. Insertion 2. Deletion 3. Traversal
2. As Linked List 1. Insertion 2. Deletion 3.
Traversal

1. Stack as an Array
#include <stdio.h>
#include <stdlib.h>
#define MAX 100

int stack[MAX], top = -1;

void push(int val) {


if (top == MAX - 1) return; // Stack overflow
stack[++top] = val;
}

void pop() {
if (top == -1) return; // Stack underflow
top--;
}

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

int main() {
push(1);
push(2);
push(3);
traverse_array();
pop();
traverse_array();
return 0;
}

2. As Linked List

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

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

struct Node* top = NULL;

void push(int val) {


struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = val;
new_node->next = top;
top = new_node;
}

void pop() {
if (!top) return;
struct Node* temp = top;
top = top->next;
free(temp);
}

void traverse_list() {
struct Node* temp = top;
while (temp) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}

int main() {
push(1);
push(2);
push(3);
traverse_list();
pop();
traverse_list();
return 0;
}

12 Implement Queue with the following operations:


1. As an Array
1. Insertion
2. Deletion
3. Traversal
2. As Linked List
1. Insertion
2. Deletion
3. Traversal
1. Queue as an Array

#include <stdio.h>
#include <stdlib.h>
#define MAX 100

int queue[MAX], front = -1, rear = -1;

void enqueue(int val) {


if ((rear + 1) % MAX == front) return; // Queue overflow
if (front == -1) front = 0;
rear = (rear + 1) % MAX;
queue[rear] = val;
}

void dequeue() {
if (front == -1) return; // Queue underflow
if (front == rear) front = rear = -1; // Reset queue
else front = (front + 1) % MAX;
}

void traverse_array() {
if (front == -1) return; // Queue is empty
int i = front;
while (1) {
printf("%d ", queue[i]);
if (i == rear) break;
i = (i + 1) % MAX;
}
printf("\n");
}
int main() {
enqueue(1);
enqueue(2);
enqueue(3);
traverse_array();
dequeue();
traverse_array();
return 0;
}

2. Queue as a Linked List


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

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

struct Node* front = NULL;


struct Node* rear = NULL;

void enqueue(int val) {


struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = val;
new_node->next = NULL;
if (!rear) {
front = rear = new_node;
return;
}
rear->next = new_node;
rear = new_node;
}

void dequeue() {
if (!front) return; // Queue underflow
struct Node* temp = front;
front = front->next;
if (!front) rear = NULL; // Reset rear if queue is empty
free(temp);
}

void traverse_list() {
struct Node* temp = front;
while (temp) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}

int main() {
enqueue(1);
enqueue(2);
enqueue(3);
traverse_list();
dequeue();
traverse_list();
return 0;
}
13 Represent a 2-variable polynomial using
array.Use this representation to implement
addition
of polynomials.

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

#define MAX_DEGREE 5 // Maximum degree of the polynomial

// Polynomial structure using a 2D array


struct Polynomial {
int coeff[MAX_DEGREE + 1][MAX_DEGREE + 1]; // Coefficients for x^i * y^j
};

// Function to initialize a polynomial to zero


void init_polynomial(struct Polynomial* p) {
for (int i = 0; i <= MAX_DEGREE; i++)
for (int j = 0; j <= MAX_DEGREE; j++)
p->coeff[i][j] = 0;
}

// Function to add two polynomials


void add_polynomials(struct Polynomial* p1, struct Polynomial* p2, struct Polynomial*
result) {
for (int i = 0; i <= MAX_DEGREE; i++)
for (int j = 0; j <= MAX_DEGREE; j++)
result->coeff[i][j] = p1->coeff[i][j] + p2->coeff[i][j];
}
// Function to print a polynomial
void print_polynomial(struct Polynomial* p) {
int first = 1;
for (int i = 0; i <= MAX_DEGREE; i++) {
for (int j = 0; j <= MAX_DEGREE; j++) {
if (p->coeff[i][j] != 0) {
if (!first) printf(" + ");
printf("%d*x^%d*y^%d", p->coeff[i][j], i, j);
first = 0;
}
}
}
printf("\n");
}

// Function to read a polynomial from user input


void read_polynomial(struct Polynomial* p) {
for (int i = 0; i <= MAX_DEGREE; i++) {
for (int j = 0; j <= MAX_DEGREE; j++) {
printf("Enter coefficient for x^%d * y^%d: ", i, j);
scanf("%d", &p->coeff[i][j]);
}
}
}

int main() {
struct Polynomial p1, p2, result;

// Initialize polynomials
init_polynomial(&p1);
init_polynomial(&p2);
init_polynomial(&result);
printf("Enter coefficients for Polynomial P1:\n");
read_polynomial(&p1);

printf("Enter coefficients for Polynomial P2:\n");


read_polynomial(&p2);

// Add the polynomials


add_polynomials(&p1, &p2, &result);

// Print the polynomials


printf("Polynomial P1: ");
print_polynomial(&p1);

printf("Polynomial P2: ");


print_polynomial(&p2);

printf("Resultant Polynomial after Addition: ");


print_polynomial(&result);

return 0;
}

14 Represent a sparse matrix using array. Use this


representation to implement addition and
transposition operations.

#include <stdio.h>
#include <stdlib.h>
#define MAX_NON_ZERO 100 // Maximum number of non-zero elements

struct SparseMatrix {
int row[MAX_NON_ZERO]; // Row indices of non-zero elements
int col[MAX_NON_ZERO]; // Column indices of non-zero elements
int val[MAX_NON_ZERO]; // Values of non-zero elements
int size; // Number of non-zero elements
};

// Function to initialize a sparse matrix


void init_sparse_matrix(struct SparseMatrix* sm) {
sm->size = 0;
}

// Function to add two sparse matrices


void add_sparse_matrices(struct SparseMatrix* sm1, struct SparseMatrix* sm2, struct
SparseMatrix* result) {
int i = 0, j = 0;
result->size = 0;

while (i < sm1->size && j < sm2->size) {


if (sm1->row[i] == sm2->row[j] && sm1->col[i] == sm2->col[j]) {
// Same position, add values
result->row[result->size] = sm1->row[i];
result->col[result->size] = sm1->col[i];
result->val[result->size] = sm1->val[i] + sm2->val[j];
i++;
j++;
} else if (sm1->row[i] < sm2->row[j] || (sm1->row[i] == sm2->row[j] && sm1->col[i] <
sm2->col[j])) {
result->row[result->size] = sm1->row[i];
result->col[result->size] = sm1->col[i];
result->val[result->size] = sm1->val[i];
i++;
} else {
result->row[result->size] = sm2->row[j];
result->col[result->size] = sm2->col[j];
result->val[result->size] = sm2->val[j];
j++;
}
result->size++;
}

// Add remaining elements of sm1


while (i < sm1->size) {
result->row[result->size] = sm1->row[i];
result->col[result->size] = sm1->col[i];
result->val[result->size] = sm1->val[i];
i++;
result->size++;
}

// Add remaining elements of sm2


while (j < sm2->size) {
result->row[result->size] = sm2->row[j];
result->col[result->size] = sm2->col[j];
result->val[result->size] = sm2->val[j];
j++;
result->size++;
}
}

// Function to transpose a sparse matrix


void transpose_sparse_matrix(struct SparseMatrix* sm, struct SparseMatrix* result) {
result->size = 0;
for (int i = 0; i < sm->size; i++) {
result->row[i] = sm->col[i];
result->col[i] = sm->row[i];
result->val[i] = sm->val[i];
}
result->size = sm->size;
}

// Function to print a sparse matrix


void print_sparse_matrix(struct SparseMatrix* sm) {
for (int i = 0; i < sm->size; i++) {
printf("Row: %d, Col: %d, Value: %d\n", sm->row[i], sm->col[i], sm->val[i]);
}
}

int main() {
struct SparseMatrix sm1, sm2, result;

// Initialize sparse matrices


init_sparse_matrix(&sm1);
init_sparse_matrix(&sm2);
init_sparse_matrix(&result);

// Example: Creating Sparse Matrix 1


sm1.row[0] = 0; sm1.col[0] = 0; sm1.val[0] = 5; // Element at (0, 0)
sm1.row[1] = 1; sm1.col[1] = 2; sm1.val[1] = 10; // Element at (1, 2)
sm1.size = 2;

// Example: Creating Sparse Matrix 2


sm2.row[0] = 0; sm2.col[0] = 1; sm2.val[0] = 3; // Element at (0, 1)
sm2.row[1] = 1; sm2.col[1] = 2; sm2.val[1] = 15; // Element at (1, 2)
sm2.size = 2;

// Add the sparse matrices


add_sparse_matrices(&sm1, &sm2, &result);

// Print the result of addition


printf("Result of Sparse Matrix Addition:\n");
print_sparse_matrix(&result);

// Transpose the first sparse matrix


struct SparseMatrix transposed;
init_sparse_matrix(&transposed);
transpose_sparse_matrix(&sm1, &transposed);

// Print the transposed matrix


printf("Transposed Sparse Matrix 1:\n");
print_sparse_matrix(&transposed);

return 0;
}

15 Implement binary search tree with operations:


1) Insertion
2) Deletion
3) Traversal.

#include <stdio.h>
#include <stdlib.h>
// Structure for a node in the binary search tree
struct Node {
int data;
struct Node* left;
struct Node* right;
};

// Function to create a new node


struct Node* create_node(int data) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = data;
new_node->left = NULL;
new_node->right = NULL;
return new_node;
}

// Function to insert a new node in the BST


struct Node* insert(struct Node* root, int data) {
if (root == NULL) {
return create_node(data);
}
if (data < root->data) {
root->left = insert(root->left, data);
} else if (data > root->data) {
root->right = insert(root->right, data);
}
return root;
}

// Function to find the minimum value node


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

// Function to delete a node from the BST


struct Node* delete_node(struct Node* root, int data) {
if (root == NULL) return root;

if (data < root->data) {


root->left = delete_node(root->left, data);
} else if (data > root->data) {
root->right = delete_node(root->right, data);
} else {
// Node with only 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, get the inorder successor


struct Node* temp = find_min(root->right);
root->data = temp->data; // Copy the inorder successor's content
root->right = delete_node(root->right, temp->data); // Delete the inorder successor
}
return root;
}
// Function for inorder traversal of the BST
void inorder_traversal(struct Node* root) {
if (root != NULL) {
inorder_traversal(root->left);
printf("%d ", root->data);
inorder_traversal(root->right);
}
}

// Function for preorder traversal of the BST


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

// Function for postorder traversal of the BST


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

// Main function to demonstrate the BST operations


int main() {
struct Node* root = NULL;
// Inserting nodes into the BST
root = insert(root, 50);
root = insert(root, 30);
root = insert(root, 20);
root = insert(root, 40);
root = insert(root, 70);
root = insert(root, 60);
root = insert(root, 80);

// Traversals
printf("Inorder traversal: ");
inorder_traversal(root);
printf("\n");

printf("Preorder traversal: ");


preorder_traversal(root);
printf("\n");

printf("Postorder traversal: ");


postorder_traversal(root);
printf("\n");

// Deleting a node
printf("Deleting 20\n");
root = delete_node(root, 20);
printf("Inorder traversal after deleting 20: ");
inorder_traversal(root);
printf("\n");

printf("Deleting 30\n");
root = delete_node(root, 30);
printf("Inorder traversal after deleting 30: ");
inorder_traversal(root);
printf("\n");

printf("Deleting 50\n");
root = delete_node(root, 50);
printf("Inorder traversal after deleting 50: ");
inorder_traversal(root);
printf("\n");

return 0;
}

16 Implement following traversal operations on Graphs represented


using
adjacency matrix and list:
1. Depth First Search
2. Breadth First Search

1. DFS using Adjacency Matrix

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

#define MAX 100

void DFS(int graph[MAX][MAX], int visited[], int vertex, int n) {


visited[vertex] = 1; // Mark the vertex as visited
printf("%d ", vertex);

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


if (graph[vertex][i] == 1 && !visited[i]) { // If there's an edge and not visited
DFS(graph, visited, i, n);
}
}
}

int main() {
int n, graph[MAX][MAX], visited[MAX] = {0};

// Input number of vertices


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

// Input adjacency matrix


printf("Enter adjacency matrix:\n");
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
scanf("%d", &graph[i][j]);

printf("DFS Traversal: ");


DFS(graph, visited, 0, n); // Start DFS from vertex 0
printf("\n");

return 0;
}

2. BFS using Adjacency List

#include <stdio.h>
#include <stdlib.h>
struct Node {
int vertex;
struct Node* next;
};

struct Node* createNode(int v) {


struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->vertex = v;
newNode->next = NULL;
return newNode;
}

void DFS(struct Node* adjList[], int visited[], int vertex) {


visited[vertex] = 1; // Mark the vertex as visited
printf("%d ", vertex);

struct Node* temp = adjList[vertex];


while (temp) {
if (!visited[temp->vertex]) {
DFS(adjList, visited, temp->vertex); // Recursive call
}
temp = temp->next;
}
}

int main() {
int n, visited[MAX] = {0};
struct Node* adjList[MAX] = {NULL};

// Input number of vertices


printf("Enter number of vertices: ");
scanf("%d", &n);
// Input adjacency list
printf("Enter edges (format: u v), enter -1 -1 to stop:\n");
while (1) {
int u, v;
scanf("%d %d", &u, &v);
if (u == -1 && v == -1) break;

struct Node* newNode = createNode(v);


newNode->next = adjList[u];
adjList[u] = newNode;

newNode = createNode(u);
newNode->next = adjList[v];
adjList[v] = newNode; // For undirected graph
}

printf("DFS Traversal: ");


DFS(adjList, visited, 0); // Start DFS from vertex 0
printf("\n");

return 0;
}

pankaj

You might also like