0% found this document useful (0 votes)
4 views70 pages

DSA Practicals Nayan

The document outlines practical programming exercises for data structures and algorithms, including implementations of average calculation, circular queues, stacks, linear queues, linked lists, and circular linked lists in C. Each section provides code examples and explanations for various operations such as insertion, deletion, and display. The exercises aim to enhance understanding and application of fundamental data structure concepts.

Uploaded by

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

DSA Practicals Nayan

The document outlines practical programming exercises for data structures and algorithms, including implementations of average calculation, circular queues, stacks, linear queues, linked lists, and circular linked lists in C. Each section provides code examples and explanations for various operations such as insertion, deletion, and display. The exercises aim to enhance understanding and application of fundamental data structure concepts.

Uploaded by

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

SHRI VAISHNAV VIDYAPEETH

VISHWAVIDYALAYA
Department of C.S.E

Data structures and algorithms


Practical
Session 2021-22
Guided by – Mr. Shyam Sunder Meena Sir
Submitted by – Nayan Tyagi
Section: B
Subject code: I BTCSE201N
Enrollment no. : 21100BTCS09902
Q 1. To develop a program to find an average of an array using AVG
function.

Answer.
include<stdio.h>
/* Function prototype */
float average(float a[100], int n); int main()
{ float a[100], res; int i, n;

printf("Enter n:\n");
scanf("%d", &n);
/* Reading array */
for(i=0;i< n;i++) {
printf("a[%d]=",i);
scanf("%f", &a[i]);

} /* Function Call */
res = average(a,n);
printf("Average = %f", res);
return 0; }
/* Function definition */
float average(float a[10], int n)
{
int i; float sum=0.0; for(i=0;i< n;i++)
{ sum = sum + a[i];

} return(sum/n); }

Q 3. To implement an algorithm for insert and delete operations of


