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

GYENEDRA DSA

Uploaded by

Robins Kumar
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)
14 views

GYENEDRA DSA

Uploaded by

Robins Kumar
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/ 42

Panipat Institute of Engineering & Technology

Samalkha, Panipat

Computer Science and Engineering Department


Lab Manual of Data Structure And Algorithm

Subject Code: -PC-CS201A


Affiliated to

Kurukshetra University Kurukshetra, India

Submitted to: Submitted by:

Mr. Sunny Kuhar Gyanendra kumar

Assistant Professor Roll no.2823297

CSE Department Section: A(3)

B. tech 2ndyear

INDEX
Exp. LIST OF PRACTICALS PAGE NO. DATE REMARK
No: S
1 Write a program for binary search method. 1-2 15-09-23

2 Write a program for Insertion, Selection, Bubble sort. 3-6 15-09-23

3 Write a program to implement Stack and its operation. 7-9 13-10-23

4 Write a program for Quick sort. 10-11 13-10-23

5 Write a program for Merge sort. 12-14 20-10-23

6 Write a program to implement Queue and its 15-17 20-10-23


operation.
7 Write a program to implement Circular Queue and its 18-20 27-10-23
operation.
8 Write a program to implement Singly Linked List for 21-24 03-11-23
the following operation: Create, Display, Searching,
Traversing, Deletion.
9 Write a program to implement Doubly Linked List for 25-28 17-11-23
the following operation: Create, Display, Inserting,
Counting, Searching, Traversing and Deletion.
10 Write a program to implement Circular Linked List 29-32 24-11-23
for the following operation: Create, Display,
Inserting, Counting, Searching, Traversing and
Deletion.
11 Write a program to implement Insertion, Deletion and 33-36 01-12-23
Traversing in B Tree.
Nikhil Sharma |2822147

PROGRAM 1

• Aim:
Write a program for binary search method .

