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

dsa file

Uploaded by

hanishkadabas21
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)
12 views

dsa file

Uploaded by

hanishkadabas21
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/ 70

PANIPAT INSTITUTE OF ENGINEERING AND TECHNOLOGY

Department of
B.TECH CSE – AI & DS

Practical File Record


Of
Data Structure and Algorithm Lab
(PC-CS-AIDS-213LA)

Submitted to: Submitted by:


Ms. Shally DIVYA SHARMA
2023057046
B. Tech CSE (AI&DS)
3rd semester
P.I.E.T DSA LAB

Assessment

Date of Practical
S.

Attendance(1

Performance
No. Name of Practical

Total Marks
File Record
Faculty

Viva (10)
Lab
(10)

(10)

(40)
Sign.

0)
1. Write a program for binary search
method.

2. Write a program for Insertion,


Selection, Bubble sort.
3. Write a program to implement Stack
and its operation

4. Write a program for Quick sort.

5 Write a program for Merge sort.

6. Write a program to implement Queue


and its operation.

7. Write a program to implement


Circular Queue and its operation.

8. Write a program to implement Singly


Linked List for the following
operation: Create, Display, Searching,
Traversing, Deletion.
9 Write a program to implement Doubly
Linked List for the following
operation: Create, Display, Inserting,
Counting, Searching, Traversing and
Deletion.
10 Write a program to implement
Circular Linked List for the following
operation: Create , Display, Inserting,
Counting, Searching, Traversing and
Deletion.
11. Write a program to implement
Insertion, Deletion and Traversing in
B Tree.
Total Marks

Aggregated Marks

Department of B. TECH CSE-AI & DS Page 1 Student Name: DIVYA


P.I.E.T DSA LAB

Practical No. 1

Aim:

Write a program for binary search method.

Objectives:

1. Show how binary search divides the search range into halves, significantly reducing the
number of comparisons.
2. Allow users to input a target element and provide the result of the search.

Key Points:

 Time Complexity: Worst-case time complexity is O (log n)), making it much faster than
linear search for large datasets.
 Flexibility: Can be extended to handle various data types or use recursion instead of
iteration.
 Algorithm Mechanics: Divides the array into halves repeatedly and compares the middle
element with the target to decide which half to continue searching.

Algorithm:
BINARY (DATA,LB,UB,ITEM,LOC)
1. Set BEG =LB,END=UB,MID=INT(BEG+END)/2)
2. Repeat step 3 & 4 while BEG<=END and DATA(MID) ≠ITEM
3. If ITEM <DATA[MID],then:
Set END=MID-1
Else:
Set BEG=MID+1
Set MID=INT (BEG+END)/2
4. If DATA[MID]=ITEM, then:
Set LOC=MID
Else:
Set =LOC=NULL
5. Exit
Source Code:
#include <stdio.h>

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


int low = 0, high = size - 1;

Department of B. TECH CSE-AI & DS Page 2 Student Name: DIVYA


P.I.E.T DSA LAB

while (low <= high) {


int mid = low + (high - low) / 2;

if (arr[mid] == target)
return mid;

if (arr[mid] < target)


low = mid + 1;
else
high = mid - 1;
}

return -1;
}

int main() {
int arr[] = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
int size = sizeof(arr) / sizeof(arr[0]);
int target;

printf("Enter the number to search: ");


scanf("%d", &target);

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

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

return 0;
}

Output:

Department of B. TECH CSE-AI & DS Page 3 Student Name: DIVYA


P.I.E.T DSA LAB

Student Work Sheet


Practical No.1

Aim:

Write a program for binary search method.

Objective:

1. Show how binary search divides the search range into halves, significantly reducing the
number of comparisons.
2. Allow users to input a target element and provide the result of the search.

Requirements:

Compiler , Visual Studio Code , some source code

Output:

Outcomes to be filled by student:


S. No. Outcomes
1. The array must be sorted for binary search to work correctly. If the array is unsorted,
the result is undefined.
2. The binary search function either finds the element and returns its index or returns -1
if the element is not in the array.
3. The program interacts with the user, asking for input (the element to search for) and
displaying the result (either the index or a "not found" message).

Viva Questions:
Q1 : What is the time complexity of the binary search algorithm implemented in this
program?
Ans : The time complexity of the binary search algorithm is O(log n), where n is the size of

Department of B. TECH CSE-AI & DS Page 4 Student Name: DIVYA


P.I.E.T DSA LAB

the array. This is because the search space is halved with each iteration of the loop,
reducing the number of comparisons logarithmically.

Q2 : What does the binarySearch() function return if the target element is found?
Ans : If the target element is found in the array, the binarySearch() function returns the
index of the element within the array.

Q3 : What will happen if the array contains duplicate elements?


Ans : The program will return the index of the first occurrence of the target element, since it
finds the target based on its position in the array.

Q4 : How does the program determine whether to search the left or right half of the array?
Ans : It compares the target with the middle element: if the target is smaller, it searches the
left half; if larger, it searches the right half.

Marks/Grade....................... Signature of Faculty

Department of B. TECH CSE-AI & DS Page 5 Student Name: DIVYA


P.I.E.T DSA LAB

Practical No. 2

Aim:

Write a program for Insertion, Selection, Bubble sort.

Objectives:
1. By implementing multiple sorting algorithms, the program helps reinforce the concepts
of algorithm design and complexity analysis.
2. Through the printArray function, the program shows the array before and after sorting,
making it easy to visualize the effect of each algorithm.
Algorithm:
A. For Insertion Sort:
INSERTION(A,N)
1. Set A[0] = –∞ [Initialize sentinel element]
2. Repeat step 3 to 5 for K = 2, 3, - - - - - - - , N
3. Set Temp = A[K] and PTR = K-1
4. Repeat while Temp < A[PTR]:
a) Set A[PTR + 1] = A[PTR]
b) Set PTR = PTR – 1
5. Set A[PTR + 1] = TEMP [End of step 2 loop]
6. Return

B. For Bubble Sort:


BUBBLE(DATA, N)
1. Repeat step 2 & 3 for K=1 to N-1
2. Set PTR = 1
3. Repeat while PTR <= N-K: [Executes passes]
a) If DATA[PTR] > DATA[PTR+1] then:
Interchange DATA[PTR] and DATA[PTR+1]
[End of If structure]
b) Set PTR = PTR + 1

Department of B. TECH CSE-AI & DS Page 6 Student Name: DIVYA


P.I.E.T DSA LAB

[End of Step 1 outer loop]


4. Exit.

C. For Selection Sort:


Procedure: Algorithm:
MIN(A, K, N, LOC) Selection(A,N)
1. Set Min = A[K] & LOC = K 1.Repeat step 2 &3 for K=1,2,_ _,N-1
2. Repeat for J = K+1, K+2, - - - - -,N 2.Call Min(A,K,N.LOC)
If Min > A[J] then Set Min =A[J] 3.[Interchange A[K] and A[LOC]
and LOC = J Set Temp=A[K],A[K]=A[LOC],
[End of loop] A[LOC]=TEMP
3. Return 4.EXIT

Key Points:
 Space Complexity: All algorithms are in-place, requiring O(1) additional space.
 Input and Output: The program uses a predefined array of integers, prints the unsorted
array, and displays the sorted results for each algorithm.
 Sorting Order: All algorithms sort the array in ascending order..
 Efficiency:All three algorithms have a worst-case time complexity of O(n²).
Source Code:
#include <stdio.h>
// Insertion Sort Function
void insertionSort(int arr[], int size) {
for (int i = 1; i < size; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}

Department of B. TECH CSE-AI & DS Page 7 Student Name: DIVYA


P.I.E.T DSA LAB

arr[j + 1] = key;
}
}
// Selection Sort Function
void selectionSort(int arr[], int size) {
for (int i = 0; i < size - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < size; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
// Bubble Sort Function
void bubbleSort(int arr[], int size) {
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}

Department of B. TECH CSE-AI & DS Page 8 Student Name: DIVYA


P.I.E.T DSA LAB

}
// Function to print the array
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int arr1[] = {64, 25, 12, 22, 11};
int size = sizeof(arr1) / sizeof(arr1[0]);
printf("Original Array: ");
printArray(arr1, size);
// Insertion Sort
insertionSort(arr1, size);
printf("Array after Insertion Sort: ");
printArray(arr1, size);
// Reinitialize the array for other sorts
int arr2[] = {64, 25, 12, 22, 11};
// Selection Sort
selectionSort(arr2, size);
printf("Array after Selection Sort: ");
printArray(arr2, size);
// Reinitialize the array for other sorts
int arr3[] = {64, 25, 12, 22, 11};
// Bubble Sort
bubbleSort(arr3, size);
printf("Array after Bubble Sort: ");

Department of B. TECH CSE-AI & DS Page 9 Student Name: DIVYA


P.I.E.T DSA LAB

printArray(arr3, size);
return 0;
}
Output:

Department of B. TECH CSE-AI & DS Page 10 Student Name: DIVYA


P.I.E.T DSA LAB

Student Work Sheet


Practical No. 2

Aim:

Write a program for Insertion, Selection, Bubble sort.

Objective:
1. By implementing multiple sorting algorithms, the program helps reinforce the concepts
of algorithm design and complexity analysis.
2. Through the printArray function, the program shows the array before and after sorting,
making it easy to visualize the effect of each algorithm.

Requirements:

Compiler , Visual Studio Code, some source code factorial number.

Output:

Outcomes to be filled by student:


S. No. Outcomes
1. Develop an understanding of how algorithms use loops, conditionals, and array
indexing to achieve sorting.
2. Appreciate the importance of choosing the right algorithm based on the dataset size
and structure.
3. Recognize that these algorithms are inefficient for large datasets, motivating the need
for more advanced algorithms like Merge Sort or Quick Sort.

Department of B. TECH CSE-AI & DS Page 11 Student Name: DIVYA


P.I.E.T DSA LAB

Viva Questions:
Q1 : What is the purpose of the program?
Ans : The program demonstrates the implementation of three sorting algorithms: Insertion
Sort, Selection Sort, and Bubble Sort, to sort an array in ascending order

Q2 : What is the time complexity of each sorting algorithm in the worst case?
Ans : The worst-case time complexity of all three algorithms is O(n²).

Q3 : Which sorting algorithm is best suited for nearly sorted arrays?


Ans : Insertion Sort is best suited for nearly sorted arrays because it has a time complexity
of O(n) in the best case.

Q4 : Why are these algorithms inefficient for large datasets?


Ans : These algorithms have a quadratic time complexity (O(n²)) in the worst case, making
them slow for large datasets compared to more efficient algorithms like Merge Sort or
Quick Sort.

Q4 : What happens if the array is already sorted before applying these algorithms?
Ans : Insertion Sort will run in O(n) time, as it makes minimal comparisons and no shifts.

Selection Sort and Bubble Sort will still run in O(n²), as they do not optimize for
sorted array

Marks/Grade....................... Signature of Faculty

Department of B. TECH CSE-AI & DS Page 12 Student Name: DIVYA


P.I.E.T DSA LAB

Practical No.3

Aim:

Write a program to implement stack and its operations.

Algorithm:

STACK-EMPTY(S)

If top[S] = 0

return true

else return false

PUSH(S, x)

top[S] <- top[S] + 1

S[top[S]] <- x

POP(S)

if STACK-EMPTY(S)

then error ”underflow”

else top[S] <- top[S] – 1

return S[top[S] + 1]

Source Code:

#include <stdio.h>

#include <stdlib.h>

#define MAX 100 // Maximum size of the stack

// Structure for Stack

typedef struct {

Department of B. TECH CSE-AI & DS Page 13 Student Name: DIVYA


P.I.E.T DSA LAB

int items[MAX];

int top;

} Stack;

// Function to initialize the stack