circular queue and implement the same using array.
Answer
Here, CQueue is a circular queue where to store data. Rear represents the
location in which the data element is to be inserted and Front represents the
location from which the data element is to be removed. Here N is the maximum
size of CQueue and finally, Item is the new item to be added.
Initially Rear = 0 and Front = 0. 1.
If Front = 0 and Rear = 0 then Set Front := 1 and go to step 4
. 2. If Front =1 and Rear = N or Front = Rear + 1 then Print: “Circular Queue
Overflow” and Return
. 3. If Rear = N then Set Rear := 1 and go to step 5
. 4. Set Rear := Rear + 1
5. Set CQueue [Rear] := Item.
6. Return.
Here, CQueue is the place where data are stored. Rear represents the location in
which the data element is to be inserted and Front represents the location from
which the data element is to be removed. Front element is assigned to Item.
Initially,
Front = 1.
1. If Front = 0 then Print: “Circular Queue Underflow” and Return. /*..Delete
without Insertion
2. Set Item := CQueue [Front]
3. If Front = N then Set Front = 1 and Return.
4. If Front = Rear then Set Front = 0 and Rear = 0 and Return.
5. Set Front := Front + 1
6. Return.
Code-
// Circular Queue implementation in C

#include <stdio.h>

#define SIZE 5
int items[SIZE];
int front = -1, rear = -1;

// Check if the queue is full


int isFull() {
if ((front == rear + 1) || (front == 0 && rear == SIZE - 1)) return 1;
return 0; }// Check if the queue is empty
int isEmpty() {
if (front == -1) return 1;
return 0;}
// Adding an element
void enQueue(int element) {
if (isFull())
printf("\n Queue is full!! \n");
else {
if (front == -1) front = 0;
rear = (rear + 1) % SIZE;
items[rear] = element;
printf("\n Inserted -> %d", element);
}
}
// Removing an element
int deQueue() {
int element;
if (isEmpty()) {
printf("\n Queue is empty !! \n");
return (-1);
} else {
element = items[front];
if (front == rear) {
front = -1;
rear = -1;
}
// Q has only one element, so we reset the
// queue after dequeing it. ?
else {
front = (front + 1) % SIZE;
}
printf("\n Deleted element -> %d \n", element);
return (element);
}
}

// Display the queue


void display() {
int i;
if (isEmpty())
printf(" \n Empty Queue\n");
else {
printf("\n Front -> %d ", front);
printf("\n Items -> ");
for (i = front; i != rear; i = (i + 1) % SIZE) {
printf("%d ", items[i]);
}
printf("%d ", items[i]);
printf("\n Rear -> %d \n", rear);
}
}
int main() {
// Fails because front = -1
deQueue();
enQueue(1);
enQueue(2);
enQueue(3);
enQueue(4);
enQueue(5);
// Fails to enqueue because front == 0 && rear == SIZE - 1
enQueue(6);
display();
deQueue();
display();
enQueue(7);
display();
// Fails to enqueue because front == rear + 1
enQueue(8);
return 0;
}
Q 4. Write a menu driven program to implement the push, pop and
display option of the stack with the help of static memory allocation.
Answer.
include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define max 20
int top=-1,s[max];
void push(int n)
{ if(top==max-1)
{ puts("stack is over flown"); return; }
else { top=top+1;
s[top]=n; } }
void pop()
{ int del;
if(top==-1)
{ puts("stack is underflown"); return; }
else { del=s[top];
printf("\n poped element is %d",del); top=top-1; } }
void display()
{ int i; if(top==-1)
puts("stack is empty");
else { for(i=top;i>=0;i--)
printf("\t%d",s[i]); } }
int main() { int opt,n;
do { printf("\n 1.Push");
printf("\n 2.Pop");
printf("\n 3.Display");
printf("\n 4.Exit ");
printf("\n\nEnter your choice :: ");
scanf("%d",&opt);
switch(opt)
{ case 1: printf("\n Enter any element to push :: ");
scanf("%d",&n);
push(n); break;
case 2: pop();
break;
case 3:
display();
break;
case 4:
exit(0); break; }

} while(1); return 0; }
Q.5. Write a menu driven program to implement the push, pop and
display option of the stack with the help of dynamic memory
allocation.

#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
struct list
{
int data;
struct list *link;
}*top=NULL;
void push(int m)
{
struct list *tmp;
tmp=(struct list *)malloc(sizeof(struct list));
tmp->data=m;
tmp->link=NULL;
tmp->link=top;
top=tmp;
}
void pop()
{
struct list *tmp;
if(top==NULL)
printf("\n\nSTACK IS EMPTY");
else
{
tmp=top;
printf("\n\nDELETED IS ELEMENT %d",tmp->data);
top=top->link;
free(tmp);
}
}
void disp()
{
struct list *q;
if(top==NULL)
printf("\nSTACK IS EMPTY");
else
{
q=top;
while(q!=NULL)
{
printf("%d->",q->data);
q=q->link;
}
}
}
void main()
{
int i,n,ch;
do
{
printf("MENU");
printf("\n1.PUSH");
printf("\n2.POP");
printf("\n3.DISPLAY");
printf("\n4.EXIT");
printf("\nENTER UR CHOICE: ");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\nENTER THE NUMBER: ");
scanf("%d",&n);
push(n);
break;
case 2:
pop();
break;
case 3:
printf("\nSTACK ELEMENTS ARE \n");
disp();
break;
case 4:
exit(0);
}
}
while(ch!=4);
getch();
}
Q 6. Write a menu driven program to implementing the various
operations on a linear queue with the help of static memory
allocation.

#include<stdio.h>
#include<stdlib.h>
#define MAX 3
int a[MAX];
int front=-1;
int rear=-1;
void insert();
void del();
void disp();
void main()
{
int ch;

do
{
printf("\nMenu \n");
printf("\n1.INSERT");
printf("\n2.del");
printf("\n3.disp");
printf("\n4.exit");
printf("\nEnter ur choice");
scanf(“%d”,&ch);
switch(ch)
{
case 1:
insert();
break;
case 2:
del();
break;
case 3:
disp();

break;
case 4:
exit(0);
}
}
while(ch!=4);
gets();
}
void insert()
{
int n;
if(rear==MAX-1)
{
printf("Q is Full");
}
else
{
if(front==-1)
{
front=0;
}
else
{
rear++;
printf("\nEnter the Element");
scanf("%d",&n);
a[rear]=n;
}

}
}
void del()
{
if(front==-1)
{
printf("\nQ is Empty");
}
else
{
printf("Deleted Element is %d", a[front]);
front++;
}
}
void disp()
{
int i;
if(front==-1)
{
printf("\nQ is Empty");
}
else
{
for(i=front;i<=rear;i++)
{
printf("%d->",a[i]);
}

Q 7. Write a menu driven program to implementing the various


operations on a linear queue with the help of dynamic memory
allocation.

#include<stdio.h>
#include<stdlib.h>
struct list
{
int data;
struct list *link;
}*front=NULL,*rear=NULL;
void create(int m)
{
struct list *tmp;
tmp=(struct list *)malloc(sizeof(struct list));
tmp->data=m;
tmp->link=NULL;
if(front==NULL)
front=tmp;
else
rear->link=tmp;
rear=tmp;
}
void del()
{
struct list *tmp;
if(front==NULL)
printf("\n\nQUEUE IS FULL");
else
{
tmp=front;
printf("\n\nDELETED IS ELEMENT %d" ,tmp->data);
front=front->link;
free(tmp);
}
}
void disp()
{
struct list *q;
if(front==NULL)
printf("\n\nQUEUE IS EMPTY");
else
{
q=front;
while(q!=NULL)
{
printf("%d==>",q->data);
q=q->link;
}
}
}
void main()
{
int i,n,ch;
clrscr();
do
{
printf("\n\nMENU");
printf("\n\n1.INSERT");
printf("\n\n2.DELETE ");
printf("\n\n3.DISPLAT ");
printf("\n\n4.EXIT");
printf("\n\nENTER UR CHOICE");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\n\nENTER THE NUMBER");
scanf("%d",&n);
create(n);
break;
case 2:
del();
break;
case 3:
printf("\n\nQUEUE ELEMENTS ARE \n\n");
disp();
break;
case 4:
exit(0);
}
}
while(ch!=4);
gets();
}
Q 8. Write a menu driven program to implement various operations
on a linear linked list.

// Linked list operations in C

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

// Create a node
struct Node {
int data;
struct Node* next;
};

// Insert at the beginning


void insertAtBeginning(struct Node** head_ref, int new_data) {
// Allocate memory to a node
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));

// insert the data


new_node->data = new_data;

new_node->next = (*head_ref);

// Move head to new node


(*head_ref) = new_node;
}

// Insert a node after a node


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

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


new_node->data = new_data;
new_node->next = prev_node->next;
prev_node->next = new_node;
}

// Insert the the end


void insertAtEnd(struct Node** head_ref, int new_data) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
struct Node* last = *head_ref; /* used in step 5*/