• 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 main() { int i,
low, high, mid, n, key, array[100];
printf("Enter number of elements: ");
scanf("%d",&n); printf("Enter %d
integers: ", n);
for(i = 0; i < n; i++)
scanf("%d",&array[i]);
printf("Enter value to find:
"); scanf("%d", &key); low =
0; high = n - 1; mid =
(low+high)/2; while (low <=
high) { if(array[mid] < key){
low = mid + 1;
}
else if (array[mid] == key) {
printf("%d found at location %d", key,
mid+1); break; } else{ high = mid - 1;
mid = (low + high)/2;
}
}
if(low > high){
printf("Not found! %d isn't present in the list", key);
}

return 0;
}

1
Nikhil Sharma |2822147

• Output:

PROGRAM 2

• Aim:

2
Nikhil Sharma |2822147

Write a program for Insertion, Selection, Bubble sort.

A. For Insertion Sort:


• Algorithm:
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
• Source code:
#include
<stdio.h> int
main(void)
{
int n, i, j, temp;
int arr[64];
printf("Enter number of elements\
n"); scanf("%d", &n); printf("Enter
%d integers\n", n);
for (i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
for (i = 1; i < n; i++)
{
j = i;
while (j > 0 && arr[j - 1] > arr[j])
{
temp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] =
temp; j--;
}
}
printf("Sorted list in ascending order:\n");
for (i = 0; i < n; i++)
{
printf("%d\n", arr[i]);
}
return 0;

3
Nikhil Sharma |2822147

Output:

B. For Selection Sort:

• Procedure: • Algorithm:
MIN(A, K, N, LOC) SELECTION( A, N)

4
Nikhil Sharma |2822147

1. Set Min = A[K] & LOC = K 1. Repeat step 2 & 3 for K = 1, 2, -


2. Repeat for J = K+1, K+2, - - - - - - - - - - , N-1
-,N If Min > A[J] then Set Min =A[J] 2. Call Min(A, K, N, LOC)
and LOC = J 3. [Interchange A[K] and A[LOC]
[End of loop] Set Temp = A[K], A[K]
3. Return =A[LOC],
A[LOC] = Temp
[End of step 1 loop]
4. Exit.
• Source code:
#include <stdio.h> int main()
{ int array[100], n, c, d, position, t;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n",
n); for (c = 0; c < n; c++)
scanf("%d", &array[c]);
for (c = 0; c < (n - 1); c++) // finding minimum element (n-1) times
{
position = c;
for (d = c + 1; d < n; d++)
{
if (array[position] > array[d])
position = d;
}
if (position != c)
{ t = array[c];
array[c] = array[position];
array[position] = t;

} }
printf("Sorted list in ascending order:\
n"); for (c = 0; c < n; c++) printf("%d\
n", array[c]); return 0; }

Output:

5
Nikhil Sharma |2822147

C. For Bubble Sort:

• Algorithm:
BUBBLE(DATA, N)

6
Nikhil Sharma |2822147

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 [End
of Step 1 outer loop] 4. Exit.
• Source code:
#include <stdio.h>
int
main() {
int array[100], n, c, d, swap;
printf("Enter number of elements\n");
scanf("%d", &n); printf("Enter %d
integers\n", n); for (c = 0; c < n; c++)
scanf("%d", &array[c]); for (c = 0 ; c
< n - 1; c++)
{
for (d = 0 ; d < n - c - 1; d++)
{
if (array[d] > array[d+1]) /* For decreasing order use '<' instead of
'>' */
{
swap = array[d];
array[d] = array[d+1];
array[d+1] = swap;
}

} }
printf("Sorted list in ascending order:\
n"); for (c = 0; c < n; c++) printf("%d\
n", array[c]); return 0; }

Output:

7
Nikhil Sharma |2822147

PROGRAM 3

8
Nikhil Sharma |2822147

• 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> int
stack[100],choice,n,top,x,i;
void
push(void); void
pop(void); void
display(void); int
main() { top=-1;
printf("\nEnter the size of STACK[MAX=100]:");
scanf("%d",&n);
printf("\n STACK OPERATIONS USING ARRAY");
printf("\n--------------------------------");
printf("\n 1.PUSH\n 2.POP\n 3.DISPLAY\n
4.EXIT"); do { printf("\n Enter the Choice:");
scanf("%d",&choice); switch(choice)
{c
ase 1:
{ push
();
break;
} case
2:
{ pop(
);
break;
} case
3:
{ displ
ay();
break;

9
Nikhil Sharma |2822147

} case
4:
{ print
f("\n
EXIT
POIN
T ");
brea
k; }
default:
{
printf ("\n Please Enter a Valid Choice(1/2/3/4)");
}
}}
while(choice!=4);
return 0; } void
push()
{ if(top>=n-1) {
printf("\nSTACK 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 Stack is under flow");
}
else {
printf("\n 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");
}
}

10
Nikhil Sharma |2822147

• Output:

11
Nikhil Sharma |2822147

PROGRAM 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

Source code:

#include <stdio.h>

// Function to swap two elements


void swap(int* a, int* b) {
int t = *a;
*a = *b;
*b = t;
}
int partition(int arr[], int low, int high) {
int pivot = arr[high];
int i = (low - 1);

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


if (arr[j] < pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);

12
Nikhil Sharma |2822147

}
void quickSort(int arr[], int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}

// Function to print the array


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

int main() {
int arr[] = { 12, 17, 6, 25, 1, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
quickSort(arr, 0, n - 1);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}

Output:

13
Nikhil Sharma |2822147

PROGRAM 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]

14
Nikhil Sharma |2822147

[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
[End of loop]
10. For I = low to high do 11. Set ar[I] = br[I]
12. Exit.
• Source code:
#include <stdio.h> #include
<stdlib.h>
void Merge(int arr[], int left, int mid, int right)
{
int i, j, k; int size1 = mid
- left + 1; int size2 = right -
mid; int Left[size1],
Right[size2]; for (i = 0; i <
size1; i++) Left[i] =
arr[left + i]; for (j = 0; j <
size2; j++) Right[j] =
arr[mid + 1 + j]; i = 0; //
intital index of first subarray
j = 0; // inital index of
second subarray k = left; //
initial index of parent array
while (i < size1 && j < size2)
{
if (Left[i] <= Right[j])
{ arr[k] =
Left[i]; i++;
} else {
arr[k] = Right[j];
j++; } k++;
} while (i <
size1)
{ arr[k] =
Left[i]; i++;
k++;
} while (j <
size2)

15
Nikhil Sharma |2822147

{ arr[k] =
Right[j]; j++;
k++;
}
}
void Merge_Sort(int arr[], int left, int right)
{ if (left <
right) {
int mid = left + (right - left) / 2;
Merge_Sort(arr, left, mid);
Merge_Sort(arr, mid + 1, right);
Merge(arr, left, mid, right);
}
} int main() { int size;
printf("Enter the size: ");
scanf("%d", &size); int
arr[size]; printf("Enter
the elements of array: ");
for (int i = 0; i < size; i++)
{
scanf("%d", &arr[i]);
}
Merge_Sort(arr, 0, size - 1);
printf("The sorted array is: ");
for (int i = 0; i < size; i++)
{
printf("%d ", arr[i]);
} printf("\
n"); return 0;
}

Output:

16
Nikhil Sharma |2822147

PROGRAM 6
• Aim:
Write a program to implement Queue and its operation.

• Algorithm:
ENQUEUE(Q, x) DEQUEUE(Q)
Q[tail[Q]] <- x if x <- Q[head[Q]] if
tail[Q] = head[Q] = length[Q] then
length[Q] then head[Q] <- 1 else
tail[Q] <- 1 head[Q] <- head[Q] + 1
else tail[Q] <- tail[Q] + 1 return x

• Source code:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define MAXSIZE 5
void
initialize(); void
insert(); void
delete();
void traverse(); int
queue[MAXSIZE];
int front,rear;
void main(){

initialize(); int
choice;
while(1)
{

17
Nikhil Sharma |2822147

printf("\nSTATIC IMPLEMENTATION OF LINEAR QUEUE");


printf("\
n--------------------------");
printf("\n1. Insert"); printf("\n2.
Delete"); printf("\n3. Traverse");
printf("\n4. Exit");
printf("\n--------------------------");
printf("\n\nEnter your choice[1/2/3/4]: ");
scanf("%d",&choice);
switch(choice)
{
case
1:insert(); break;
case 2:delete();
break; case
3:traverse();
break; case
4:exit(0);
default : printf("\n Invalid choice");
}
getch();
}
} void
initialize() {
front = rear = -1;
} void
insert() {
int num;
if(rear==MAXSIZE-1)
{
printf("\nQueue is full(Queue Overflow)");
return;
}
printf("\nEnter the elements to be inserted: ");

scanf("%d",&num);
rear++;
queue[rear]=num;
if(front==-1)
front=0; } void
delete()
{ if(front==-1){
printf("\nQueue is Empty(Queue Underflow)");
return;
} int num; num = queue[front];
printf("\nDeleted element is: %d",num);

18
Nikhil Sharma |2822147

front++;
if(front>rear)
front=rear=-1; }
void traverse() {
if(front==-1){
printf("\nQueue is empty(Queue Underflow)");
return; }
else{ printf("\nQueue elements
are: \n"); for(int i=front;i<=rear;i+
+)
printf("%d\t",queue[i]);
}
}

Output:

19
Nikhil Sharma |2822147

PROGRAM 7
• Aim:

20
Nikhil Sharma |2822147

Write a program to implement Circular Queue and its operation.


• Algorithm:

add_circular( item,queue,rear,front delete_circular (item,queue,rear,front)


) { rear=(rear+1)mod {
n; if (front == if (front = = rear)
rear) print ("queue is empty");
then print " queue is full " else
else { {
queue front= front+1;
[rear]=item;} } item=queue[front];
}
}
Source code:
#include<stdio.h>
# define MAX 5 int
cqueue_arr[MAX]; int
front = -1; int rear = -
1; void insert(int item)
{
if((front == 0 && rear == MAX-1) || (front == rear+1))
{ printf("Queue Overflow \n");
return; }
if(front == -1)
{ front = 0; rear =
0; } else{ if(rear
== MAX-1)
rear = 0;
else
rear = rear+1;
}
cqueue_arr[rear] = item ;
}
void deletion(){ if(front
== -1){ printf("Queue
Underflow\n");
retur
n;}
printf("Element deleted from queue is : %d\
n",cqueue_arr[front]); if(front == rear){ front = -1; rear=-1;
}
else{ if(front
== MAX-1) front =
0; else front =
front+1;

21
Nikhil Sharma |2822147

} } void display(){ int front_pos


= front,rear_pos = rear; if(front == -
1){ printf("Queue is empty\n");
return; } printf("Queue elements
:"); if( front_pos <= rear_pos )
while(front_pos <= rear_pos)
{ printf("%d
",cqueue_arr[front_pos]);
front_pos++; }
else{ while(front_pos <= MAX-
1){ printf("%d
",cqueue_arr[front_pos]);
front_pos++; } front_pos = 0;
while(front_pos <= rear_pos)
{ printf("%d
",cqueue_arr[front_pos]);
front_pos++;
} } printf("\n"); } int main(){ int choice,item;
do{ printf("1.Insert\n"); printf("2.Delete\n");
printf("3.Display\n"); printf("4.Quit\n");
printf("Enter your choice : ");
scanf("%d",&choice); switch(choice){ case 1 :
printf("Input the element for insertion in queue : ");
scanf("%d",
&item);
insert(item); break;
case 2 : deletion();
break; case 3: display();
break; case 4: break;
default: printf("Wrong
choice\n");
}}
while(choice!=4);
return 0; }

22
Nikhil Sharma |2822147

Output:

23
Nikhil Sharma |2822147

PROGRAM 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>
struct Node
{ int data;
struct Node *next;
};
struct Node* createNode(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct
Node)); if (newNode == NULL) {
printf("Memory allocation failed\n");
exit(1);
}
newNode->data =
value; newNode->next =
NULL; return newNode;
} void insertAtEnd(struct Node** head, int
value) { struct Node* newNode =
createNode(value); if (*head == NULL) {
*head = newNode;
} else {
struct Node* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;

}}

24
Nikhil Sharma |2822147

void display(struct Node*


head) { if (head == NULL) {
printf("List is empty\n");
} else
{ printf("Linked List:
"); while (head !=
NULL) { printf("%d
-> ", head->data);
head = head->next;
}
printf("NULL\n");

}}
int search(struct Node* head, int value) {
int position = 1; while
(head != NULL) { if
(head->data == value) {
return position;
}
head = head->next;
position++;
}
return -1; // Return -1 if value is not found
} void deleteNode(struct Node** head, int
value) { struct Node *temp = *head, *prev =
NULL; if (temp != NULL && temp->data ==
value) {
*head = temp-
>next; free(temp);
return;
}
while (temp != NULL && temp->data != value) {
prev = temp;
temp = temp->next;
}
if (temp == NULL)
{ printf("Value not found in the list\
n");
return;
}
prev->next = temp->next;
free(temp); } void freeLinkedList(struct
Node** head) {
struct Node* temp;
while (*head != NULL) {
temp = *head; *head =

25
Nikhil Sharma |2822147

(*head)->next;
free(temp);
} } int main() { struct
Node* head = NULL; int
choice, value, position;
do {
printf("\nLinked List Operations\n");
printf("1. Insert\n");
printf("2. Display\n");
printf("3. Search\n");
printf("4. Delete\n");
printf("5. Exit\n");
printf("Enter your choice:
"); scanf("%d",
&choice); switch
(choice) { case 1:
printf("Enter value to insert: ");
scanf("%d", &value);
insertAtEnd(&head,
value); break; case
2: display(head);
break; case 3:
printf("Enter value to
search: "); scanf("%d",
&value); position =
search(head, value);
if (position != -1) {
printf("Value found at position %d\n", position);
} else {
printf("Value not found in the list\n");
}
break;
case 4:
printf("Enter value to delete: ");
scanf("%d", &value);
deleteNode(&head,
value); break; case
5: printf("Exiting...\n");
break;
default:
printf("Invalid choice! Please enter a valid choice.\n");
}
} while (choice != 5);
freeLinkedList(&head);
return 0;
}

26
Nikhil Sharma |2822147

Output:

27
Nikhil Sharma |2822147

PROGRAM 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>
struct Node
{ int data; struct
Node* prev; struct
Node* next;
};
struct Node* createNode(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct
Node)); if (newNode == NULL) {
printf("Memory allocation failed\n");
exit(1);
}
newNode->data = value;
newNode->prev = NULL;
newNode->next = NULL; return
newNode;
} void insertAtEnd(struct Node** head, int
value) { struct Node* newNode =
createNode(value); if (*head == NULL) {
*head = newNode;
} else {
struct Node* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
newNode->prev = temp;

}}
void display(struct Node*
head) { if (head == NULL) {
printf("List is empty\n");
} else {

28
Nikhil Sharma |2822147

printf("Forward Linked List: ");


while (head != NULL)
{ printf("%d -> ", head->data);
head = head->next;
}
printf("NULL\n");
printf("Backward Linked List: ");
while (head->prev != NULL)
{ printf("%d -> ", head->data);
head = head->prev;
}
printf("%d -> NULL\n", head->data);

}}
int countNodes(struct Node* head) {
int count = 0;
while (head != NULL) {
count++; head =
head->next;
}
return count; }
int search(struct Node* head, int value) {
int position = 1; while
(head != NULL) { if
(head->data == value) {
return position;
}
head = head->next;
position++;
}
return -1; // Return -1 if value is not found
}
void deleteNode(struct Node** head, int value) {
struct Node* temp = *head;
if (temp != NULL && temp->data == value) {
*head = temp->next;
if (*head != NULL)
{ (*head)->prev =
NULL;
}
free(temp);
return;
}
while (temp != NULL && temp->data != value) {
temp = temp->next;
}

29
Nikhil Sharma |2822147

if (temp == NULL)
{ printf("Value not found in the list\
n");
return;
}
if (temp->next != NULL) {
temp->next->prev = temp->prev; }
if (temp->prev != NULL) {
temp->prev->next = temp->next;
}
free(temp); }
void freeLinkedList(struct Node** head) {
struct Node* temp;
while (*head != NULL) {
temp = *head; *head =
(*head)->next;
free(temp);
} } int main() { struct Node*
head = NULL; int choice, value,
position, nodeCount;
do {
printf("\nDoubly Linked List Operations\n");
printf("1. Insert\n");
printf("2. Display\n");
printf("3. Count Nodes\n");
printf("4. Search\n");
printf("5. Delete\n");
printf("6. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) { case 1:
printf("Enter value to insert: ");
scanf("%d", &value);
insertAtEnd(&head,
value); break; case
2: display(head);
break; case 3:
nodeCount = countNodes(head);
printf("Number of nodes in the list: %d\n",
nodeCount); break; case 4:
printf("Enter value to
search: "); scanf("%d",
&value); position =
search(head, value);
if (position != -1) {
printf("Value found at position %d\n", position);
} else {
printf("Value not found in the list\n");

30
Nikhil Sharma |2822147

}
break;
case 5:
printf("Enter value to delete: ");
scanf("%d", &value);
deleteNode(&head,
value); break; case
6: printf("Exiting...\n");
break;
default:
printf("Invalid choice! Please enter a valid choice.\n");
}
} while (choice != 6);
// Free memory allocated for the linked list before
exiting freeLinkedList(&head); return 0;
}
Output:

31
Nikhil Sharma |2822147

PROGRAM 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 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>
struct Node
{ int data;
struct Node* next;
};
struct Node* createNode(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct
Node)); if (newNode == NULL) {
printf("Memory allocation failed\n");
exit(1);
}
newNode->data =
value; newNode->next =
NULL; return newNode;
}
struct Node* insertAtEnd(struct Node* head, int
value) { struct Node* newNode = createNode(value);
if (head == NULL) { head = newNode; head-
>next = head; // Pointing to itself for circularity
} else {
struct Node* temp = head;
while (temp->next != head) {
temp = temp->next;
}
temp->next = newNode;

32
Nikhil Sharma |2822147

newNode->next = head;
}
return head;
}
void display(struct Node*
head) { if (head == NULL) {
printf("List is empty\n");
} else { struct Node*
temp = head; printf("Circular
Linked List: "); do {
printf("%d -> ", temp->data);

temp = temp-
>next; } while (temp !=
head);
printf("Head\n");

}}
int countNodes(struct Node* head) {
if (head == NULL) {
return 0; } else {
int count = 0; struct
Node* temp = head; do {
count++; temp = temp-
>next; } while (temp !=
head); return count;

}}
struct Node* search(struct Node* head, int
value) { if (head == NULL) { return
NULL; } else { struct Node* temp = head;
do {
if (temp->data == value) {
return temp;
}
temp = temp-
>next; } while (temp !=
head);
return NULL;

}}
struct Node* deleteNode(struct Node* head, int
value) { if (head == NULL) { printf("List is
empty\n"); return head;
}
struct Node* temp = head;
struct Node* prev =
NULL; do {

33
Nikhil Sharma |2822147

if (temp->data == value) {
if (prev == NULL) { // Deleting the head
node struct Node* lastNode = head;
while (lastNode->next != head) {
lastNode = lastNode->next;
}
lastNode->next = head->next; // Changing the last node's next to the second
node head = head->next; // Changing the head free(temp); // Freeing
memory of the deleted node return head; } else {
prev->next = temp->next;
free(temp);
return head;
}
}
prev = temp;
temp = temp->next; }
while (temp != head);

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


return head;
} int
main() {
struct Node* head = NULL;
int choice, value;
do {
printf("\nCircular Linked List Operations\n");
printf("1. Insert\n");
printf("2. Display\n");
printf("3. Count Nodes\n");
printf("4. Search\n");
printf("5. Delete\n");
printf("6. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter value to insert:
"); scanf("%d", &value);
head = insertAtEnd(head, value);
break; case 2:
display(head);
break;
case 3:
printf("Number of nodes in the list: %d\n",
countNodes(head)); break; case 4:
printf("Enter value to search: ");
scanf("%d", &value);

34
Nikhil Sharma |2822147

struct Node* searchResult = search(head,


value); if (searchResult != NULL) {
printf("Value %d found in the list\n", value);
} else {
printf("Value %d not found in the list\n", value);
}
break;
case 5:
printf("Enter value to delete: ");
scanf("%d", &value);
head = deleteNode(head,
value); break; case 6:
printf("Exiting...\n");
break;
default:
printf("Invalid choice! Please enter a valid choice.\n");
}
} while (choice != 6);
struct Node* temp = head;
if (temp != NULL) {
do {
struct Node* prev = temp;
temp = temp->next; free(prev);
} while (temp != head);
}
return 0;

35
Nikhil Sharma |2822147

}
Output:

PROGRAM 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:

36
Nikhil Sharma |2822147

- 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:
- 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 <stdbool.h>
#define t 3 // Minimum degree of the B-tree
struct Node {
int n; // Number of keys
int keys[2 * t - 1]; // Array to store keys
struct Node *child[2 * t]; // Array of child pointers
bool leaf; // Flag to indicate if it's a leaf node
};
struct Node* createNode() {
struct Node* newNode = (struct Node*)malloc(sizeof(struct
Node)); newNode->n = 0; newNode->leaf = true;
for (int i = 0; i < 2 * t; i++) { newNode-
>child[i] = NULL;
}return newNode;
}
void traverse(struct Node* root)
{ if (root != NULL) {
int i;
for (i = 0; i < root->n; i++)
{ traverse(root->child[i]);
printf(" %d", root->keys[i]);
}

37
Nikhil Sharma |2822147

traverse(root->child[i]);

}}
struct Node* search(struct Node* root, int key)
{ int i = 0;
while (i < root->n && key > root->keys[i]) {
i++;
} if (root->keys[i] == key) {
return root;
} if (root->leaf) {
return NULL;
} return search(root->child[i], key);
}
void insert(struct Node** root, int
key) { struct Node* r = *root; if (r-
>n == (2 * t - 1)) { struct Node* s =
createNode();
*root = s; s-
>leaf = false; s-
>child[0] = r;
splitChild(s, 0);
insertNonFull(s, key);
} else {
insertNonFull(r, key);

}}
void insertNonFull(struct Node* x, int key) {
int i = x->n -
1; if (x->leaf) {
while (i >= 0 && key < x->keys[i]) {
x->keys[i + 1] = x->keys[i];
i--;
}
x->keys[i + 1] = key;
x->n+
+; } else {
while (i >= 0 && key < x->keys[i]) {

i--; }
i++;
if (x->child[i]->n == (2 * t -
1)) { splitChild(x, i); if
(key > x->keys[i]) {
i++;
}
}
insertNonFull(x->child[i], key);

38
Nikhil Sharma |2822147

} } void splitChild(struct
Node* x, int i) { struct Node* y =
x->child[i]; struct Node* z =
createNode(); z->leaf = y->leaf;
z->n = t - 1; for (int j = 0; j < t - 1;
j++) {
z->keys[j] = y->keys[j + t];
} if (!y->leaf)
{ for (int j = 0; j < t; j++)
{
z->child[j] = y->child[j + t];
} } y->n = t - 1;
for (int j = x->n; j >= i + 1; j--) {
x->child[j + 1] = x->child[j];
} x->child[i + 1] = z;
for (int j = x->n - 1; j >= i; j--) {
x->keys[j + 1] = x->keys[j];
}
x->keys[i] = y->keys[t - 1];
x->n++; } int main() { struct
Node* root = createNode(); int
choice, key; do {
printf("\nB-tree Operations\
n"); printf("1. Insert\n");
printf("2. Search\n"); printf("3.
Traverse\n"); printf("4. Exit\
n"); printf("Enter your choice:
"); scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter key to insert: ");
scanf("%d", &key); insert(&root,
key);
break;
case 2:
printf("Enter key to search: ");
scanf("%d", &key);
struct Node* searchResult = search(root,
key); if (searchResult != NULL) {
printf("Key %d found in the B-tree.\n", key);
} else {
printf("Key %d not found in the B-tree.\n", key);
} break;
case 3:
printf("B-tree traversal:\
n"); traverse(root);
printf("\n"); break;

39
Nikhil Sharma |2822147

case 4: printf("Exiting...\
n");
break;
default:
printf("Invalid choice! Please enter a valid choice.\n");
}
} while (choice != 4);
return 0;
}
Output:

40

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy