0% found this document useful (0 votes)
8 views55 pages

DS Practical File

The document outlines programs to implement various data structures and algorithms. It includes programs to implement functions, arrays, linked lists, stacks, queues, trees, and graphs. It also includes programs for sorting techniques like insertion sort, selection sort, merge sort and quick sort as well as searching techniques like linear search and binary search.

Uploaded by

Gaurav Yadav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views55 pages

DS Practical File

The document outlines programs to implement various data structures and algorithms. It includes programs to implement functions, arrays, linked lists, stacks, queues, trees, and graphs. It also includes programs for sorting techniques like insertion sort, selection sort, merge sort and quick sort as well as searching techniques like linear search and binary search.

Uploaded by

Gaurav Yadav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

Data Structure Lab (CSE-102 P)

Sr. Name of Name of the Program


No. Modules

1. Functions •
WAP to create a function to swap two numbers using call by value.

WAP to implement call by reference for swapping of two numbers.
2. Arrays •
WAP to create an array.

WAP to insert a new number in an array at any location

WAP to delete any number from an array
3. Searching •
WAP to search an element into an array using linear search

WAP for finding the element in an array using binary search method
using iteration and recursion.
4. Sorting WAP that implements the following sorting: -

• Insertion Sort
• Selection Sort
• Bubble Sort
• Merge Sort
• Quick Sort
5. Stack and Queue • WAP to implement stack using array.
using Array • WAP to implement queue using array.

6. Linked List • WAP to create a linked list & perform operations such as insert, delete
and reverse in the linked list.
7. Stack and Queue • WAP to implement stack using linked list.
using Linked • WAP to implement queue using linked list
List

8. Tree WAP to perform the following operations: -

• Insert an element into a binary search tree.


• Delete an element from a binary search tree.
• Search for a key element in a binary search tree.
9. Graph • WAP to implement DFS and BFS
Practical 1

Aim- WAP to create a function to swap two numbers using call by value

#include <stdio.h>

void swapx(int x, int y);

int main()

int a = 10, b = 20;

swapx(a, b);

printf("In the Caller:\na = %d b = %d\n", a, b);

return 0;

void swapx(int x, int y)

int t;

t = x;

x = y;

y = t;

printf("Inside Function:\nx = %d y = %d\n", x, y);

}
Practical 2

Aim- WAP to implement call by reference for swapping of two numbers

#include <stdio.h>

void swapx(int*, int*);

int main()

int a = 10, b = 20;

swapx(&a, &b);

printf("Inside the Caller:\na = %d b = %d\n", a, b);

return 0;

void swapx(int* x, int* y)

int t;

t = *x;

*x = *y;

*y = t;

printf("Inside the Function:\nx = %d y = %d\n", *x, *y);

}
Practical 3

Aim- Creation of Array

#include <stdio.h>

int main () {

int n[ 10 ]; /* n is an array of 10 integers */

int i,j;

/* initialize elements of array n to 0 */

for ( i = 0; i < 10; i++ ) {

n[ i ] = i + 100; /* set element at location i to i + 100 */

/* output each array element's value */

for (j = 0; j < 10; j++ ) {

printf("Element[%d] = %d\n", j, n[j] );

return 0;

}
Practical 4

Aim- WAP to insert a new number in an array at any location

#include <stdio.h>

int main()

int arr[100] = { 0 };

int i, x, pos, n = 10;

// initial array of size 10

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

arr[i] = i + 1;

// print the original array

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

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

printf("\n");

// element to be inserted

x = 50;

// position at which element is to be inserted

pos = 5;

// increase the size by 1

n++;

// shift elements forward

for (i = n - 1; i >= pos; i--)

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

// insert x at pos

arr[pos - 1] = x;
// print the updated array

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

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

printf("\n");

return 0;

}
Program-5

Aim- WAP to delete any number from an array

#include <stdio.h>

int main()

int array[100], position, c, n;

printf("Enter number of elements in array\n");

scanf("%d", &n);

printf("Enter %d elements\n", n);

for ( c = 0 ; c < n ; c++ )

scanf("%d", &array[c]);

printf("Enter the location where you wish to delete element\n");

scanf("%d", &position);

if ( position >= n+1 )

printf("Deletion not possible.\n");

else

for ( c = position - 1 ; c < n - 1 ; c++ )

array[c] = array[c+1];

printf("Resultant array is\n");

for( c = 0 ; c < n - 1 ; c++ )

printf("%d\n", array[c]);

return 0;

}
Program-6