void initialize(Stack *s) {

s->top = -1;

// Function to check if the stack is empty

int isEmpty(Stack *s) {

return s->top == -1;

// Function to check if the stack is full

int isFull(Stack *s) {

return s->top == MAX - 1;

// Function to push an element onto the stack

void push(Stack *s, int value) {

if (isFull(s)) {

printf("Stack Overflow! Unable to push %d.\n", value);

return;

s->items[++(s->top)] = value;

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

Department of B. TECH CSE-AI & DS Page 14 Student Name: DIVYA


P.I.E.T DSA LAB

// Function to pop an element from the stack

int pop(Stack *s) {

if (isEmpty(s)) {

printf("Stack Underflow! Unable to pop.\n");

return -1;

return s->items[(s->top)--];

// Function to peek the top element of the stack

int peek(Stack *s) {

if (isEmpty(s)) {

printf("Stack is empty! No top element.\n");

return -1;

return s->items[s->top];

// Function to display the stack

void display(Stack *s) {

if (isEmpty(s)) {

printf("Stack is empty!\n");

return;

Department of B. TECH CSE-AI & DS Page 15 Student Name: DIVYA


P.I.E.T DSA LAB

printf("Stack elements: ");

for (int i = s->top; i >= 0; i--) {

printf("%d ", s->items[i]);

printf("\n");

int main() {

Stack s;

initialize(&s);

int choice, value;

while (1) {

printf("\nStack Operations:\n");

printf("1. Push\n");

printf("2. Pop\n");

printf("3. Peek\n");

printf("4. Display\n");

printf("5. Exit\n");

printf("Enter your choice: ");

scanf("%d", &choice);

switch (choice) {

case 1:

printf("Enter the value to push: ");

scanf("%d", &value);

Department of B. TECH CSE-AI & DS Page 16 Student Name: DIVYA


P.I.E.T DSA LAB

push(&s, value);

break;

case 2:

value = pop(&s);

if (value != -1)

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

break;

case 3:

value = peek(&s);

if (value != -1)

printf("Top element is %d.\n", value);

break;

case 4:

display(&s);

break;

case 5:

printf("Exiting program.\n");

exit(0);

default:

printf("Invalid choice! Please try again.\n");

return 0;

Department of B. TECH CSE-AI & DS Page 17 Student Name: DIVYA


P.I.E.T DSA LAB

Output:

Department of B. TECH CSE-AI & DS Page 18 Student Name: DIVYA


P.I.E.T DSA LAB

Practical No. 4

Aim:

Write a program for Quick sort.

Procedure:
QUICK(A, N, Beg, End, LOC)
1. Set Left = Beg , Right = End, LOC = Beg
2. [Scan right to left]
a) Repeat while A[LOC] <= Right and LOC ≠ Right
Right = Right-1 [End of loop]
b) If LOC = Right, then : Return
c) If A[LOC] > A[Right] then:
i) Temp = A[LOC], A[LOC] = A[Right],
A[Right] = Temp
ii) Set LOC = Right
iii) Go to step 3
3. [Scan from left to right]
a) Repeat while A[Left] <= A[LOC] and Left ≠ LOC
Left = Left + 1 [End of loop]
b) If LOC = Left, then: Return
c) If A[Left] > A[LOC], then:
i)Temp = A[LOC], A[LOC] = A[Left],
A[Left] = Temp
ii) Set LOC = Left
iii) Go to step 2

Algorithm:
1. [Initialize] Top = Null
2. [Push boundary values of A onto stacks when A has 2 or more elements]
If N > 1, then TOP = TOP + 1, LOWER[1] = 1, UPPER[1] = N
3. Repeat step 4 to 7 while Top ≠ Null
4. [Pop sublist from stacks]
Set Beg = LOWER[TOP], End = UPPER[TOP] TOP = TOP – 1
5. Call QUICK(A, N, Beg, End, LOC)
6. [PUSH left sublist onto stacks when it has 2 or more elements]
If Beg < LOC-1 then:

Department of B. TECH CSE-AI & DS Page 19 Student Name: DIVYA


P.I.E.T DSA LAB

Top = TOP+1, LOWER[TOP] = Beg, UPPER[TOP] = LOC-1


7. [PUSH Right Sublist into stack]
If LOC+1 < End then:
TOP = TOP + 1, LOWER[TOP] = LOC+1, UPPER[TOP] = End
8. Exit
Source Code:

#include <stdio.h>

// Function to swap two elements

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

int temp = *a;

*a = *b;

*b = temp;

// Partition function for Quick Sort

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

int pivot = arr[high]; // Choose the last element as the pivot

int i = low - 1; // Index of the smaller element

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

if (arr[j] <= pivot) { // If current element is smaller than or equal to the pivot

i++;

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

Department of B. TECH CSE-AI & DS Page 20 Student Name: DIVYA


P.I.E.T DSA LAB

swap(&arr[i + 1], &arr[high]); // Place the pivot in the correct position

return i + 1; // Return the pivot index

// Quick Sort function

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

if (low < high) {

int pi = partition(arr, low, high); // Partition the array

quickSort(arr, low, pi - 1); // Sort the left subarray

quickSort(arr, pi + 1, high); // Sort the right subarray

// Function to print the array

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

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

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

printf("\n");

int main() {

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

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

printf("Original array: ");

printArray(arr, size);

Department of B. TECH CSE-AI & DS Page 21 Student Name: DIVYA


P.I.E.T DSA LAB

quickSort(arr, 0, size - 1);

printf("Sorted array: ");

printArray(arr, size);

return 0;

Output:

Department of B. TECH CSE-AI & DS Page 22 Student Name: DIVYA


P.I.E.T DSA LAB

Practical No.5

Aim:

Write a program for Merge sort.

Algorithm(2-Way Merge Sort):


MergeSort(AR, low, high)
1. If(low < high) then:
a) Set mid = (low + high)/2
b) MergeSort(ar, low, mid);
c) MergeSort(ar, mid+1, high);
d) Merge(ar, low, mid, high);
2. Exit.
Algorithm:
Merge(AR, low, mid, high)
1. Set i=low, j=mid+1 and k=high
2. Repeat while((i<=mid)&&(j<=high))
3. if(ar[i] <= ar[j]) then
a) Set br[k] = ar[i]
b) Set i=i+1 and k=k+1
[End of if]
[End of loop]
4. Repeat while (I <= mid)
5. Set br[k] = ar[i]
6. Set i=i+1 and k=k+1
[End of loop]
7. Repeat while (j <= high)
8. Set br[k] = ar[j]
9. Set j=j+1 and k=k+1

Department of B. TECH CSE-AI & DS Page 23 Student Name: DIVYA


P.I.E.T DSA LAB

[End of loop]
10. For I = low to high do
11. Set ar[I] = br[I]
12. Exit.
Source Code:
#include <stdio.h>
// Function to merge two subarrays
void merge(int arr[], int left, int mid, int right) {
int n1 = mid - left + 1; // Size of the left subarray
int n2 = right - mid; // Size of the right subarray
int L[n1], R[n2]; // Temporary arrays to hold the subarrays
// Copy data to temporary arrays
for (int i = 0; i < n1; i++)
L[i] = arr[left + i];
for (int j = 0; j < n2; j++)
R[j] = arr[mid + 1 + j];
// Merge the temporary arrays back into the original array
int 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++;
}
// Copy remaining elements of L[], if any

Department of B. TECH CSE-AI & DS Page 24 Student Name: DIVYA


P.I.E.T DSA LAB

while (i < n1) {


arr[k] = L[i];
i++;
k++;
}
// Copy remaining elements of R[], if any
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
// Merge Sort function
void mergeSort(int arr[], int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2; // Calculate the midpoint
// Recursively sort the left and right halves
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
// Merge the sorted halves
merge(arr, left, mid, right);
}
}
// Function to print the array
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");

Department of B. TECH CSE-AI & DS Page 25 Student Name: DIVYA


