Advanced Data Structures Lab
Advanced Data Structures Lab
Lab Manual
Prepared By:
[Link] indrapalli
Associate Professor & Head, CSE allied Branches
Princeton Institute of Engineering and Technology for women
3 B-Tree Operations 15
1
Chapter 1
Aim
To write a C program to perform insertion, deletion, and search operations on a Binary
Search Tree (BST).
Problem Statement
Design and implement a menu-driven program in C that:
Algorithm
BST Insertion
1. If the tree is empty, create a new node and make it the root.
3. If key is less than root key, recursively insert into the left subtree.
4. If key is greater than root key, recursively insert into the right subtree.
2
Advanced Data Structures Lab Manual B3CS104PC
BST Search
1. If the current node is NULL, key is not found.
BST Deletion
1. If node to delete is a leaf, simply remove it.
Program
1 #include <stdio.h>
2 #include
3
<stdlib.h>
4
typedef struct Node {
5
int key;
6
struct Node *left, *right;
7
} Node;
8
3
Advanced Data Structures Lab Manual B3CS104PC
19
4
Advanced Data Structures Lab Manual B3CS104PC
20 else if (key > root->key)
21 root->right = insert(root->right, key);
22 else
23 printf("Duplicate key %d ignored.\n", key);
24 return root;
25 }
26
5
Advanced Data Structures Lab Manual B3CS104PC
61
return root;
62 }
63
78 int main() {
79 Node *root = NULL;
80 int choice, key;
81 while (1) {
82 printf("\n--- BST Operations ---\n");
83 printf("1. Insert\n2. Delete\n3. Search\n4.
Inorder Traversal\n5. Exit\n");
84 printf("Enter choice: ");
85 if (scanf("%d", &choice) != 1) break;
86 switch (choice) {
87 case 1:
88 printf("Enter key to insert: ");
89 scanf("%d", &key);
90 root = insert(root, key);
91 break;
92 case 2:
93 printf("Enter key to delete: ");
94 scanf("%d", &key);
95 root = delete(root, key);
96 break;
97 case 3:
98 printf("Enter key to search: ");
99 scanf("%d", &key);
100 if (search(root, key))
6
Advanced Data Structures Lab Manual B3CS104PC
101 printf("Key %d found in BST.\n", key);
102 else
103 printf("Key %d not found in BST.\n", key);
104 break;
105 case 4:
106 printf("Inorder Traversal: ");
107 inorder(root);
108 printf("\n");
109 break;
110 case 5:
111 exit(0);
112 default:
113 printf("Invalid choice.\n");
114 }
115 }
116 return 0;
117 }
1 50
1 30
1 70
1 20
1 40
4
3 40
2 30
4
5
Inorder Traversal: 20 30 40 50 70
Key 40 found in BST.
Inorder Traversal: 20 40 50 70
7
Advanced Data Structures Lab Manual B3CS104PC
Result
The operations of insertion, deletion, and search on a Binary Search Tree were successfully
implemented and tested using C.
1. What is a Binary Search Tree? State its properties. A Binary Search Tree
(BST) is a binary tree where each node has a key, and keys in the left subtree are
smaller while keys in the right subtree are larger. Both subtrees must also be valid
BSTs. This ordering property makes searching and updating efficient.
2. What is the time complexity of search in a BST in best and worst case?
The best case occurs when the key is found at the root, giving a time
complexity of O(1). The worst case occurs in a skewed BST (like a linked list),
giving O(n). For a balanced BST, average search time is O(log n).
3. How does deletion differ for nodes with zero, one, and two children? If
the node is a leaf (zero children), it is removed directly. If it has one child, the
node is replaced by its child. If it has two children, the inorder successor (or
predecessor) replaces its key, and the successor node is deleted recursively.
4. What is the relation between inorder traversal of a BST and sorted order
of keys? Inorder traversal visits nodes in the order: Left Subtree Root Right
Subtree. For a BST, this traversal produces keys in strictly increasing sorted order.
This property is often used to verify if a tree is a valid BST.
8
Chapter 2
Aim
To implement Merge Sort, Heap Sort, and Quick Sort in C and compare their working
principles, performance, and outputs.
Objectives
Understand the divide-and-conquer strategy in Merge Sort and Quick Sort.
Compare the time and space complexities of three major sorting algorithms.
Problem Statement
Write a C program that:
Sorts the array using one of the following: Merge Sort, Heap Sort, or Quick Sort.
9
Advanced Data Structures Lab Manual B3CS104PC
Theory
Sorting is a fundamental operation in computer science. Among many available sorting
techniques, Merge Sort, Heap Sort, and Quick Sort are widely used due to their
performance and reliability.
Algorithm
Merge Sort
Merge Sort uses the Divide and Conquer strategy:
Characteristics:
Stable sort.
Heap Sort
Heap Sort uses a binary heap structure:
Characteristics:
10
Advanced Data Structures Lab Manual B3CS104PC
Not stable.
Quick Sort
Quick Sort also follows Divide and Conquer:
Characteristics:
Program
Complete C program implementing all three sorting algorithms:
1 #include <stdio.h>
2
12 i =0; j = 0; k= l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) a[k++] = L[i++];
11
Advanced Data Structures Lab Manual B3CS104PC
15 else a[k++] = R[j++];
16 }
17 while (i < n1) a[k++] = L[i++];
18 while (j < n2) a[k++] = R[j++];
19 }
20
12
Advanced Data Structures Lab Manual B3CS104PC
56
84 int main() {
85 int a[100], n, i, choice;
86 printf("Enter number of elements: ");
87 scanf("%d", &n);
88 printf("Enter %d elements:\n", n);
89 for (i = 0; i < n; i++) scanf("%d", &a[i]);
90
91 while (1) {
92 printf("\n1. Merge Sort\n2. Heap Sort\n3. ck
Qui
Sort\n4. Exit\n");
93 printf("Enter choice: ");
94 scanf("%d", &choice);
95
13
Advanced Data Structures Lab Manual B3CS104PC
96 if (choice == 4) break;
97
98 switch (choice) {
99 case 1:
100 mergeSort(a, 0, n - 1);
101 printf("Sorted array (Merge Sort): ");
102 printArray(a, n);
103 break;
104 case 2:
105 heapSort(a, n);
106 printf("Sorted array (Heap Sort): ");
107 printArray(a, n);
108 break;
109 case 3:
110 quickSort(a, 0, n - 1);
111 printf("Sorted array (Quick Sort): ");
112 printArray(a, n);
113 break;
114 default:
115 printf("Invalid choice.\n");
116 }
117 }
118 return 0;
119 }
n = 5
Elements: 5 1 4 2 8
1 2 4 5 8
Divide [5 1 4] and [2 8]
Divide [5 1] [4] and [2] [8]
14
Advanced Data Structures Lab Manual B3CS104PC
Merge [1 5 4] and [2 8]
Merge [1 4 5 2 8]
Final [1 2 4 5 8]
Result
Merge Sort, Heap Sort, and Quick Sort were implemented in C and their outputs vali-
dated. Each algorithm successfully sorted the given input array, demonstrating different
approaches to sorting.
10. Which sorting algorithm is preferred in system libraries (C/C++) and why?
15
Chapter 3
B-Tree Operations
Aim
To implement insertion, deletion, and search operations on a B-Tree of specified minimum
degree t using C programming.
Objective
The objectives of this experiment are:
To understand how B-Trees maintain balanced height and ensure efficient disk ac-
cess.
Theory Background
What is a B-Tree?
A B-Tree is a multi-way search tree in which each node may contain multiple keys. It is
designed for disk-based or large-memory storage, minimizing disk accesses.
A B-Tree of minimum degree t has the following properties:
16
Advanced Data Structures Lab Manual B3CS104PC
The tree is height-balanced: all leaves occur at the same depth.
Applications of B-Trees
Database indexing (MySQL, PostgreSQL)
Problem Statement
Develop a C program to:
Insertion Algorithm
1. If the root is full (2t − 1 keys), create a new root and split the old root.
Search Algorithm
1. Perform linear or binary search on the current node’s keys.
17
Advanced Data Structures Lab Manual B3CS104PC
Deletion Algorithm (Conceptual Overview)
B-Tree deletion is complex and involves multiple cases:
1 #include <stdio.h>
2 #include
3
<stdlib.h>
4
#define T 3 /* minimum degree */
5
6
typedef struct BTreeNode {
7
int keys[2*T-1];
8 struct BTreeNode *child[2*T];
9 int n;
10
int leaf;
11
} BTreeNode;
12
BTreeNode* createNode(int leaf) {
13
BTreeNode *node = (BTreeNode*)malloc(sizeof(BTreeNode))
14
;
node->leaf =
15 leaf; node->n =
16 0;
17
int i;
for (i = 0; i < 2*T; i+
18
+) node->child[i] =
19
NULL; return node;
20
}
18
Advanced Data Structures Lab Manual B3CS104PC
21
22
19
Advanced Data Structures Lab Manual B3CS104PC
23 void traverse(BTreeNode *root) {
24 int i;
25 if (root == NULL) return;
26 for (i = 0; i < root->n; i++) {
27 if (!root->leaf)
28 traverse(root->child[i]);
29 printf("%d ", root->keys[i]);
30 }
31 if (!root->leaf)
32 traverse(root->child[i]);
33 }
34
43 if (root->leaf)
44 return NULL;
45
53 z->n = T - 1;
54
58 if (!y->leaf) {
59 for (j = 0; j < T; j++)
60 z->child[j] = y->child[j + T];
61 }
62
63 y->n = T - 1;
20
Advanced Data Structures Lab Manual B3CS104PC
64
72 x->keys[i] = y->keys[T -
73 1]; x->n = x->n + 1;
74 }
75
79 if (x->leaf) {
80 while (i >= 0 && k < x->keys[i]) {
81 x->keys[i + 1] = x->keys[i];
82 i--;
83 }
84 x->keys[i + 1] = k;
85 x->n++;
86 }
87 else {
88 while (i >= 0 && k < x->keys[i])
89 i--;
90 i++;
91
92 if (x->child[i]->n == 2*T - 1) {
93 splitChild(x, i, x->child[i]);
94
95 if (k > x->keys[i]) i+
96 +;
97 }
98 insertNonFull(x->child[i], k);
99 }
100 }
101
21
Advanced Data Structures Lab Manual B3CS104PC
104 root = createNode(1);
22
Advanced Data Structures Lab Manual B3CS104PC
105 root->keys[0] = k;
106 root->n = 1;
107 return root;
108 }
109
115 int i = 0;
116 if (k > s->keys[0])
117 i++;
118 insertNonFull(s->child[i], k);
119 return s;
120 }
121 else {
122 insertNonFull(root, k);
123 return root;
124 }
125 }
126
23
Advanced Data Structures Lab Manual B3CS104PC
144 case 2:
145 printf("Enter key to search: ");
146 scanf("%d", &key);
147 if (root && search(root, key))
148 printf("Key %d found.\n", key);
149 else
150 printf("Key %d not found.\n", key);
151 break;
152
153 case 3:
154 printf("B-Tree (inorder-like traversal): ");
155 traverse(root);
156 printf("\n");
157 break;
158
159 case 4:
160 exit(0);
161
162 default:
163 printf("Invalid choice.\n");
164 }
165 }
166
167 return 0;
168 }
Output
B-Tree (inorder-like traversal):
5 6 7 10 12 17 20 30
24
Advanced Data Structures Lab Manual B3CS104PC
Observations
Node splits occurred when inserting keys into a full node.
Height of the tree grows slowly due to high branching factor (2t children).
Advantages of B-Trees
Efficient for disk-based storage.
Time Complexity
Search: O(t log n)
Space: O(n)
Result
The B-Tree implementation successfully demonstrates insertion, search, node-splitting,
and traversal. Although deletion is conceptually discussed, the program focuses on inser-
tion and search operations, which are essential for understanding B-Tree structure and
behavior.
25
Advanced Data Structures Lab Manual B3CS104PC
Viva Questions
1. What is a B-Tree? How does it differ from AVL or Red-Black Trees?
26
Chapter 4
Aim
To implement the fundamental operations of a Min-Max Heap, specifically:
using a two-heap approach (one Min Heap and one Max Heap).
Objective
The objective of this experiment is to understand:
Theory Background
27
Advanced Data Structures Lab Manual B3CS104PC
Delete-Min: Remove the element with the lowest priority
Min-Max Heap
A Min-Max Heap is a complete binary tree in which:
efficiently Limitations:
Algorithms
Insertion Algorithm
1. Insert the key into both the Min Heap and Max Heap.
28
Advanced Data Structures Lab Manual B3CS104PC
Delete-Min Algorithm
1. The minimum element is the root of the Min Heap.
Delete-Max Algorithm
1. The maximum element is the root of the Max Heap.
4. Apply maxHeapify.
Search Algorithm
Perform a linear search in the Min Heap array:
O(n)
1 #include <stdio.h>
2 #include <stdlib.h>
3
6 typedef struct {
7 int minHeap[MAX];
8 int maxHeap[MAX];
9 int size;
10 } MinMax;
11
29
Advanced Data Structures Lab Manual B3CS104PC
17 if (l < n && a[l] < a[smallest]) smallest =
18 l; if (r < n && a[r] < a[smallest]) smallest
19 = r; if (smallest != i) {
20
swap(&a[i], &a[smallest]);
21
minHeapify(a, n,
smallest);
22
}
23 }
24
49
for (i = n/2 - 1; i >= 0; i--)
{ minHeapify(mm->minHeap, n,
50
i); maxHeapify(mm->maxHeap,
51
n, i);
52
}
53 }
54
63 }
64
91 int main() {
92 MinMax mm;
93 [Link] = 0;
94 int choice, key, x;
95
96 while (1) {
31
Advanced Data Structures Lab Manual B3CS104PC
97 printf("\n1. Insert\n2. Extract Min\n3. Extract Max
\n");
98 printf("4. Search\n5. Print Heaps\n6. Exit\n");
99 printf("Enter choice: ");
100 scanf("%d", &choice);
101
109 case 2:
110 x = extractMin(&mm);
111 if (x == -1) printf("Heap empty.\n");
112 else printf("Min = %d\n", x);
113 break;
114
115 case 3:
116 x = extractMax(&mm);
117 if (x == -1) printf("Heap empty.\n");
118 else printf("Max = %d\n", x);
119 break;
120
121 case 4:
122 printf("Enter key to search: ");
123 scanf("%d", &key);
124 if (searchKey(&mm, key)) printf("Key found.\n")
;
125 else printf("Key not found.\n");
126 break;
127
128 case 5:
129 printHeaps(&mm);
130 break;
131
132 case 6:
133 exit(0);
134
135 default:
32
Advanced Data Structures Lab Manual B3CS104PC
136 printf("Invalid choice.\n");
137 }
138 }
139 return 0;
140 }
Sample Input/Output
Input
1
Enter key: 40
1
Enter key: 10
1
Enter key: 80
1
Enter key: 5
5
2
3
5
Output
MinHeap: 5 10 80 40
MaxHeap: 80 40 10 5
Min = 5
Max = 80
MinHeap: 10 40 80
MaxHeap: 40 10 5
Observations
The minimum value is always at the root of the Min Heap.
Insert operation requires heap reconstruction, making the approach less optimal.
33
Advanced Data Structures Lab Manual B3CS104PC
Search operation is linear because heap property does not support binary search.
Extract-Min: O(log n)
Extract-Max: O(log n)
Search: O(n)
Advantages
Easy to implement
Limitations
Duplicate storage doubles memory usage
Min and Max heaps can become unsynchronized in advanced use cases
Result
A Min-Max priority queue was implemented using two heaps (Min Heap and Max Heap).
Operations such as insertion, deletion of minimum, deletion of maximum, and search
were successfully performed and verified.
34
Advanced Data Structures Lab Manual B3CS104PC
Viva Questions
1. What is a Min-Max Heap? How is it different from Min Heap or Max
Heap?
A Min-Max Heap supports both delete-min and delete-max operations efficiently,
unlike a normal heap which supports only one of them.
3. What are the time complexities of insert and delete operations in a heap?
Insert: O(log n), Delete-min and delete-max: O(log n).
35
Chapter 5
Aim
To implement the core operations of a Leftist Tree (also called a Leftist Heap), namely:
Insertion of a key
Objective
The purpose of this experiment is to understand:
How Leftist Trees maintain structural properties to support efficient merging
How Leftist Trees compare with other priority queue structures like binary heaps
Theory Background
Leftist Tree
A Leftist Tree is a variant of a min-heap that is explicitly designed to make the merge
operation efficient.
Each node in a Leftist Heap stores:
36
Advanced Data Structures Lab Manual B3CS104PC
Key value
For any node in a Leftist Heap, the leftist property must be maintained:
Leftist Property
A Leftist Tree always leans to the left, ensuring the shortest null path is always on the
right side. This structure ensures:
Operations
1. Merge The fundamental operation. Algorithm:
2. Recursively merge the right subtree of the root with the other heap.
37
Advanced Data Structures Lab Manual B3CS104PC
Algorithm
Algorithm for Merge
1. If either heap is empty, return the other.
2. Ensure the root with the smaller key becomes the new root.
5. Update NPL.
Program
(The C program remains unchanged.)
1 <same code here>
38
Advanced Data Structures Lab Manual B3CS104PC
Sample Input and Output
Sample Input
1
Enter key: 30
1
Enter key: 10
1
Enter key: 40
1
Enter key: 5
4
2
4
Sample Output
Inorder: 5 10 30 40
Min deleted: 5
Inorder: 10 30 40
Observations
The heap maintained leftist property by swapping children where needed.
Insert: O(log n)
Delete-Min: O(log n)
39
Advanced Data Structures Lab Manual B3CS104PC
Result
The operations of a Leftist Tree — merge, insertion, delete-min, search, and traversal —
were successfully implemented using recursive algorithms. The output verifies correctness
of the leftist property and null-path lengths.
Viva Questions
1. What is the null path length (NPL) in a Leftist Tree?
It is the length of the shortest path from a node to a leaf or null child.
40
Chapter 6
Aim
To develop and implement a program in C for performing the following operations
using a Binomial Heap:
Insertion of a key
Objective
Binomial Heaps are an essential data structure in priority queue implementations. They
support efficient merging (union) of heaps, unlike binary heaps. This experiment helps
students:
Theory Background
Binomial Tree
A Binomial Tree Bk of order k is defined recursively as:
41
Advanced Data Structures Lab Manual B3CS104PC
B0 is a single node.
Bk is made by linking two Bk−1 trees, making one the leftmost child of the other.
Properties:
Height of Bk is k.
ki
Exactly nodes are at depth i.
Binomial Heap
A Binomial Heap is a collection of Binomial Trees satisfying:
Major Operations
1. Union Operation The most important operation:
2. Insert Operation Insert = Union of existing heap with a new singleton binomial
tree.
3. Delete-Min Steps:
sibling pointers
child pointers
42
Advanced Data Structures Lab Manual B3CS104PC
Algorithm
1. Insertion
1. Create a single-node binomial tree.
2. Delete-Min
1. Traverse root list and find the minimum key.
3. Search
Recursively search the key in:
1. Current root
2. Child subtree
3. Sibling nodes
4. Print Heap
Print each binomial tree as:
Bk : root → children
Program
(The C program remains exactly as provided by the user.)
1 <same program code here>
43
Advanced Data Structures Lab Manual B3CS104PC
Sample Input/Output
Input
1
Enter key: 20
1
Enter key: 5
1
Enter key: 30
4
2
4
Output
B0: 5
B1: 5 20
Min deleted: 5
B1: 20 30
Observations
Binomial Heap construction is dependent on binary representation of heap size.
Delete-Min: O(log n)
Search: O(n)
Union: O(log n)
44
Advanced Data Structures Lab Manual B3CS104PC
Result
The operations of a Binomial Heap—namely insertion, deletion of minimum, search, and
printing the heap—were successfully implemented. The program demonstrates correct
construction and maintenance of binomial trees with proper linking and merging.
Viva Questions
1. What is a Binomial Heap? How is it different from a Binary Heap?
A Binomial Heap is a collection of binomial trees that supports efficient merging.
Binary heaps cannot merge in O(log n); binomial heaps can.
45
Chapter 7
Aim
To design and implement insertion, deletion, and search operations on an AVL Tree
in C, ensuring the tree remains height-balanced after each modification.
Problem Statement
An AVL Tree (named after Adelson-Velsky and Landis) is a self-balancing Binary Search
Tree where the height difference between the left and right subtrees (called the
Balance Factor) is always maintained between −1 and +1. The goal of this
experiment is to:
Insert nodes into an AVL Tree
Description
The AVL Tree ensures that the height of the binary search tree remains logarithmic,
guaranteeing O(log n) search, insertion, and deletion times.
Balance Factor
The Balance Factor of a node is defined as:
When the balance factor goes beyond this range, rotations are performed.
Types of Rotations
LL Rotation (Right Rotation): Left-heavy subtree.
Key Concepts
AVL tree keeps a height field in each node.
Algorithm
1. Insertion Algorithm
1. Insert the key as in a normal BST.
BF = height(left) − height(right)
47
Advanced Data Structures Lab Manual B3CS104PC
2. Deletion Algorithm
1. Delete the node similar to BST deletion.
3. Search Algorithm
1. Compare the key with current node.
4. Traversal
Preorder traversal prints:
Program
1 #include <stdio.h>
2 #include
3
<stdlib.h>
4
typedef struct AVLNode {
5
int key;
6
struct AVLNode *left, *right;
7
int height;
8 } AVLNode;
9
14
// Utility to get maximum of two integers
15
int max(int a, int b) { return a > b ? a : b; }
16
48
Advanced Data Structures Lab Manual B3CS104PC
17
49
Advanced Data Structures Lab Manual B3CS104PC
18 // Create a new AVL Node
19 AVLNode* createNode(int key) {
20 AVLNode *n = (AVLNode*)malloc(sizeof(AVLNode));
21 n->key = key;
22 n->left = n->right = NULL;
23 n->height = 1;
24 return n;
25 }
26
27 // Right Rotate
28 AVLNode* rightRotate(AVLNode *y) {
29 AVLNode *x = y->left;
30 AVLNode *T2 = x->right;
31
32 x->right = y;
33 y->left = T2;
34
38 return x;
39 }
40
41 // Left Rotate
42 AVLNode* leftRotate(AVLNode *x) {
43 AVLNode *y = x->right;
44 AVLNode *T2 = y->left;
45
46 y->left = x;
47 x->right = T2;
48
52 return y;
53 }
54
50
Advanced Data Structures Lab Manual B3CS104PC
59 }
60
76 // LL Case
77 if (balance > 1 && key < root->left->key)
78 return rightRotate(root);
79
80 // RR Case
81 if (balance < -1 && key > root->right->key)
82 return leftRotate(root);
83
84 // LR Case
85 if (balance > 1 && key > root->left->key) {
86 root->left = leftRotate(root->left);
87 return rightRotate(root);
88 }
89
90 // RL Case
91 if (balance < -1 && key < root->right->key) {
92 root->right = rightRotate(root->right);
93 return leftRotate(root);
94 }
95
96 return root;
97 }
98
51
Advanced Data Structures Lab Manual B3CS104PC
99 // Get Inorder Successor
100 AVLNode* minValueNode(AVLNode *node) {
101 AVLNode *current = node;
102 while (current->left) current = current->left;
103 return current;
104 }
105
116 else {
117 if (!root->left || !root->right) {
118 AVLNode *temp = root->left ? root->left : root
->right;
119
120 if (!temp) {
121 temp = root;
122 root = NULL;
123 } else {
124 *root = *temp;
125 }
126 free(temp);
127 }
128 else {
129 AVLNode *temp = minValueNode(root->right);
130 root->key = temp->key;
131 root->right = deleteNode(root->right, temp->key
);
132 }
133 }
134
52
Advanced Data Structures Lab Manual B3CS104PC
137 root->height = max(height(root->left), height(root-
> right)) + 1;
138 int balance = getBalance(root);
139
140 // LL Case
141 if (balance > 1 && getBalance(root->left) >= 0)
142 return rightRotate(root);
143
144 // LR Case
145 if (balance > 1 && getBalance(root->left) < 0) {
146 root->left = leftRotate(root->left);
147 return rightRotate(root);
148 }
149
150 // RR Case
151 if (balance < -1 && getBalance(root->right) <= 0)
152 return leftRotate(root);
153
154 // RL Case
155 if (balance < -1 && getBalance(root->right) > 0) {
156 root->right = rightRotate(root->right);
157 return leftRotate(root);
158 }
159
163 // Search
164 AVLNode* search(AVLNode *root, int key) {
165 if (!root) return NULL;
166 if (key == root->key) return root;
167 if (key < root->key) return search(root->left, key);
168 return search(root->right, key);
169 }
170
53
Advanced Data Structures Lab Manual B3CS104PC
177 }
178
195 case 2:
196 printf("Enter key: ");
197 scanf("%d", &key);
198 root = deleteNode(root, key);
199 break;
200
201 case 3:
202 printf("Enter key: ");
203 scanf("%d", &key);
204 printf(search(root, key) ? "Found\n" : "Not
found\n");
205 break;
206
207 case 4:
208 printf("Preorder: ");
209 preorder(root);
210 printf("\n");
211 break;
212
213 case 5:
214 exit(0);
215 }
54
Advanced Data Structures Lab Manual B3CS104PC
216 }
217 return 0;
218
}
Sample Input
1
Enter key: 30
1
Enter key: 20
1
Enter key: 40
1
Enter key: 10
4
Expected Output
Preorder: 30 20 10 40
Observations
Insertions that caused imbalance triggered LL, RR, LR, or RL rotations.
Result
The AVL Tree was successfully implemented including insertion, deletion, search, and
preorder traversal. The tree maintained its balance through appropriate rotations after
each update operation.
55
Advanced Data Structures Lab Manual B3CS104PC
Viva Questions
1. What is the balance factor in an AVL tree?
It is the difference between the heights of the left and right subtrees:
BF = height(left) − height(right)
56
Chapter 8
Aim
To design and implement insertion, fix-up, and search operations of a Red–Black
Tree (RBT) in C, ensuring that the Red–Black Tree properties remain satisfied after
each insertion.
Problem Statement
A Red–Black Tree is a self-balancing binary search tree that guarantees O(log n) time
complexity for searching, insertion, and deletion. The objective of this experiment is to:
Insert keys into an RBT
Description
Red–Black Trees balance themselves using color properties and rotations. They are widely
used in:
STL map/set (C++)
57
Advanced Data Structures Lab Manual B3CS104PC
Red–Black Tree Properties
1. Every node is either RED or BLACK.
4. RED nodes cannot have RED parents (no two consecutive REDs).
5. Every path from a node to its descendant NIL nodes contains the same number of
BLACK nodes.
Balancing Techniques
Left Rotation – pushes heavier left subtree downward.
Algorithm
1. Insertion Algorithm
1. Insert new node like in a regular BST (color = RED).
2. Search Algorithm
1. Compare key with root.
58
Advanced Data Structures Lab Manual B3CS104PC
3. Inorder Traversal
Displays nodes in sorted order with colors:
1 #include <stdio.h>
2 #include
3
<stdlib.h>
4
typedef enum { RED, BLACK } Color;
5
6
typedef struct RBNode {
7
int key;
8 Color color;
9 struct RBNode *left, *right, *parent;
10 } RBNode;
11
14
RBNode* createNode(int key) {
15
RBNode *n =
16 (RBNode*)malloc(sizeof(RBNode)); n->key =
17 key;
18
n->color = RED;
n->left = n->right = n->parent = NIL;
19
return n;
20
}
21
22
// Left Rotation
23
void leftRotate(RBNode **root, RBNode *x)
24 { RBNode *y = x->right;
25
26
x->right = y->left;
27
if (y->left != NIL) y->left->parent = x;
28
y->parent = x->parent;
29
if (x->parent == NIL)
30
*root = y;
31
else if (x == x->parent->left)
59
Advanced Data Structures Lab Manual B3CS104PC
32
33
34
60
Advanced Data Structures Lab Manual B3CS104PC
35 else
36 x->parent->right = y;
37
38 y->left = x;
39 x->parent =
40 } y;
41
42 // Right Rotation
43 void rightRotate(RBNode **root, RBNode *y) {
44 RBNode *x = y->left;
45
46 y->left = x->right;
47 if (x->right != NIL) x->right->parent = y;
48
49 x->parent = y->parent;
50 if (y->parent == NIL)
51 *root = x;
52 else if (y == y->parent->left)
53 y->parent->left = x;
54 else
55 y->parent->right = x;
56
57 x->right = y;
58 y->parent =
59 } x;
60
65 if (z->parent == z->parent->parent->left) {
66
67 RBNode *y = z->parent->parent->right;
68
69 if (y->color == RED) {
70 z->parent->color = BLACK;
71 y->color = BLACK;
72 z->parent->parent->color = RED;
73 z = z->parent->parent;
74 }
61
Advanced Data Structures Lab Manual B3CS104PC
75 else {
62
Advanced Data Structures Lab Manual B3CS104PC
76 if (z == z->parent->right) {
77 z = z->parent;
78 leftRotate(root, z);
79 }
80 z->parent->color = BLACK;
81 z->parent->parent->color = RED;
82 rightRotate(root, z->parent->parent);
83 }
84 }
85 else {
86
87 RBNode *y = z->parent->parent->left;
88
89 if (y->color == RED) {
90 z->parent->color = BLACK;
91 y->color = BLACK;
92 z->parent->parent->color = RED;
93 z = z->parent->parent;
94 }
95 else {
96 if (z == z->parent->left) {
97 z = z->parent;
98 rightRotate(root, z);
99 }
100 z->parent->color = BLACK;
101 z->parent->parent->color = RED;
102 leftRotate(root, z->parent->parent);
103 }
104 }
105 }
106 (*root)->color = BLACK;
107 }
108
63
Advanced Data Structures Lab Manual B3CS104PC
117 if (z->key < x->key)
118 x = x->left;
119 else
120 x = x->right;
121 }
122
123 z->parent = y;
124 if (y == NIL)
125 *root = z;
126 else if (z->key < y->key)
127 y->left = z;
128 else
129 y->right = z;
130
64
Advanced Data Structures Lab Manual B3CS104PC
157 NIL->left = NIL->right = NIL->parent = NIL;
158
159
root = NIL;
160
while (1) {
161
printf("\n1. Insert\n2. Search\n3. Inorder\n4. Exit
162
\n");
printf("Enter choice: ");
163 scanf("%d", &choice);
164
165
switch (choice) {
166
case 1:
printf("Enter key: ");
167
scanf("%d", &key);
168
insertRB(&root, key);
169
break;
170
171 case 2:
172 printf("Enter key: ");
173 scanf("%d", &key);
174
printf(searchRB(root, key) != NIL ? "Found\n" :
"Not found\n");
175
break;
176
case 3:
177
inorder(root);
178 printf("\n");
179 break;
180
181
case 4:
exit(0);
182
}
183
}
184
return 0;
185
}
186
187
188
189
65
Advanced Data Structures Lab Manual B3CS104PC
Sample Input
1
Enter key: 20
66
Advanced Data Structures Lab Manual B3CS104PC
1
Enter key: 15
1
Enter key: 30
1
Enter key: 25
3
Expected Output
15(R) 20(B) 25(R) 30(B)
Observations
The newly inserted nodes are initially RED.
Result
Red–Black Tree insertion, fix-up, and search operations were successfully implemented.
The program maintains all Red–Black Tree balancing properties using rotations and
recoloring.
Viva Questions
1. State the properties of a Red–Black Tree.
All paths from a node to leaves contain the same number of BLACK nodes, root is
BLACK, etc.
67
Advanced Data Structures Lab Manual B3CS104PC
4. What is the purpose of rotations?
Rotations restore BST structure and maintain balancing properties.
68
Chapter 9
Aim
To design and implement a dictionary (key-based lookup structure) using hashing and
to perform basic operations such as insertion, searching, deletion, and display using the
open addressing technique with linear probing.
Problem Statement
A dictionary stores key-value pairs, enabling fast insertion, deletion, and search. The
challenge is to design a hash table of fixed size and implement collision resolution using
linear probing. The program should allow the user to:
Insert a key
Delete a key
Description
Hashing is an efficient technique for implementing dictionaries. A hash function maps
a key to an index of a hash table. Collisions occur when multiple keys map to the same
index. To handle collisions, we use:
69
Advanced Data Structures Lab Manual B3CS104PC
Special markers used:
Algorithm
1. Hash Function
1. Compute: index = key mod TABLE SIZE
2. Insert Operation
1. Compute initial index using the hash function.
3. Search Operation
1. Compute initial index.
4. Delete Operation
1. Search the key.
70
Advanced Data Structures Lab Manual B3CS104PC
5. Display Operation
1. For each index i:
1 #include <stdio.h>
2 #include
3
<stdlib.h>
4
#define TABLE_SIZE 10
5
#define EMPTY -1
6
#define DELETED -2
7
8 int hashTable[TABLE_SIZE];
9
10 // Hash function
11
int hash(int key) {
return key % TABLE_SIZE;
12
}
13
14
// Initialize hash table
15
void initTable() {
16 int i;
17 for (i = 0; i < TABLE_SIZE; i++)
18 hashTable[i] = EMPTY;
19
}
20
// Insert a key (linear probing)
21
void insert(int key) {
22
int index =
23
hash(key); int start
24
= index;
25
71
Advanced Data Structures Lab Manual B3CS104PC
28
29
30
72
Advanced Data Structures Lab Manual B3CS104PC
31
printf("Hash table full.\n");
32 return;
33 }
34 }
35 hashTable[index] = key;
36 }
37
49 if (index == start)
50 break;
51 }
52 return -1;
53 }
54
55 // Delete a key
56 void deleteKey(int key) {
57 int pos = search(key);
58
59 if (pos == -1) {
60 printf("Key not found.\n");
61 return;
62 }
63
64 hashTable[pos] = DELETED;
65 printf("Key %d deleted.\n", key);
66 }
67
73
Advanced Data Structures Lab Manual B3CS104PC
71 printf("\n--- Hash Table ---\n");
74
Advanced Data Structures Lab Manual B3CS104PC
72
76 if (hashTable[i] == EMPTY)
77 printf("EMPTY");
78 else if (hashTable[i] == DELETED)
79 printf("DELETED");
80 else
81 printf("%d", hashTable[i]);
82
83 printf("\n");
84 }
85 }
86
87 int main() {
88 int choice, key;
89
90 initTable();
91
92 while (1) {
93 printf("\n1. Insert\n2. Search\n3. Delete\n4.
Display\n5. Exit\n");
94 printf("Enter choice: ");
95 scanf("%d", &choice);
96
97 switch (choice) {
98 case 1:
99 printf("Enter key: ");
100 scanf("%d", &key);
101 insert(key);
102 break;
103
104 case 2:
105 printf("Enter key: ");
106 scanf("%d", &key);
107 printf(search(key) != -1 ? "Found\n" : "Not
found\n");
108 break;
109
110 case 3:
75
Advanced Data Structures Lab Manual B3CS104PC
111 printf("Enter key: ");
112 scanf("%d", &key);
113 deleteKey(key);
114 break;
115
116 case 4:
117 display();
118 break;
119
120 case 5:
121 exit(0);
122
123 default:
124 printf("Invalid choice.\n");
125 }
126 }
127
128 return 0;
129 }
Sample Input
1
Enter key: 25
1
Enter key: 15
1
Enter key: 35
4
Expected Output
--- Hash Table ---
0: EMPTY
1: EMPTY
2: EMPTY
3: EMPTY
4: EMPTY
5: 25
76
Advanced Data Structures Lab Manual B3CS104PC
6: 15
7: 35
8: EMPTY
9: EMPTY
Observations
Keys 25, 15, and 35 are placed based on their hash values and collisions.
Result
The dictionary operations (insert, search, delete, and display) were successfully imple-
mented using hashing with open addressing and linear probing.
Viva Questions
1. What is a hash function? What properties should it have?
It maps keys to table indices. Good hash functions are uniform, deterministic, and
fast to compute.
77
Chapter 10
Knuth–Morris–Pratt (KMP)
Pattern Matching Algorithm
Aim
To design and implement the Knuth–Morris–Pratt (KMP) pattern matching algorithm
in C, using the LPS (Longest Proper Prefix–Suffix) preprocessing technique to efficiently
search for occurrences of a pattern within a text.
Problem Statement
Given a text string T of length n and a pattern string P of length m, write a C program to
search for all occurrences of P in T without performing unnecessary re-comparisons.
The KMP algorithm must preprocess the pattern to compute the LPS array, which
enables efficient shifting without backtracking in the text.
Description
The KMP algorithm improves upon brute-force pattern matching by ensuring that
the text index never moves backward. Instead of re-checking already matched
characters, KMP uses a preprocessed table known as the LPS (Longest Proper
Prefix–Suffix) array.
Key Features
Avoids redundant comparisons.
78
Advanced Data Structures Lab Manual B3CS104PC
LPS (Longest Proper Prefix–Suffix) Array
For each prefix of the pattern, LPS[i] stores the length of the longest proper prefix
which is also a suffix. This helps determine how many characters can be skipped after a
mismatch.
Example:
Pattern: ABABAC LPS Array: [0, 0, 1, 2, 3, 0]
Algorithm
2. Maintain a length variable ‘len‘ to track the current prefix-suffix match length.
4. If mismatch:
Time Complexity
Preprocessing (LPS): O(m)
79
Advanced Data Structures Lab Manual B3CS104PC
Total Time Complexity: O(n + m)
Program
1 #include <stdio.h>
2 #include <string.h>
3
10 while (i < m) {
11 if (pat[i] == pat[len]) {
12 len++;
13 lps[i] = len;
14 i++;
15 } else {
16 if (len != 0)
17 len = lps[len - 1];
18 else {
19 lps[i] = 0;
20 i++;
21 }
22 }
23 }
24 }
25
32
computeLPS(pat, m, lps);
33
34
int i = 0, j = 0;
80
Advanced Data Structures Lab Manual B3CS104PC
35 while (i < n) {
36 if (pat[j] == txt[i]) {
37 i++;
38 j++;
39 }
40 if (j == m) {
41 printf("Pattern found at index %d\n", i - j);
42 j = lps[j - 1];
43 } else if (i < n && pat[j] != txt[i]) {
44 if (j != 0)
45 j = lps[j - 1];
46 else
47 i++;
48 }
49 }
50 }
51
52 int main() {
53 char txt[200], pat[100];
54
63 KMP(txt, pat);
64
65 return 0;
66 }
Sample Input
Enter text: ABABDABACDABABCABAB
Enter pattern: ABABCABAB
81
Advanced Data Structures Lab Manual B3CS104PC
Expected Output
Pattern found at index 10
Explanation of Output
The algorithm begins matching from left to right.
Whenever mismatch occurs, instead of rechecking all characters, the LPS array is
used to skip unnecessary comparisons.
Result
The Knuth–Morris–Pratt (KMP) algorithm was successfully implemented in C. The pro-
gram correctly computes the LPS array and efficiently finds pattern matches without
redundant comparisons, demonstrating linear-time string matching.
Viva Questions
1. What is the time complexity of KMP?
The time complexity is O(n + m), where n is text length and m is pattern
length.
82
Chapter 11
Aim
To write and execute a C program that implements the Naive (Brute-Force) pattern
matching algorithm to find all occurrences of a pattern within a given text.
Problem Statement
Given a text string T of length n and a pattern string P of length m, the task is to
compare P with every possible substring of T and identify all starting positions where
an exact match is found. This experiment demonstrates the simplest string searching
method, where characters are compared sequentially without using any preprocessing or
skipping techniques.
Description
The brute-force (naive) pattern matching algorithm is the simplest and most intuitive
method of searching for a substring within a text. It checks for a match by aligning the
pattern P at every possible starting position in the text T and comparing characters
one-by-one.
Characteristics
No preprocessing or heuristics used.
83
Advanced Data Structures Lab Manual B3CS104PC
Useful for small-scale and simple applications.
Algorithm
1. Read input text string T and pattern string P .
4. If no index satisfies equality, the pattern does not exist in the text.
Time Complexity
Best Case: O(n) (first characters mismatch frequently)
Program
1 #include <stdio.h>
2 #include <string.h>
3
84
Advanced Data Structures Lab Manual B3CS104PC
14 }
15 if (j == m)
16
printf("Pattern found at index %d\n", i);
}
17
}
18
19
int main() {
20
char txt[200], pat[100];
21
26
printf("Enter pattern: ");
27
fgets(pat, sizeof(pat),
28
stdin); pat[strcspn(pat, "\
29 n")] = ’\0’;
30
31 bruteForceMatch(txt, pat);
32
return 0;
33
34
Sample Input
Enter text: AABAACAADAABAABA
Enter pattern: AABA
Expected Output
Pattern found at index 0
Pattern found at index 9
Pattern found at index 12
Explanation of Output
The pattern “AABA” occurs at positions 0, 9, and 12 in the text.
86
Advanced Data Structures Lab Manual B3CS104PC
Result
The brute-force pattern matching algorithm was successfully implemented. The program
correctly identifies all occurrences of a given pattern in the text by performing sequential
character comparisons without using preprocessing tables.
Viva Questions
1. What is the worst-case time complexity of the brute-force algorithm?
The worst-case time complexity is O(nm), where n is the length of the text and m
is the length of the pattern.
87
Chapter 12
Aim
To design and implement the Boyer–Moore pattern matching algorithm in C using
the Bad-Character Heuristic, and to analyze its efficiency in comparison with other
string matching algorithms.
Problem Statement
Given a text string T of length n and a pattern string P of length m, write a C program
to find all occurrences of P in T using the Boyer–Moore algorithm. Implement the bad-
character heuristic to efficiently skip unnecessary comparisons and minimize the
number of character checks.
Description
The Boyer–Moore pattern matching algorithm is one of the most efficient string searching
methods. It improves upon naive pattern matching by using two ideas:
88
Advanced Data Structures Lab Manual B3CS104PC
skips portions of the text intelligently,
It is widely used in text editors, command-line tools (grep), and search engines.
Algorithm
3. If mismatch occurs:
Time Complexity
Best Case: O(n/m) due to large jumps.
89
Advanced Data Structures Lab Manual B3CS104PC
Program (Bad-Character Heuristic)
1 #include <stdio.h>
2 #include <string.h>
3
15
22 badCharHeuristic(pat, m, badchar);
23
27 int j = m - 1;
28
33 if (j < 0) {
34 printf("Pattern found at index %d\n", s);
35
90
Advanced Data Structures Lab Manual B3CS104PC
39 } else {
40 // Mismatch shift using bad character rule
41
int shift = j - badchar[(unsigned char)txt[s +
j]];
if (shift < 1) shift = 1;
42
s += shift;
43
}
44 }
45 }
46
47
int main() {
48
char txt[200], pat[100];
49
printf("Enter text: ");
50
fgets(txt, sizeof(txt),
51
stdin);
52
txt[strcspn(txt, "\n")] = ’\0’; // remove newline
53
58
boyerMoore(txt, pat);
59
return 0;
60
61
Input
Text: ABABDABACDABABCABAB
Pattern: ABABCABAB
Expected Output
Pattern found at index 10
Result
91
Advanced Data Structures Lab Manual B3CS104PC
The Boyer–Moore pattern matching algorithm was successfully implemented using the
Bad-Character heuristic. The program efficiently located pattern occurrences within the
92
Advanced Data Structures Lab Manual B3CS104PC
given text by minimizing unnecessary comparisons and using intelligent shifting strate-
gies.
Viva Questions
1. What are the heuristics used in the Boyer–Moore algorithm? Answer: Bad-
Character Heuristic and Good-Suffix Heuristic.
3. Compare Boyer–Moore with KMP in terms of shift strategy. Answer: KMP uses
prefix-based failure function and never skips characters in text. Boyer–Moore uses
mismatch-based shifts allowing larger jumps and is often faster.
4. What is the role of the Bad-Character Table? Answer: It stores the rightmost
occurrence of each character in the pattern to determine how far the pattern should
shift after mismatch.
5. What happens when the mismatched character does not exist in the pattern? An-
swer: The pattern shifts by m positions (pattern length), maximizing the skip.
6. Can Boyer–Moore scan text from left-to-right? Answer: No, it compares pattern
characters from right-to-left.
7. Why is the worst-case performance rare? Answer: Because the algorithm’s shifts
depend on rare cases of repeating patterns.
93