Aim- WAP to search an element into an array using linear search

// C code to linearly search x in arr[]. If x is present then return its location, otherwise
return -1

#include <stdio.h>

int search(int arr[], int N, int x)

int i;

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

if (arr[i] == x)

return i;

return -1;

int main(void)

int arr[] = { 2, 3, 4, 10, 40 };

int x = 10;

int N = sizeof(arr) / sizeof(arr[0]);

// Function call

int result = search(arr, N, x);

(result == -1)

? printf("Element is not present in array")

: printf("Element is present at index %d", result);

return 0;

}
Program-7

Aim- WAP for finding the element in an array using binary search method using iteration and
recursion

(A) Iteration

#include <stdio.h>

// A iterative binary search function. It returns location of x in

// given array arr[l..r] if present, otherwise -1

int binarySearch(int arr[], int l, int r, int x)

while (l <= r)

int m = l + (r-l)/2;

// Check if x is present at mid

if (arr[m] == x)

return m;

// If x greater, ignore left half

if (arr[m] < x)

l = m + 1;

// If x is smaller, ignore right half

else

r = m - 1;

// if we reach here, then element was not present

return -1;

}
int main(void)

int arr[] = {2, 3, 4, 10, 40};

int n = sizeof(arr)/ sizeof(arr[0]);

int x = 10;

int result = binarySearch(arr, 0, n-1, x);

(result == -1)? printf("Element is not present in array")

: printf("Element is present at index %d", result);

return 0;

(B) Recursion
#include <stdio.h>
// A recursive binary search function. It returns location of x in
// given array arr[l..r] is present, otherwise -1
int binarySearch(int arr[], int l, int r, int x)
{
if (r >= l)
{
int mid = l + (r - l)/2;
// If the element is present at the middle itself
if (arr[mid] == x) return mid;
// If element is smaller than mid, then it can only be present
// in left subarray
if (arr[mid] > x) return binarySearch(arr, l, mid-1, x);
// Else the element can only be present in right subarray
return binarySearch(arr, mid+1, r, x);
}
// We reach here when element is not present in array
return -1;
}
int main(void)
{
int arr[] = {2, 3, 4, 10, 40};
int n = sizeof(arr)/ sizeof(arr[0]);
int x = 10;
int result = binarySearch(arr, 0, n-1, x);
(result == -1)? printf("Element is not present in array")
: printf("Element is present at index %d", result);
return 0;
}
Program-9
Aim- WAP to implement of insertion sort
// C program for insertion sort
#include <math.h>
#include <stdio.h>
/* Function to sort an array using insertion sort*/
void insertionSort(int arr[], int n)
{
int i, key, j;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;

/* Move elements of arr[0..i-1], that are


greater than key, to one position ahead
of their current position */
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
// A utility function to print an array of size n
void printArray(int arr[], int n)
{
int i;
for (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);
printArray(arr, n);

return 0;
}
Program-9
Aim- WAP to implement of Selection sort

// C program for implementation of selection sort

#include <stdio.h>

void swap(int *xp, int *yp)

int temp = *xp;

*xp = *yp;

*yp = temp;

void selectionSort(int arr[], int n)

int i, j, min_idx;

// One by one move boundary of unsorted subarray

for (i = 0; i < n-1; i++)

// Find the minimum element in unsorted array

min_idx = i;

for (j = i+1; j < n; j++)

if (arr[j] < arr[min_idx])

min_idx = j;

// Swap the found minimum element with the first element

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

}
/* Function to print an array */