P.I.E.T DSA LAB

}
int main() {
int arr[] = {12, 11, 13, 5, 6, 7};
int size = sizeof(arr) / sizeof(arr[0]);
printf("Original array: ");
printArray(arr, size);
mergeSort(arr, 0, size - 1);
printf("Sorted array: ");
printArray(arr, size);
return 0;
}
Output:

Department of B. TECH CSE-AI & DS Page 26 Student Name: DIVYA


P.I.E.T DSA LAB

Practical No.6

Aim:

Write a program to implement Queue and its operation

Algorithm:

ENQUEUE(Q, x)

Q[tail[Q]] <- x

if tail[Q] = length[Q]

then tail[Q] <- 1

else tail[Q] <- tail[Q] + 1

DEQUEUE(Q)

x <- Q[head[Q]]

if head[Q] = length[Q]

then head[Q] <- 1

else head[Q] <- head[Q] + 1

return x
Source Code:
#include <stdio.h>
#include <stdlib.h>
#define MAX 100 // Maximum size of the queue

// Structure for Queue


typedef struct {
int items[MAX];
int front, rear;
} Queue;

// Function to initialize the queue


void initialize(Queue *q) {
q->front = -1;
q->rear = -1;
}

Department of B. TECH CSE-AI & DS Page 27 Student Name: DIVYA


P.I.E.T DSA LAB

// Function to check if the queue is empty


int isEmpty(Queue *q) {
return q->front == -1;
}

// Function to check if the queue is full


int isFull(Queue *q) {
return q->rear == MAX - 1;
}

// Function to enqueue (add) an element to the queue


void enqueue(Queue *q, int value) {
if (isFull(q)) {
printf("Queue Overflow! Unable to enqueue %d.\n", value);
return;
}
if (isEmpty(q)) {
q->front = 0;
}
q->items[++(q->rear)] = value;
printf("Enqueued %d to the queue.\n", value);
}

// Function to dequeue (remove) an element from the queue


int dequeue(Queue *q) {
if (isEmpty(q)) {
printf("Queue Underflow! Unable to dequeue.\n");
return -1;
}
int value = q->items[q->front];
if (q->front == q->rear) { // If there is only one element left
q->front = q->rear = -1;
} else {
q->front++;
}
return value;
}

// Function to peek at the front element of the queue


int peek(Queue *q) {
if (isEmpty(q)) {
printf("Queue is empty! No front element.\n");
return -1;
}
return q->items[q->front];

Department of B. TECH CSE-AI & DS Page 28 Student Name: DIVYA


P.I.E.T DSA LAB

// Function to display the queue


void display(Queue *q) {
if (isEmpty(q)) {
printf("Queue is empty!\n");
return;
}
printf("Queue elements: ");
for (int i = q->front; i <= q->rear; i++) {
printf("%d ", q->items[i]);
}
printf("\n");
}

int main() {
Queue q;
initialize(&q);
int choice, value;

while (1) {
printf("\nQueue Operations:\n");
printf("1. Enqueue\n");
printf("2. Dequeue\n");
printf("3. Peek\n");
printf("4. Display\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter the value to enqueue: ");
scanf("%d", &value);
enqueue(&q, value);
break;
case 2:
value = dequeue(&q);
if (value != -1)
printf("Dequeued %d from the queue.\n", value);
break;
case 3:
value = peek(&q);
if (value != -1)
printf("Front element is %d.\n", value);
break;

Department of B. TECH CSE-AI & DS Page 29 Student Name: DIVYA


P.I.E.T DSA LAB

case 4:
display(&q);
break;
case 5:
printf("Exiting program.\n");
exit(0);
default:
printf("Invalid choice! Please try again.\n");
}
}
return 0;
}
Output:

Department of B. TECH CSE-AI & DS Page 30 Student Name: DIVYA


P.I.E.T DSA LAB

Practical No.7

Aim:

Write a program to implement Circular Queue and its operation.

Algorithm:

add_circular( item,queue,rear,front)