new_node->data = new_data;
new_node->next = NULL;

if (*head_ref == NULL) {
*head_ref = new_node;
return;
}

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


last->next = new_node;
return;
}

// Delete a node
void deleteNode(struct Node** head_ref, int key) {
struct Node *temp = *head_ref, *prev;

if (temp != NULL && temp->data == key) {


*head_ref = temp->next;
free(temp);
return;
}
// Find the key to be deleted
while (temp != NULL && temp->data != key) {
prev = temp;
temp = temp->next;
}

// If the key is not present


if (temp == NULL) return;
// Remove the node
prev->next = temp->next;

free(temp);
}

// Search a node
int searchNode(struct Node** head_ref, int key) {
struct Node* current = *head_ref;

while (current != NULL) {


if (current->data == key) return 1;
current = current->next;
}
return 0;
}

// Sort the linked list


void sortLinkedList(struct Node** head_ref) {
struct Node *current = *head_ref, *index = NULL;
int temp;

if (head_ref == NULL) {
return;
} else {
while (current != NULL) {
// index points to the node next to current
index = current->next;

while (index != NULL) {


if (current->data > index->data) {
temp = current->data;
current->data = index->data;
index->data = temp;
}
index = index->next;
}
current = current->next;
}
}
}

// Print the linked list


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

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

insertAtEnd(&head, 1);
insertAtBeginning(&head, 2);
insertAtBeginning(&head, 3);
insertAtEnd(&head, 4);
insertAfter(head->next, 5);

printf("Linked list: ");


printList(head);

printf("\nAfter deleting an element: ");


deleteNode(&head, 3);
printList(head);

int item_to_find = 3;
if (searchNode(&head, item_to_find)) {
printf("\n%d is found", item_to_find);
} else {
printf("\n%d is not found", item_to_find);
}

sortLinkedList(&head);
printf("\nSorted List: ");
printList(head);
}

Q 9. Write a menu driven program to implement various operations


on a circular linked list