void printArray(int arr[], int size)

int i;

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

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

printf("\n");

// Driver program to test above functions

int main()

int arr[] = {64, 25, 12, 22, 11};

int n = sizeof(arr)/sizeof(arr[0]);

selectionSort(arr, n);

printf("Sorted array: \n");

printArray(arr, n);

return 0;

}
Program-10
Aim- WAP to implement of Bubble sort
// C program for implementation of Bubble sort
#include <stdio.h>
void swap(int* xp, int* yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
// A function to implement bubble sort
void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n - 1; i++)

// Last i elements are already in place


for (j = 0; j < n - i - 1; j++)
if (arr[j] > arr[j + 1])
swap(&arr[j], &arr[j + 1]);
}
/* Function to print an array */
void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}

// Driver program to test above functions


int main()
{
int arr[] = { 5, 1, 4, 2, 8 };
int n = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}
Program-11
Aim- WAP to implement of Merge sort

#include <stdio.h>

#define max 10

int a[11] = { 10, 14, 19, 26, 27, 31, 33, 35, 42, 44, 0 };

int b[10];

void merging(int low, int mid, int high) {

int l1, l2, i;

for(l1 = low, l2 = mid + 1, i = low; l1 <= mid && l2 <= high; i++) {

if(a[l1] <= a[l2])

b[i] = a[l1++];

else

b[i] = a[l2++];

while(l1 <= mid)

b[i++] = a[l1++];

while(l2 <= high)

b[i++] = a[l2++];

for(i = low; i <= high; i++)

a[i] = b[i];

void sort(int low, int high) {

int mid;

if(low < high) {

mid = (low + high) / 2;


sort(low, mid);

sort(mid+1, high);

merging(low, mid, high);

} else {

return;

int main() {

int i;

printf("List before sorting\n");

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

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

sort(0, max);

printf("\nList after sorting\n");

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

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

}
Program-12
Aim- WAP to implement of Quick sort

// C code to implement quicksort

#include <stdio.h>

// Function to swap two elements

void swap(int* a, int* b)

int t = *a;

*a = *b;

*b = t;

// Partition the array using the last element as the pivot

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

// Choosing the pivot

int pivot = arr[high];

// Index of smaller element and indicates

// the right position of pivot found so far

int i = (low - 1);

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

// If current element is smaller than the pivot

if (arr[j] < pivot) {

// Increment index of smaller element

i++;

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

swap(&arr[i + 1], &arr[high]);

return (i + 1);

// The main function that implements QuickSort

// arr[] --> Array to be sorted,

// low --> Starting index,

// high --> Ending index

void quickSort(int arr[], int low, int high)

if (low < high) {

// pi is partitioning index, arr[p]

// is now at right place

int pi = partition(arr, low, high);

// Separately sort elements before

// partition and after partition

quickSort(arr, low, pi - 1);

quickSort(arr, pi + 1, high);

// Driver code

int main()

{
int arr[] = { 10, 7, 8, 9, 1, 5 };

int N = sizeof(arr) / sizeof(arr[0]);

// Function call

quickSort(arr, 0, N - 1);

printf("Sorted array: \n");

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

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

return 0;

}
Program- 13

Aim- WAP to implement stack using array

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

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

}
Program- 14

Aim- WAP to implement queue using Array

#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;

case 4:

exit(0);

default:
printf("Wrong Choice: please see the options");

return 0;

}
Program- 15

Aim- WAP to create a linked list & perform operations such as insert, delete and reverse in the
linked list.

(A) Creation
// Linked list implementation in C

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

// Creating a node
struct node {
int value;
struct node *next;
};

// print the linked list value


void printLinkedlist(struct node *p) {
while (p != NULL) {
printf("%d ", p->value);
p = p->next;
}
}

int main() {
// Initialize nodes
struct node *head;
struct node *one = NULL;
struct node *two = NULL;
struct node *three = NULL;

// Allocate memory
one = malloc(sizeof(struct node));
two = malloc(sizeof(struct node));
three = malloc(sizeof(struct node));
// Assign value values
one->value = 1;
two->value = 2;
three->value = 3;
// Connect nodes
one->next = two;
two->next = three;
three->next = NULL;
// printing node-value
head = one;
printLinkedlist(head);
}
(B) Insert
// A complete working C program to demonstrate all insertion methods
// on Linked List
#include <stdio.h>
#include <stdlib.h>

// A linked list node


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

/* Given a reference (pointer to pointer) to the head of a list and


an int, inserts a new node on the front of the list. */
void push(struct Node** head_ref, int new_data)
{
/* 1. allocate node */
struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));

/* 2. put in the data */


new_node->data = new_data;

/* 3. Make next of new node as head */


new_node->next = (*head_ref);

/* 4. move the head to point to the new node */


(*head_ref) = new_node;
}

/* Given a node prev_node, insert a new node after the given


prev_node */
void insertAfter(struct Node* prev_node, int new_data)
{
/*1. check if the given prev_node is NULL */
if (prev_node == NULL)
{
printf("the given previous node cannot be NULL");
return;
}

/* 2. allocate new node */


struct Node* new_node =(struct Node*) malloc(sizeof(struct Node));

/* 3. put in the data */


new_node->data = new_data;

/* 4. Make next of new node as next of prev_node */


new_node->next = prev_node->next;

/* 5. move the next of prev_node as new_node */


prev_node->next = new_node;
}

/* Given a reference (pointer to pointer) to the head


of a list and an int, appends a new node at the end */
void append(struct Node** head_ref, int new_data)
{
/* 1. allocate node */
struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));

struct Node *last = *head_ref; /* used in step 5*/

/* 2. put in the data */


new_node->data = new_data;

/* 3. This new node is going to be the last node, so make next of


it as NULL*/
new_node->next = NULL;

/* 4. If the Linked List is empty, then make the new node as head */
if (*head_ref == NULL)
{
*head_ref = new_node;
return;
}

/* 5. Else traverse till the last node */


while (last->next != NULL)
last = last->next;

/* 6. Change the next of last node */


last->next = new_node;
return;
}