{ rear=(rear+1)mod n;

if (front == rear)

then print " queue is full "

else { queue [rear]=item;}

delete_circular (item,queue,rear,front)

{ if (front = = rear)

print ("queue is empty");

else { front= front+1;

item=queue[front]; }

}
Source Code:
#include <stdio.h>
#include <stdlib.h>
#define MAX 5 // Maximum size of the circular queue
// Structure for Circular Queue
typedef struct {
int items[MAX];
int front, rear;
} CircularQueue;
// Function to initialize the circular queue
void initialize(CircularQueue *q) {
q->front = -1;

Department of B. TECH CSE-AI & DS Page 31 Student Name: DIVYA


P.I.E.T DSA LAB

q->rear = -1;
}
// Function to check if the circular queue is empty
int isEmpty(CircularQueue *q) {
return q->front == -1;
}
// Function to check if the circular queue is full
int isFull(CircularQueue *q) {
return (q->rear + 1) % MAX == q->front;
}
// Function to enqueue (add) an element to the circular queue
void enqueue(CircularQueue *q, int value) {
if (isFull(q)) {
printf("Circular Queue Overflow! Unable to enqueue %d.\n", value);
return;
}
if (isEmpty(q)) {
q->front = 0;
}
q->rear = (q->rear + 1) % MAX;
q->items[q->rear] = value;
printf("Enqueued %d to the circular queue.\n", value);
}

// Function to dequeue (remove) an element from the circular queue


int dequeue(CircularQueue *q) {
if (isEmpty(q)) {
printf("Circular Queue Underflow! Unable to dequeue.\n");
return -1;
}
int value = q->items[q->front];
if (q->front == q->rear) { // If there is only one element left
q->front = q->rear = -1;
} else {
q->front = (q->front + 1) % MAX;
}
return value;
}

// Function to peek at the front element of the circular queue

Department of B. TECH CSE-AI & DS Page 32 Student Name: DIVYA


P.I.E.T DSA LAB

int peek(CircularQueue *q) {


if (isEmpty(q)) {
printf("Circular Queue is empty! No front element.\n");
return -1;
}
return q->items[q->front];
}

// Function to display the circular queue


void display(CircularQueue *q) {
if (isEmpty(q)) {
printf("Circular Queue is empty!\n");
return;
}
printf("Circular Queue elements: ");
int i = q->front;
while (1) {
printf("%d ", q->items[i]);
if (i == q->rear) break;
i = (i + 1) % MAX;
}
printf("\n");
}

int main() {
CircularQueue q;
initialize(&q);
int choice, value;

while (1) {
printf("\nCircular Queue Operations:\n");
printf("1. Enqueue\n");
printf("2. Dequeue\n");
printf("3. Peek\n");
printf("4. Display\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {

Department of B. TECH CSE-AI & DS Page 33 Student Name: DIVYA


P.I.E.T DSA LAB

case 1:
printf("Enter the value to enqueue: ");
scanf("%d", &value);
enqueue(&q, value);
break;
case 2:
value = dequeue(&q);
if (value != -1)
printf("Dequeued %d from the circular queue.\n", value);
break;
case 3:
value = peek(&q);
if (value != -1)
printf("Front element is %d.\n", value);
break;
case 4:
display(&q);
break;
case 5:
printf("Exiting program.\n");
exit(0);
default:
printf("Invalid choice! Please try again.\n");
}
}
return 0;
}

Department of B. TECH CSE-AI & DS Page 34 Student Name: DIVYA


P.I.E.T DSA LAB

Output:

Department of B. TECH CSE-AI & DS Page 35 Student Name: DIVYA


P.I.E.T DSA LAB

Practical No. 8

Aim:

Write a program to implement Singly Linked List for the following operation: Create, Display,
Searching, Traversing, Deletion.

Procedure:

Linked list is a data structure with the following specifics::

1. Data is dynamically added or removed.

2. Every data object has two parts-a data part and a link part. Together they constitute a node.

3. The list can be traversed only through pointers.

4. Every node is an important constituent of the data.

5. The end of the data is always a leaf end.

6. Tree structures (branched link lists) are used to store data into disks.
Source Code:
#include <stdio.h>
#include <stdlib.h>
// Node structure for the singly linked list
typedef struct Node {
int data;
struct Node *next;
} Node;
// Function to create a new node
Node* createNode(int value) {
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->next = NULL;
return newNode;

Department of B. TECH CSE-AI & DS Page 36 Student Name: DIVYA


P.I.E.T DSA LAB

}
// Function to create a singly linked list
void create(Node **head, int value) {
Node *newNode = createNode(value);
if (*head == NULL) {
*head = newNode;
} else {
Node *temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
printf("Node with value %d created.\n", value);
}
// Function to display the linked list
void display(Node *head) {
if (head == NULL) {
printf("The list is empty.\n");
return;
}
printf("Linked List: ");
while (head != NULL) {
printf("%d -> ", head->data);
head = head->next;
}
printf("NULL\n");
}

Department of B. TECH CSE-AI & DS Page 37 Student Name: DIVYA


P.I.E.T DSA LAB

// Function to search for a value in the linked list


void search(Node *head, int key) {
int position = 0;
while (head != NULL) {
if (head->data == key) {
printf("Element %d found at position %d.\n", key, position);
return;
}
head = head->next;
position++;
}
printf("Element %d not found in the list.\n", key);
}
// Function to traverse and display elements in the linked list
void traverse(Node *head) {
if (head == NULL) {
printf("The list is empty. No elements to traverse.\n");
return;
}
printf("Traversing the list: ");
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
// Function to delete a node from the linked list
void deleteNode(Node **head, int key) {

Department of B. TECH CSE-AI & DS Page 38 Student Name: DIVYA


P.I.E.T DSA LAB

Node *temp = *head, *prev = NULL;


// Check if the head node is to be deleted
if (temp != NULL && temp->data == key) {
*head = temp->next;
free(temp);
printf("Element %d deleted from the list.\n", key);
return;
}
// Search for the key to delete
while (temp != NULL && temp->data != key) {
prev = temp;
temp = temp->next;
}
// If the key is not found
if (temp == NULL) {
printf("Element %d not found in the list.\n", key);
return;
}
// Unlink the node and free memory
prev->next = temp->next;
free(temp);
printf("Element %d deleted from the list.\n", key);
}
int main() {
Node *head = NULL;
int choice, value, key;
while (1) {
printf("\nSingly Linked List Operations:\n");

Department of B. TECH CSE-AI & DS Page 39 Student Name: DIVYA


P.I.E.T DSA LAB

printf("1. Create Node\n");


printf("2. Display List\n");
printf("3. Search Element\n");
printf("4. Traverse List\n");
printf("5. Delete Node\n");
printf("6. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter value to create a node: ");
scanf("%d", &value);
create(&head, value);
break;
case 2:
display(head);
break;
case 3:
printf("Enter value to search: ");
scanf("%d", &key);
search(head, key);
break;
case 4:
traverse(head);
break;
case 5:
printf("Enter value to delete: ");
scanf("%d", &key);

Department of B. TECH CSE-AI & DS Page 40 Student Name: DIVYA


P.I.E.T DSA LAB

deleteNode(&head, key);
break;
case 6:
printf("Exiting program.\n");
exit(0);
default:
printf("Invalid choice! Please try again.\n");
}
}
return 0;
}
Output:

Department of B. TECH CSE-AI & DS Page 41 Student Name: DIVYA


P.I.E.T DSA LAB

Practical No. 9

Aim:

Write a program to implement Doubly Linked List for the following operation: Create, Display,
Inserting, Counting, Searching, Traversing and Deletion.

Procedure:

Linked list is a data structure with the following specifics::

1. Data is dynamically added or removed.

2. Every data object has two parts-a data part and a link part. Together they constitute node.

3. The list can be traversed only through pointers.

4. Every node is an important constituent of the data.

5. The end of the data is always a leaf end.

6. Tree structures (branched link lists) are used to store data into disks.
Source Code:
#include <stdio.h>
#include <stdlib.h>
// Node structure for doubly linked list
typedef struct Node {
int data;
struct Node *prev;
struct Node *next;
} Node;
// Function to create a new node
Node* createNode(int value) {
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->prev = NULL;

Department of B. TECH CSE-AI & DS Page 42 Student Name: DIVYA


P.I.E.T DSA LAB

newNode->next = NULL;
return newNode;
}
// Function to create a doubly linked list
void create(Node **head, int value) {
Node *newNode = createNode(value);
if (*head == NULL) {
*head = newNode;
} else {
Node *temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
newNode->prev = temp;
}
printf("Node with value %d created.\n", value);
}
// Function to display the doubly linked list
void display(Node *head) {
if (head == NULL) {
printf("The list is empty.\n");
return;
}
printf("Doubly Linked List: ");
while (head != NULL) {
printf("%d <-> ", head->data);
head = head->next;
}

Department of B. TECH CSE-AI & DS Page 43 Student Name: DIVYA


P.I.E.T DSA LAB

printf("NULL\n");
}
// Function to insert a node at the beginning
void insertAtBeginning(Node **head, int value) {
Node *newNode = createNode(value);
if (*head == NULL) {
*head = newNode;
} else {
newNode->next = *head;
(*head)->prev = newNode;
*head = newNode;
}
printf("Node with value %d inserted at the beginning.\n", value);
}
// Function to count the number of nodes in the doubly linked list
int count(Node *head) {
int count = 0;
while (head != NULL) {
count++;
head = head->next;
}
return count;
}
// Function to search for an element in the doubly linked list
void search(Node *head, int key) {
int position = 0;
while (head != NULL) {
if (head->data == key) {
printf("Element %d found at position %d.\n", key, position);

Department of B. TECH CSE-AI & DS Page 44 Student Name: DIVYA


P.I.E.T DSA LAB

return;
}
head = head->next;
position++;
}
printf("Element %d not found in the list.\n", key);
}
// Function to traverse the doubly linked list
void traverse(Node *head) {
if (head == NULL) {
printf("The list is empty. No elements to traverse.\n");
return;
}
printf("Traversing the list: ");
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
// Function to delete a node from the doubly linked list
void deleteNode(Node **head, int key) {
Node *temp = *head;
// If the list is empty
if (*head == NULL) {
printf("The list is empty. No nodes to delete.\n");
return;
}

Department of B. TECH CSE-AI & DS Page 45 Student Name: DIVYA


P.I.E.T DSA LAB

// Check if the node to be deleted is the first node


if (temp != NULL && temp->data == key) {
*head = temp->next; // Change head
if (*head != NULL) {
(*head)->prev = NULL;
}
free(temp);
printf("Node with value %d deleted from the list.\n", key);
return;
}
// Search for the node to be deleted
while (temp != NULL && temp->data != key) {
temp = temp->next;
}
// If the key was not found
if (temp == NULL) {
printf("Element %d not found in the list.\n", key);
return;
}
// Unlink the node from the doubly linked list
if (temp->next != NULL) {
temp->next->prev = temp->prev;
}
if (temp->prev != NULL) {
temp->prev->next = temp->next;
}
free(temp);
printf("Node with value %d deleted from the list.\n", key);
}

Department of B. TECH CSE-AI & DS Page 46 Student Name: DIVYA


P.I.E.T DSA LAB

int main() {
Node *head = NULL;
int choice, value, key;
while (1) {
printf("\nDoubly Linked List Operations:\n");
printf("1. Create Node\n");
printf("2. Display List\n");
printf("3. Insert at Beginning\n");
printf("4. Count Nodes\n");
printf("5. Search Element\n");
printf("6. Traverse List\n");
printf("7. Delete Node\n");
printf("8. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter value to create a node: ");
scanf("%d", &value);
create(&head, value);
break;
case 2:
display(head);
break;
case 3:
printf("Enter value to insert at the beginning: ");
scanf("%d", &value);
insertAtBeginning(&head, value);
break;

Department of B. TECH CSE-AI & DS Page 47 Student Name: DIVYA


P.I.E.T DSA LAB

case 4:
printf("Total nodes: %d\n", count(head));
break;
case 5:
printf("Enter value to search: ");
scanf("%d", &key);
search(head, key);
break;
case 6:
traverse(head);
break;
case 7:
printf("Enter value to delete: ");
scanf("%d", &key);
deleteNode(&head, key);
break;
case 8:
printf("Exiting program.\n");
exit(0);
default:
printf("Invalid choice! Please try again.\n");
}
}
return 0;
}

Department of B. TECH CSE-AI & DS Page 48 Student Name: DIVYA


P.I.E.T DSA LAB

Output:

Department of B. TECH CSE-AI & DS Page 49 Student Name: DIVYA


P.I.E.T DSA LAB

Practical No. 10

Aim:

Write a program to implement Circular Linked List for the following operation: Create, Display,
Inserting, Counting, Searching, Traversing and Deletion.

Procedure:
Linked list is a data structure with the following specifics::
1. Data is dynamically added or removed.
2. Every data object has two parts-a data part and a link part. Together they constitute node.
3. The list can be traversed only through pointers.
4. Every node is an important constituent of the data.
5. The end of the data is always a leaf end.
6. Tree structures (branched link lists) are used to store data into disks.
Source Code:
#include <stdio.h>
#include <stdlib.h>
// Node structure for Circular Linked List
typedef struct Node {
int data;
struct Node *next;
} Node;
// Function to create a new node
Node* createNode(int value) {
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->next = NULL;
return newNode;
}

Department of B. TECH CSE-AI & DS Page 50 Student Name: DIVYA


P.I.E.T DSA LAB

// Function to create and append a node to the circular linked list


void create(Node **head, int value) {
Node *newNode = createNode(value);
if (*head == NULL) {
*head = newNode;
newNode->next = *head; // Pointing to itself to form the circular link
} else {
Node *temp = *head;
while (temp->next != *head) {
temp = temp->next;
}
temp->next = newNode;
newNode->next = *head;
}
printf("Node with value %d created.\n", value);
}
// Function to display the entire circular linked list
void display(Node *head) {
if (head == NULL) {
printf("The list is empty.\n");
return;
}
Node *temp = head;
printf("Circular Linked List: ");
do {
printf("%d -> ", temp->data);
temp = temp->next;
} while (temp != head);

Department of B. TECH CSE-AI & DS Page 51 Student Name: DIVYA


P.I.E.T DSA LAB

printf("(back to head)\n");
}
// Function to insert a node at the beginning
void insertAtBeginning(Node **head, int value) {
Node *newNode = createNode(value);
if (*head == NULL) {
*head = newNode;
newNode->next = *head;
} else {
Node *temp = *head;
while (temp->next != *head) {
temp = temp->next;
}
newNode->next = *head;
*head = newNode;
temp->next = *head;
}
printf("Node with value %d inserted at the beginning.\n", value);
}
// Function to insert a node at the end
void insertAtEnd(Node **head, int value) {
Node *newNode = createNode(value);
if (*head == NULL) {
*head = newNode;
newNode->next = *head;
} else {
Node *temp = *head;
while (temp->next != *head) {

Department of B. TECH CSE-AI & DS Page 52 Student Name: DIVYA


P.I.E.T DSA LAB

temp = temp->next;
}
temp->next = newNode;
newNode->next = *head;
}
printf("Node with value %d inserted at the end.\n", value);
}
// Function to count the number of nodes in the circular linked list
int count(Node *head) {
int count = 0;
if (head != NULL) {
Node *temp = head;
do {
count++;
temp = temp->next;
} while (temp != head);
}
return count;
}
// Function to search for an element in the circular linked list
void search(Node *head, int key) {
int position = 0;
if (head != NULL) {
Node *temp = head;
do {
if (temp->data == key) {
printf("Element %d found at position %d.\n", key, position);
return;

Department of B. TECH CSE-AI & DS Page 53 Student Name: DIVYA


P.I.E.T DSA LAB

}
temp = temp->next;
position++;
} while (temp != head);
}
printf("Element %d not found in the list.\n", key);
}
// Function to traverse the list
void traverse(Node *head) {
if (head == NULL) {
printf("The list is empty. No elements to traverse.\n");
return;
}
Node *temp = head;
printf("Traversing the list: ");
do {
printf("%d ", temp->data);
temp = temp->next;
} while (temp != head);
printf("\n");
}
// Function to delete a node from the circular linked list
void deleteNode(Node **head, int key) {
if (*head == NULL) {
printf("The list is empty. No nodes to delete.\n");
return;
}

Department of B. TECH CSE-AI & DS Page 54 Student Name: DIVYA


P.I.E.T DSA LAB

Node *temp = *head;


// If the node to be deleted is the only node
if (temp->data == key && temp->next == *head) {
free(temp);
*head = NULL;
printf("Node with value %d deleted from the list.\n", key);
return;
}
// If the head node is to be deleted
if (temp->data == key) {
Node *last = *head;
while (last->next != *head) {
last = last->next;
}
*head = temp->next;
last->next = *head;
free(temp);
printf("Node with value %d deleted from the list.\n", key);
return;
}
// Search for the node to be deleted
Node *prev = NULL;
while (temp->data != key && temp->next != *head) {
prev = temp;
temp = temp->next;
}

// If the key was not found

Department of B. TECH CSE-AI & DS Page 55 Student Name: DIVYA


P.I.E.T DSA LAB

if (temp->data != key) {
printf("Element %d not found in the list.\n", key);
return;
}
// Unlink the node and free memory
prev->next = temp->next;
free(temp);
printf("Node with value %d deleted from the list.\n", key);
}
int main() {
Node *head = NULL;
int choice, value, key;
while (1) {
printf("\nCircular Linked List Operations:\n");
printf("1. Create Node\n");
printf("2. Display List\n");
printf("3. Insert at Beginning\n");
printf("4. Insert at End\n");
printf("5. Count Nodes\n");
printf("6. Search Element\n");
printf("7. Traverse List\n");
printf("8. Delete Node\n");
printf("9. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter value to create a node: ");

Department of B. TECH CSE-AI & DS Page 56 Student Name: DIVYA


P.I.E.T DSA LAB

scanf("%d", &value);
create(&head, value);
break;
case 2:
display(head);
break;
case 3:
printf("Enter value to insert at the beginning: ");
scanf("%d", &value);
insertAtBeginning(&head, value);
break;
case 4:
printf("Enter value to insert at the end: ");
scanf("%d", &value);
insertAtEnd(&head, value);
break;
case 5:
printf("Total nodes: %d\n", count(head));
break;
case 6:
printf("Enter value to search: ");
scanf("%d", &key);
search(head, key);
break;
case 7:
traverse(head);
break;
case 8:

Department of B. TECH CSE-AI & DS Page 57 Student Name: DIVYA


P.I.E.T DSA LAB

printf("Enter value to delete: ");


scanf("%d", &key);
deleteNode(&head, key);
break;
case 9:
printf("Exiting program.\n");
exit(0);
default:
printf("Invalid choice! Please try again.\n");
}
}
return 0;
}
Output:

Department of B. TECH CSE-AI & DS Page 58 Student Name: DIVYA


P.I.E.T DSA LAB

Practical No. 11
Aim:
Write a program to implement Insertion, Deletion and Traversing in B Tree.

Algorithm:

 Insertion

1. Start at the root.

2. If the root is full, split it and create a new root.

3. Perform a recursive insert:

a) Find the child that should receive the new key.