#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *link;
}*start;
void addlast(int);
void create(int);
void disp();
void addbeg(int);
void main()
{
int ch,n,i,m,a,pos;

start=NULL;
do
{
printf("\n\nMENU\n\n");
printf("\n1.CREATE\n");
printf("\n2.DISPLAY\n");
printf("\n3.ADDBEG\n");
printf("\n4.ADDLAST \n");
printf("\n5.EXIT\n");
printf("\nENTER UR CHOICE\n");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\n\nHOW MANY NODES U WANT TO CREATE\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nENTER THE DATA");
scanf("%d",&m);
create(m);
}
break;
case 2:
disp();
break;
case 5:
exit(0);
case 3:
printf("\nENTER THE VALUE FOR NODE");
scanf("%d",&a);
addbeg(a);
break;
case 4:
printf("\nENTER THE VALUE FOR NODE\n");
scanf("%d",&m);
addlast(m);
break;
}
}
while(ch!=5);
getch();
}
void create(int data)
{
struct node *q,*tmp;
tmp=(struct node *)malloc(sizeof(struct node));
tmp->data=data;
tmp->link=NULL;
if(start==NULL)
{
start=tmp;
}
else
{
q=start;
while(q->link!=NULL)
q=q->link;
q->link=tmp;
}
}
void disp()
{
struct node *q;
if(start==NULL)
{
printf("\n\nLIST IS EMPTY");
}
else
{
q=start;
while(q!=NULL)
{
printf("%d->",q->data);
q=q->link;
}
printf("NULL");
}
}
void addbeg(int data)
{
struct node *tmp;
tmp=(struct node *)malloc(sizeof(struct node ));
tmp->data=data;
tmp->link=start;
start=tmp;
}
void addlast(int data)
{
struct node *q,*tmp;
tmp=(struct node *) malloc(sizeof(struct node));
tmp->data=data;
tmp->link=NULL;
q=start;
while(q->link!=NULL)
q=q->link;
q->link=tmp;
}

Q 10. Program for implementation of Bubble sort


// Bubble sort in C

#include <stdio.h>

// perform the bubble sort


void bubbleSort(int array[], int size) {
// loop to access each array element
for (int step = 0; step < size - 1; ++step) {

// loop to compare array elements


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

// compare two adjacent elements


// change > to < to sort in descending order
if (array[i] > array[i + 1]) {

// swapping occurs if elements


// are not in the intended order
int temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
}
}
}
}

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

int main() {
int data[] = {-2, 45, 0, 11, -9};

// find the array's length


int size = sizeof(data) / sizeof(data[0]);

bubbleSort(data, size);

printf("Sorted Array in Ascending Order:\n");


printArray(data, size);
}

Q 11. Program for Insertion sort 12. Program for Merge 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");

}
/* Driver program to test insertion sort */
int main()
{
int arr[] = { 12, 11, 13, 5, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
insertionSort(arr, n);
printArray(arr, n);
return 0;
}

Q12. Program for Merge Sort

// Merge sort in C

#include <stdio.h>

// Merge two subarrays L and M into arr


void merge(int arr[], int p, int q, int r) {

// Create L ← A[p..q] and M ← A[q+1..r]


int n1 = q - p + 1;
int n2 = r - q;
int L[n1], M[n2];

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


L[i] = arr[p + i];
for (int j = 0; j < n2; j++)
M[j] = arr[q + 1 + j];

// Maintain current index of sub-arrays and main array


int i, j, k;
i = 0;
j = 0;
k = p;

// Until we reach either end of either L or M, pick larger among


// elements L and M and place them in the correct position at A[p..r]
while (i < n1 && j < n2) {
if (L[i] <= M[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = M[j];
j++;
}
k++;
}

// When we run out of elements in either L or M,


// pick up the remaining elements and put in A[p..r]
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}

while (j < n2) {


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

// Divide the array into two subarrays, sort them and merge them
void mergeSort(int arr[], int l, int r) {
if (l < r) {
// m is the point where the array is divided into two subarrays
int m = l + (r - l) / 2;

mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);

// Merge the sorted subarrays


merge(arr, l, m, r);
}
}

// Print the array


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

// Driver program
int main() {
int arr[] = {6, 5, 12, 10, 9, 1};
int size = sizeof(arr) / sizeof(arr[0]);
mergeSort(arr, 0, size - 1);

printf("Sorted array: \n");


printArray(arr, size);
}

Q 13. Program to implement Heap sort

// Heap Sort in C

#include <stdio.h>

// Function to swap the the position of two elements


void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}

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


// Find largest among root, left child and right child
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;

// Swap and continue heapifying if root is not largest


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

// Main function to do heap sort


void heapSort(int arr[], int n) {
// Build max heap
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);

// Heap sort
for (int i = n - 1; i >= 0; i--) {
swap(&arr[0], &arr[i]);

// Heapify root element to get highest element at root again


heapify(arr, i, 0);
}
}

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