// This function prints contents of linked list starting from head


void printList(struct Node *node)
{
while (node != NULL)
{
printf(" %d ", node->data);
node = node->next;
}
}

/* Driver program to test above functions*/


int main()
{
/* Start with the empty list */
struct Node* head = NULL;

// Insert 6. So linked list becomes 6->NULL


append(&head, 6);

// Insert 7 at the beginning. So linked list becomes 7->6->NULL


push(&head, 7);

// Insert 1 at the beginning. So linked list becomes 1->7->6->NULL


push(&head, 1);

// Insert 4 at the end. So linked list becomes 1->7->6->4->NULL


append(&head, 4);

// Insert 8, after 7. So linked list becomes 1->7->8->6->4->NULL


insertAfter(head->next, 8);

printf("\n Created Linked list is: ");


printList(head);

return 0;
}
(C) Deletion
// C code to delete a node from linked list
#include <stdio.h>
#include <stdlib.h>

typedef struct Node {


int number;
struct Node* next;
} Node;

void Push(Node** head, int A)


{
Node* n = malloc(sizeof(Node));
n->number = A;
n->next = *head;
*head = n;
}

void deleteN(Node** head, int position)


{
Node* temp;
Node* prev;
temp = *head;
prev = *head;
for (int i = 0; i < position; i++) {
if (i == 0 && position == 1) {
*head = (*head)->next;
free(temp);
}
else {
if (i == position - 1 && temp) {
prev->next = temp->next;
free(temp);
}
else {
prev = temp;

// Position was greater than


// number of nodes in the list
if (prev == NULL)
break;
temp = temp->next;
}
}
}
}

void printList(Node* head)


{
while (head) {
printf("[%i] [%p]->%p\n", head->number, head,
head->next);
head = head->next;
}
printf("\n\n");
}