b) If the child is full, split it.

c) Recursively insert the key into the appropriate child.

 Deletion

1. Start at the root.

2. Perform a recursive delete:

a) If the key is in the current node:

- If the node is a leaf, remove the key.

- If the node is an internal node:

- If the child preceding the key has at least `t` keys, replace the key with its predecessor and
recursively delete the predecessor.

- If the child has fewer than `t` keys:

- If the succeeding child has at least `t` keys, replace the key with its successor and recursively
delete the successor.

- If both the child and its succeeding sibling have `t-1` keys, merge them.

b) If the key is not in the current node:

Department of B. TECH CSE-AI & DS Page 59 Student Name: DIVYA


P.I.E.T DSA LAB

- If the current node is a leaf, the key is not in the tree.

- If the current node is an internal node:

- Determine the child that must contain the key, and recursively delete it.

3. Handle underflow conditions: -

If the root is empty, set it to its only child.

- If a non-root internal node has fewer than `t-1` keys:

- Borrow a key from its preceding or succeeding sibling if the sibling has at least `t` keys.

- Merge the node with one of its siblings if both siblings have only `t-1` keys.

4. Repeat the process until the key is deleted or determined not to be in the tree.

 Traversing

1. Start at the root.

2. Traverse each key in the node:

a. If it's an internal node, recursively traverse its child.