// Driver code
int main() {
int arr[] = {1, 12, 9, 5, 6, 10};
int n = sizeof(arr) / sizeof(arr[0]);
heapSort(arr, n);

printf("Sorted array is \n");


printArray(arr, n);
}

14. Program to implement Quick sort

// Quick sort in C

#include <stdio.h>

// function to swap elements


void swap(int *a, int *b) {
int t = *a;
*a = *b;
*b = t;
}

// function to find the partition position


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

// select the rightmost element as pivot


int pivot = array[high];

// pointer for greater element


int i = (low - 1);

// traverse each element of the array


// compare them with the pivot
for (int j = low; j < high; j++) {
if (array[j] <= pivot) {

// if element smaller than pivot is found


// swap it with the greater element pointed by i
i++;

// swap element at i with element at j


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

// swap the pivot element with the greater element at i


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

// return the partition point


return (i + 1);
}

void quickSort(int array[], int low, int high) {


if (low < high) {

// find the pivot element such that


// elements smaller than pivot are on left of pivot
// elements greater than pivot are on right of pivot
int pi = partition(array, low, high);

// recursive call on the left of pivot


quickSort(array, low, pi - 1);

// recursive call on the right of pivot


quickSort(array, pi + 1, high);
}
}

// function to print array elements


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

// main function
int main() {
int data[] = {8, 7, 2, 1, 0, 9, 6};

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

printf("Unsorted Array\n");
printArray(data, n);

// perform quicksort on data


quickSort(data, 0, n - 1);

printf("Sorted array in ascending order: \n");


printArray(data, n);
}

Q 15. Program to Construct a Binary Search Tree and perform


deletion, inorder traversal on it

// Binary Search Tree operations in C

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

struct node {
int key;
struct node *left, *right;
};

// Create a node
struct node *newNode(int item) {
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}

// Inorder Traversal
void inorder(struct node *root) {
if (root != NULL) {
// Traverse left
inorder(root->left);

// Traverse root
printf("%d -> ", root->key);

// Traverse right
inorder(root->right);
}
}

// Insert a node
struct node *insert(struct node *node, int key) {
// Return a new node if the tree is empty
if (node == NULL) return newNode(key);

// Traverse to the right place and insert the node


if (key < node->key)
node->left = insert(node->left, key);
else
node->right = insert(node->right, key);

return node;
}

// Find the inorder successor


struct node *minValueNode(struct node *node) {
struct node *current = node;

// Find the leftmost leaf


while (current && current->left != NULL)
current = current->left;

return current;
}
// Deleting a node
struct node *deleteNode(struct node *root, int key) {
// Return if the tree is empty
if (root == NULL) return root;

// Find the node to be deleted


if (key < root->key)
root->left = deleteNode(root->left, key);
else if (key > root->key)
root->right = deleteNode(root->right, key);

else {
// If the node is 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;
}
// If the node has two children
struct node *temp = minValueNode(root->right);

// Place the inorder successor in position of the node to be deleted


root->key = temp->key;

// Delete the inorder successor


root->right = deleteNode(root->right, temp->key);
}
return root;
}

// Driver code
int main() {
struct node *root = NULL;
root = insert(root, 8);
root = insert(root, 3);
root = insert(root, 1);
root = insert(root, 6);
root = insert(root, 7);
root = insert(root, 10);
root = insert(root, 14);
root = insert(root, 4);
printf("Inorder traversal: ");
inorder(root);

printf("\nAfter deleting 10\n");


root = deleteNode(root, 10);
printf("Inorder traversal: ");
inorder(root);
}
Q 16. To develop an algorithm for binary tree operations and
implement the same.

Search operations-

Algorithm:

Algorithm:
If root == NULL return NULL; If number == root->data return root->data; If
number < root->data return search(root->left) If number > root->data return
search(root->right)