// Drivers code
int main()
{
Node* list = malloc(sizeof(Node));
list->next = NULL;
Push(&list, 1);
Push(&list, 2);
Push(&list, 3);

printList(list);

// Delete any position from list


deleteN(&list, 1);
printList(list);
return 0;
}
(D) Inversion
#include<stdio.h>
#include<stdlib.h>

/* Link list node */


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

/* Function to reverse the linked list */


static void reverse(struct Node** head_ref)
{
struct Node* prev = NULL;
struct Node* current = *head_ref;
struct Node* next;
while (current != NULL)
{
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*head_ref = prev;
}

/* Function to push a node */


void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));

/* put in the data */


new_node->data = new_data;
/* link the old list of the new node */
new_node->next = (*head_ref);

/* move the head to point to the new node */


(*head_ref) = new_node;
}

/* Function to print linked list */


void printList(struct Node *head)
{
struct Node *temp = head;
while(temp != NULL)
{
printf("%d ", temp->data);
temp = temp->next;
}
}

/* Driver program to test above function*/


int main()
{
/* Start with the empty list */
struct Node* head = NULL;

push(&head, 20);
push(&head, 4);
push(&head, 15);
push(&head, 85);

printf("Given linked list\n");


printList(head);
reverse(&head);
printf("\nReversed Linked list \n");
printList(head);
getchar();
}
Program-16

Aim- WAP to implement stack using Linked List

#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;

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

}
Program-17

Aim- WAP to implement queue using Linked List

// C program for array implementation of queue

#include <limits.h>

#include <stdio.h>

#include <stdlib.h>

// A structure to represent a queue

struct Queue {

int front, rear, size;

unsigned capacity;

int* array;

};

// function to create a queue

// of given capacity.

// It initializes size of queue as 0

struct Queue* createQueue(unsigned capacity)

struct Queue* queue = (struct Queue*)malloc(

sizeof(struct Queue));

queue->capacity = capacity;

queue->front = queue->size = 0;

// This is important, see the enqueue

queue->rear = capacity - 1;

queue->array = (int*)malloc(
queue->capacity * sizeof(int));

return queue;

// Queue is full when size becomes

// equal to the capacity

int isFull(struct Queue* queue)

return (queue->size == queue->capacity);

// Queue is empty when size is 0

int isEmpty(struct Queue* queue)

return (queue->size == 0);

// Function to add an item to the queue.

// It changes rear and size

void enqueue(struct Queue* queue, int item)

if (isFull(queue))

return;

queue->rear = (queue->rear + 1)

% queue->capacity;
queue->array[queue->rear] = item;

queue->size = queue->size + 1;

printf("%d enqueued to queue\n", item);

// Function to remove an item from queue.

// It changes front and size

int dequeue(struct Queue* queue)

if (isEmpty(queue))

return INT_MIN;

int item = queue->array[queue->front];

queue->front = (queue->front + 1)

% queue->capacity;

queue->size = queue->size - 1;

return item;

// Function to get front of queue

int front(struct Queue* queue)

if (isEmpty(queue))

return INT_MIN;

return queue->array[queue->front];

}
// Function to get rear of queue

int rear(struct Queue* queue)

if (isEmpty(queue))

return INT_MIN;

return queue->array[queue->rear];

// Driver program to test above functions./

int main()

struct Queue* queue = createQueue(1000);

enqueue(queue, 10);

enqueue(queue, 20);

enqueue(queue, 30);

enqueue(queue, 40);

printf("%d dequeued from queue\n\n",

dequeue(queue));

printf("Front item is %d\n", front(queue));

printf("Rear item is %d\n", rear(queue));

return 0;

}
Program- 18

Aim- WAP to perform the following operations: -

• Insert an element into a binary search tree.


• Delete an element from a binary search tree.
• Search for a key element in a binary search tree.

#include <stdio.h>

#include <stdlib.h>

struct node {

int data; //node will store some data

struct node *right_child; // right child

struct node *left_child; // left child

};

//function to create a node