b. If it's a leaf, process the key.

3. Continue the process for each child of the node.


Source Code:
#include <stdio.h>
#include <stdlib.h>
#define MIN_DEGREE 2
// A BTree node
typedef struct BTreeNode {
int *keys; // Array of keys
int t; // Minimum degree (defines the range for number of keys)
struct BTreeNode **children; // Array of child pointers
int n; // Current number of keys

Department of B. TECH CSE-AI & DS Page 60 Student Name: DIVYA


P.I.E.T DSA LAB

int leaf; // 1 if leaf node, 0 if not


} BTreeNode;

// Function to create a new B-tree node


BTreeNode* createNode(int t, int leaf) {
BTreeNode *newNode = (BTreeNode*)malloc(sizeof(BTreeNode));
newNode->t = t;
newNode->leaf = leaf;
newNode->keys = (int*)malloc((2 * t - 1) * sizeof(int));
newNode->children = (BTreeNode**)malloc(2 * t * sizeof(BTreeNode*));
newNode->n = 0;
return newNode;
}
// Function to traverse the tree in in-order
void traverse(BTreeNode *root) {
if (root != NULL) {
int i;
for (i = 0; i < root->n; i++) {
if (!root->leaf)
traverse(root->children[i]);
printf("%d ", root->keys[i]);
}
if (!root->leaf)
traverse(root->children[i]);
}
}
// Function to insert a key in a non-full node
void insertNonFull(BTreeNode *node, int key) {

Department of B. TECH CSE-AI & DS Page 61 Student Name: DIVYA


P.I.E.T DSA LAB

int i = node->n - 1;
if (node->leaf) {
while (i >= 0 && node->keys[i] > key) {
node->keys[i + 1] = node->keys[i];
i--;
}
node->keys[i + 1] = key;
node->n++;
} else {
while (i >= 0 && node->keys[i] > key)
i--;

i++;
if (node->children[i]->n == 2 * node->t - 1) {
splitChild(node, i);
if (node->keys[i] < key)
i++;
}
insertNonFull(node->children[i], key);
}
}
// Function to split a child of a node
void splitChild(BTreeNode *parent, int i) {
int t = parent->t;
BTreeNode *y = parent->children[i];
BTreeNode *z = createNode(t, y->leaf);
int j;
z->n = t - 1;

Department of B. TECH CSE-AI & DS Page 62 Student Name: DIVYA


P.I.E.T DSA LAB

for (j = 0; j < t - 1; j++)


z->keys[j] = y->keys[j + t];
if (!y->leaf) {
for (j = 0; j < t; j++)
z->children[j] = y->children[j + t];
}
y->n = t - 1;
for (j = parent->n; j > i; j--)
parent->children[j + 1] = parent->children[j];
parent->children[i + 1] = z;
for (j = parent->n - 1; j >= i; j--)
parent->keys[j + 1] = parent->keys[j];
parent->keys[i] = y->keys[t - 1];
parent->n++;
}
// Function to insert a key into the B-tree
void insert(BTreeNode **root, int key) {
BTreeNode *r = *root;
if (r->n == 2 * r->t - 1) {
BTreeNode *s = createNode(r->t, 0);
s->children[0] = r;
*root = s;
splitChild(s, 0);
insertNonFull(s, key);
} else {
insertNonFull(r, key);
}
}