Insert operations-
Algorithm:
If node == NULL return createNode(data) if (data < node->data) node->left =
insert(node->left, data); else if (data > node->data) node->right = insert(node-
>right, data); return node;
Delete operations-
Algorithm:
1.Starting at the root, find the deepest and rightmost node in binary
treeand node which we want to delete.
2.Replace the deepest rightmost node’s data with the node to be deleted.
3.Then delete the deepest rightmost node

// Binary Search Tree operations in C


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

struct node {
int key;
struct node *left, *right;
};

// Create a node
struct node *newNode(int item) {
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}

// Inorder Traversal
void inorder(struct node *root) {
if (root != NULL) {
// Traverse left
inorder(root->left);

// Traverse root
printf("%d -> ", root->key);
// Traverse right
inorder(root->right);
}
}

// Insert a node
struct node *insert(struct node *node, int key) {
// Return a new node if the tree is empty
if (node == NULL) return newNode(key);

// Traverse to the right place and insert the node


if (key < node->key)
node->left = insert(node->left, key);
else
node->right = insert(node->right, key);

return node;
}

// Find the inorder successor


struct node *minValueNode(struct node *node) {
struct node *current = node;

// Find the leftmost leaf


while (current && current->left != NULL)
current = current->left;

return current;
}

// Deleting a node
struct node *deleteNode(struct node *root, int key) {
// Return if the tree is empty
if (root == NULL) return root;

// Find the node to be deleted


if (key < root->key)
root->left = deleteNode(root->left, key);
else if (key > root->key)
root->right = deleteNode(root->right, key);

else {
// If the node is 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;
}

// If the node has two children


struct node *temp = minValueNode(root->right);

// Place the inorder successor in position of the node to be deleted


root->key = temp->key;

// Delete the inorder successor


root->right = deleteNode(root->right, temp->key);
}
return root;
}

// Driver code
int main() {
struct node *root = NULL;
root = insert(root, 8);
root = insert(root, 3);
root = insert(root, 1);
root = insert(root, 6);
root = insert(root, 7);
root = insert(root, 10);
root = insert(root, 14);
root = insert(root, 4);

printf("Inorder traversal: ");


inorder(root);

printf("\nAfter deleting 10\n");


root = deleteNode(root, 10);
printf("Inorder traversal: ");
inorder(root);
}

Q 17. To design an algorithm for sequential search, implement and


test it.

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;
}
// Driver code
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;
}

18. To develop an algorithm for binary search and perform the same.
Answer-

Step 1 : Find the middle element of array. using , middle = initial_value +


end_value / 2 ;
Step 2 : If middle = element, return ‘element found’ and index
Step 3 : if middle > element, call the function with end_value = middle - 1
Step 4 : if middle < element, call the function with start_value = middle + 1 .
Step 5 : exit.

PROGRAM TO IMPLEMENT BINARY SEARCH USING ITERATIVE CALL

#include <stdio.h>
int iterativeBinarySearch(int array[], int start_index, int end_index, int element)
{ while
(start_index <= end_index)
{ int middle = start_index + (end_index- start_index )/2;
if (array[middle] == element)
return middle;
if (array[middle] < element)
start_index = middle + 1;
else
end_index = middle - 1; }
return -1; }
int main(void)
{ int array[] = {1, 4, 7, 9, 16, 56, 70};
int n = 7;
int element = 16;
int found_index = iterativeBinarySearch(array, 0, n-1, element);
if(found_index == -1 )
{ printf("Element not found in the array ");
}
else { printf("Element found at index : %d",found_index);
} return 0; }

PROGRAM TO IMPLEMENT BINARY SEARCH USING RECURSIVE CALL

#include <stdio.h>
int recursiveBinarySearch(int array[], int start_index, int end_index, int element)
{ if (end_index >= start_index){
int middle = start_index + (end_index - start_index )/2;
if (array[middle] == element)
return middle;
if (array[middle] > element)
return recursiveBinarySearch(array, start_index, middle-1, element);
return recursiveBinarySearch(array, middle+1, end_index, element);
} return -1; }
int main(void){ int array[] = {1, 4, 7, 9, 16, 56, 70}; int n = 7;
int element = 9;
int found_index = recursiveBinarySearch(array, 0, n-1, element);
if(found_index == -1 ) { printf("Element not found in the array ");
}
else { printf("Element found at index : %d",found_index);
} return 0; }

You might also like