struct node* new_node(int x) {

struct node *temp;

temp = malloc(sizeof(struct node));

temp -> data = x;

temp -> left_child = NULL;

temp -> right_child = NULL;

return temp;

// searching operation
struct node* search(struct node * root, int x) {

if (root == NULL || root -> data == x) //if root->data is x then the element is found

return root;

else if (x > root -> data) // x is greater, so we will search the right subtree

return search(root -> right_child, x);

else //x is smaller than the data, so we will search the left subtree

return search(root -> left_child, x);

// insertion

struct node* insert(struct node * root, int x) {

//searching for the place to insert

if (root == NULL)

return new_node(x);

else if (x > root -> data) // x is greater. Should be inserted to the right

root -> right_child = insert(root -> right_child, x);

else // x is smaller and should be inserted to left

root -> left_child = insert(root -> left_child, x);

return root;

//function to find the minimum value in a node

struct node* find_minimum(struct node * root) {

if (root == NULL)

return NULL;
else if (root -> left_child != NULL) // node with minimum value will have no left child

return find_minimum(root -> left_child); // left most element will be minimum

return root;

// deletion

struct node* delete(struct node * root, int x) {

//searching for the item to be deleted

if (root == NULL)

return NULL;

if (x > root -> data)

root -> right_child = delete(root -> right_child, x);

else if (x < root -> data)

root -> left_child = delete(root -> left_child, x);

else {

//No Child node

if (root -> left_child == NULL && root -> right_child == NULL) {

free(root);

return NULL;

//One Child node

else if (root -> left_child == NULL || root -> right_child == NULL) {

struct node *temp;

if (root -> left_child == NULL)


temp = root -> right_child;

else

temp = root -> left_child;

free(root);

return temp;

//Two Children

else {

struct node *temp = find_minimum(root -> right_child);

root -> data = temp -> data;

root -> right_child = delete(root -> right_child, temp -> data);

return root;

// Inorder Traversal

void inorder(struct node *root) {

if (root != NULL) // checking if the root is not null

inorder(root -> left_child); // traversing left child

printf(" %d ", root -> data); // printing data at root

inorder(root -> right_child); // traversing right child

}
}

int main() {

struct node *root;

root = new_node(20);

insert(root, 5);

insert(root, 1);

insert(root, 15);

insert(root, 9);

insert(root, 7);

insert(root, 12);

insert(root, 30);

insert(root, 25);

insert(root, 40);

insert(root, 45);

insert(root, 42);

inorder(root);

printf("\n");

root = delete(root, 1);

root = delete(root, 40);

root = delete(root, 45);

root = delete(root, 9);

inorder(root);

printf("\n");

return 0;

}
Program- 19

Aim- Implement BFS and DFS in a graph

(A) BFS
// BFS algorithm in C

#include <stdio.h>
#include <stdlib.h>
#define SIZE 40

struct queue {
int items[SIZE];
int front;
int rear;
};

struct queue* createQueue();


void enqueue(struct queue* q, int);
int dequeue(struct queue* q);
void display(struct queue* q);
int isEmpty(struct queue* q);
void printQueue(struct queue* q);

struct node {
int vertex;
struct node* next;
};

struct node* createNode(int);

struct Graph {
int numVertices;
struct node** adjLists;
int* visited;
};

// BFS algorithm
void bfs(struct Graph* graph, int startVertex) {
struct queue* q = createQueue();
graph->visited[startVertex] = 1;
enqueue(q, startVertex);

while (!isEmpty(q)) {
printQueue(q);
int currentVertex = dequeue(q);
printf("Visited %d\n", currentVertex);

struct node* temp = graph->adjLists[currentVertex];

while (temp) {
int adjVertex = temp->vertex;

if (graph->visited[adjVertex] == 0) {
graph->visited[adjVertex] = 1;
enqueue(q, adjVertex);
}
temp = temp->next;
}
}
}

// Creating a node
struct node* createNode(int v) {
struct node* newNode = malloc(sizeof(struct node));
newNode->vertex = v;
newNode->next = NULL;
return newNode;
}

// Creating a graph
struct Graph* createGraph(int vertices) {
struct Graph* graph = malloc(sizeof(struct Graph));
graph->numVertices = vertices;

graph->adjLists = malloc(vertices * sizeof(struct node*));


graph->visited = malloc(vertices * sizeof(int));

int i;
for (i = 0; i < vertices; i++) {
graph->adjLists[i] = NULL;
graph->visited[i] = 0;
}

return graph;
}

// Add edge
void addEdge(struct Graph* graph, int src, int dest) {
// Add edge from src to dest
struct node* newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;

// Add edge from dest to src


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

// Create a queue
struct queue* createQueue() {
struct queue* q = malloc(sizeof(struct queue));
q->front = -1;
q->rear = -1;
return q;
}

// Check if the queue is empty


int isEmpty(struct queue* q) {
if (q->rear == -1)
return 1;
else
return 0;
}

// Adding elements into queue


void enqueue(struct queue* q, int value) {
if (q->rear == SIZE - 1)
printf("\nQueue is Full!!");
else {
if (q->front == -1)
q->front = 0;
q->rear++;
q->items[q->rear] = value;
}
}

// Removing elements from queue


int dequeue(struct queue* q) {
int item;
if (isEmpty(q)) {
printf("Queue is empty");
item = -1;
} else {
item = q->items[q->front];
q->front++;
if (q->front > q->rear) {
printf("Resetting queue ");
q->front = q->rear = -1;
}
}
return item;
}

// Print the queue


void printQueue(struct queue* q) {
int i = q->front;

if (isEmpty(q)) {
printf("Queue is empty");
} else {
printf("\nQueue contains \n");
for (i = q->front; i < q->rear + 1; i++) {
printf("%d ", q->items[i]);
}
}
}

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

bfs(graph, 0);

return 0;
}

(B) DFS
// DFS algorithm in C

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

struct node {
int vertex;
struct node* next;
};

struct node* createNode(int v);

struct Graph {
int numVertices;
int* visited;

// We need int** to store a two dimensional array.


// Similary, we need struct node** to store an array of Linked lists
struct node** adjLists;
};

// DFS algo
void DFS(struct Graph* graph, int vertex) {
struct node* adjList = graph->adjLists[vertex];
struct node* temp = adjList;
graph->visited[vertex] = 1;
printf("Visited %d \n", vertex);

while (temp != NULL) {


int connectedVertex = temp->vertex;

if (graph->visited[connectedVertex] == 0) {
DFS(graph, connectedVertex);
}
temp = temp->next;
}
}

// Create a node
struct node* createNode(int v) {
struct node* newNode = malloc(sizeof(struct node));
newNode->vertex = v;
newNode->next = NULL;
return newNode;
}

// Create graph
struct Graph* createGraph(int vertices) {
struct Graph* graph = malloc(sizeof(struct Graph));
graph->numVertices = vertices;

graph->adjLists = malloc(vertices * sizeof(struct node*));

graph->visited = malloc(vertices * sizeof(int));

int i;
for (i = 0; i < vertices; i++) {
graph->adjLists[i] = NULL;
graph->visited[i] = 0;
}
return graph;
}

// Add edge
void addEdge(struct Graph* graph, int src, int dest) {
// Add edge from src to dest
struct node* newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;

// Add edge from dest to src


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

// Print the graph


void printGraph(struct Graph* graph) {
int v;
for (v = 0; v < graph->numVertices; v++) {
struct node* temp = graph->adjLists[v];
printf("\n Adjacency list of vertex %d\n ", v);
while (temp) {
printf("%d -> ", temp->vertex);
temp = temp->next;
}
printf("\n");
}
}

int main() {
struct Graph* graph = createGraph(4);
addEdge(graph, 0, 1);
addEdge(graph, 0, 2);
addEdge(graph, 1, 2);
addEdge(graph, 2, 3);

printGraph(graph);

DFS(graph, 2);

return 0;
}

You might also like