Department of B. TECH CSE-AI & DS Page 63 Student Name: DIVYA


P.I.E.T DSA LAB

// Function to find the predecessor of a key


int getPredecessor(BTreeNode *x, int i) {
BTreeNode *current = x->children[i];
while (!current->leaf)
current = current->children[current->n];
return current->keys[current->n - 1];
}
// Function to find the successor of a key
int getSuccessor(BTreeNode *x, int i) {
BTreeNode *current = x->children[i + 1];
while (!current->leaf)
current = current->children[0];
return current->keys[0];
}
// Function to delete a key from a node
void deleteKey(BTreeNode *x, int key) {
int i = 0;
while (i < x->n && key > x->keys[i])
i++;
if (i < x->n && key == x->keys[i]) {
if (x->leaf) {
for (int j = i + 1; j < x->n; j++)
x->keys[j - 1] = x->keys[j];
x->n--;
} else {
BTreeNode *leftChild = x->children[i];
BTreeNode *rightChild = x->children[i + 1];
if (leftChild->n >= x->t) {

Department of B. TECH CSE-AI & DS Page 64 Student Name: DIVYA


P.I.E.T DSA LAB

int pred = getPredecessor(x, i);


x->keys[i] = pred;
deleteKey(leftChild, pred);
} else if (rightChild->n >= x->t) {
int succ = getSuccessor(x, i);
x->keys[i] = succ;
deleteKey(rightChild, succ);
} else {
merge(x, i);
deleteKey(leftChild, key);
}
}
} else {
if (x->leaf) {
printf("Key %d not found.\n", key);
return;
}
int flag = (i == x->n);
if (x->children[i]->n < x->t)
fill(x, i);
if (flag && i > x->n)
deleteKey(x->children[i - 1], key);
else
deleteKey(x->children[i], key);
}
}
// Function to merge two child nodes
void merge(BTreeNode *x, int i) {

Department of B. TECH CSE-AI & DS Page 65 Student Name: DIVYA


P.I.E.T DSA LAB

BTreeNode *leftChild = x->children[i];


BTreeNode *rightChild = x->children[i + 1];
int t = x->t;
leftChild->keys[t - 1] = x->keys[i];
for (int j = 0; j < rightChild->n; j++)
leftChild->keys[t + j] = rightChild->keys[j];
if (!leftChild->leaf) {
for (int j = 0; j <= rightChild->n; j++)
leftChild->children[t + j] = rightChild->children[j];
}
for (int j = i + 1; j < x->n; j++)
x->keys[j - 1] = x->keys[j];
for (int j = i + 2; j <= x->n; j++)
x->children[j - 1] = x->children[j];
leftChild->n += rightChild->n + 1;
x->n--;
free(rightChild);
}
// Function to fill a child node if it has less than t keys
void fill(BTreeNode *x, int i) {
if (i > 0 && x->children[i - 1]->n >= x->t)
borrowFromPrev(x, i);
else if (i < x->n && x->children[i + 1]->n >= x->t)
borrowFromNext(x, i);
else {
if (i < x->n)
merge(x, i);
else

Department of B. TECH CSE-AI & DS Page 66 Student Name: DIVYA


P.I.E.T DSA LAB

merge(x, i - 1);
}
}
// Function to borrow a key from the previous sibling
void borrowFromPrev(BTreeNode *x, int i) {
BTreeNode *child = x->children[i];
BTreeNode *sibling = x->children[i - 1];
for (int j = child->n - 1; j >= 0; j--)
child->keys[j + 1] = child->keys[j];
if (!child->leaf) {
for (int j = child->n; j >= 0; j--)
child->children[j + 1] = child->children[j];
}
child->keys[0] = x->keys[i - 1];
if (!x->leaf)
child->children[0] = sibling->children[sibling->n];
x->keys[i - 1] = sibling->keys[sibling->n - 1];
child->n++;
sibling->n--;
}
// Function to borrow a key from the next sibling
void borrowFromNext(BTreeNode *x, int i) {
BTreeNode *child = x->children[i];
BTreeNode *sibling = x->children[i + 1];
child->keys[child->n] = x->keys[i];
if (!(child->leaf))
child->children[child->n + 1] = sibling->children[0];
x->keys[i] = sibling->keys[0];

Department of B. TECH CSE-AI & DS Page 67 Student Name: DIVYA


P.I.E.T DSA LAB

for (int j = 1; j < sibling->n; j++)


sibling->keys[j - 1] = sibling->keys[j];
if (!sibling->leaf) {
for (int j = 1; j <= sibling->n; j++)
sibling->children[j - 1] = sibling->children[j];
}
child->n++;
sibling->n--;
}
int main() {
BTreeNode *root = createNode(MIN_DEGREE, 1); // Create a B-tree with min degree = 2
insert(&root, 10);
insert(&root, 20);
insert(&root, 5);
insert(&root, 6);
insert(&root, 12);
printf("B-tree after insertions: ");
traverse(root);
printf("\n");
deleteKey(root, 10);
printf("B-tree after deletion of 10: ");
traverse(root);
printf("\n");
deleteKey(root, 6);
printf("B-tree after deletion of 6: ");
traverse(root);
printf("\n");
return 0;

Department of B. TECH CSE-AI & DS Page 68 Student Name: DIVYA


P.I.E.T DSA LAB

}
Output:

Department of B. TECH CSE-AI & DS Page 69 Student Name: DIVYA

You might also like