Advanced Data Structures Lab
Advanced Data Structures Lab
(UGC - Autonomous)
Lab Manual
Prepared By:
Mr. Jitendra Alaparthi
Associate Professor & Head, CSE
Holy Mary Institute of Technology & Science
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:
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 <stdlib.h>
3
3
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
4
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))
5
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
6
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.
7
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.
Understand heap-based selection strategy in Heap Sort.
Compare the time and space complexities of three major sorting algorithms.
Implement each algorithm in C and analyze differences.
Problem Statement
Write a C program that:
8
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.
Requires additional memory.
Consistent O(n log n) performance.
Heap Sort
Heap Sort uses a binary heap structure:
Characteristics:
9
Advanced Data Structures Lab Manual B3CS104PC
Not stable.
In-place sorting algorithm.
Consistent O(n log n) performance.
Quick Sort
Quick Sort also follows Divide and Conquer:
Characteristics:
12 i = 0; j = 0; k = l;
13 while (i < n1 && j < n2) {
14 if (L[i] <= R[j]) a[k++] = L[i++];
10
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
11
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. Quick
Sort\n4. Exit\n");
93 printf("Enter choice: ");
94 scanf("%d", &choice);
95
12
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]
13
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?
14
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:
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:
Search Algorithm
1. Perform linear or binary search on the current node’s keys.
16
Advanced Data Structures Lab Manual B3CS104PC
Deletion Algorithm (Conceptual Overview)
B-Tree deletion is complex and involves multiple cases:
17
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;
18
Advanced Data Structures Lab Manual B3CS104PC
64
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])
96 i++;
97 }
98 insertNonFull(x->child[i], k);
99 }
100 }
101
19
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
20
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
21
Advanced Data Structures Lab Manual B3CS104PC
Observations
Node splits occurred when inserting keys into a full node.
The B-Tree remained balanced after every insertion.
Keys are always stored in sorted order within nodes.
Searches used binary-like navigation through children.
Height of the tree grows slowly due to high branching factor (2t children).
Advantages of B-Trees
Efficient for disk-based storage.
Logarithmic height, even for millions of entries.
Supports large block size and minimizes disk I/O.
Balanced tree; no rotations required (unlike AVL).
Time Complexity
Search: O(t log n)
Insertion: O(t log n)
Deletion: 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.
22
Advanced Data Structures Lab Manual B3CS104PC
Viva Questions
1. What is a B-Tree? How does it differ from AVL or Red-Black Trees?
23
Chapter 4
Aim
To implement the fundamental operations of a Min-Max Heap, specifically:
Objective
The objective of this experiment is to understand:
24
Advanced Data Structures Lab Manual B3CS104PC
Delete-Min: Remove the element with the lowest priority
Delete-Max: Remove the element with the highest priority
Insert: Insert an element with a given priority
Find-Min and Find-Max: Retrieve minimum and maximum elements
A Min-Max Heap is an efficient implementation of a DEPQ.
Min-Max Heap
A Min-Max Heap is a complete binary tree in which:
Algorithms
Insertion Algorithm
1. Insert the key into both the Min Heap and Max Heap.
25
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)
6 typedef struct {
7 int minHeap[MAX];
8 int maxHeap[MAX];
9 int size;
10 } MinMax;
11
26
Advanced Data Structures Lab Manual B3CS104PC
17 if (l < n && a[l] < a[smallest]) smallest = l;
18 if (r < n && a[r] < a[smallest]) smallest = r;
19 if (smallest != i) {
20 swap(&a[i], &a[smallest]);
21 minHeapify(a, n, smallest);
22 }
23 }
24
27
Advanced Data Structures Lab Manual B3CS104PC
58 int root = mm->minHeap[0];
59 mm->minHeap[0] = mm->minHeap[n-1];
60 mm->size--;
61 minHeapify(mm->minHeap, mm->size, 0);
62 return root;
63 }
64
91 int main() {
92 MinMax mm;
93 [Link] = 0;
94 int choice, key, x;
95
96 while (1) {
28
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:
29
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.
The maximum value is always at the root of the Max Heap.
Insert operation requires heap reconstruction, making the approach less optimal.
30
Advanced Data Structures Lab Manual B3CS104PC
Search operation is linear because heap property does not support binary search.
The two-heap method demonstrates double-ended priority queue behavior but is
not a true Min-Max Heap.
31
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).
32
Chapter 5
Aim
To implement the core operations of a Leftist Tree (also called a Leftist Heap), namely:
Insertion of a key
Deletion of the minimum element (Delete-Min)
Searching for a key
Displaying the heap (Inorder traversal)
using the merge-based leftist heap implementation.
Objective
The purpose of this experiment is to understand:
How Leftist Trees maintain structural properties to support efficient merging
How merge operations form the basis of insert and delete-min
How null-path length (NPL) influences the structure of the tree
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:
33
Advanced Data Structures Lab Manual B3CS104PC
Key value
Left and right children
Null Path Length (NPL), also called dist
Null Path Length (NPL)
The Null Path Length of a node is defined as:
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.
34
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>
35
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.
Insertion internally called the merge operation, ensuring logarithmic performance.
Delete-min operation reduced heap height by merging the root’s subtrees.
Search stops early if key ¡ current node (due to heap property).
The right spine of a leftist heap is always the shortest.
Time Complexity Analysis
Merge: O(log n)
Insert: O(log n)
Delete-Min: O(log n)
Search: O(n) (heap property does not guarantee BST order)
36
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.
37
Chapter 6
Aim
To develop and implement a program in C for performing the following operations using
a Binomial Heap:
Insertion of a key
Deletion of the minimum element (Delete-Min)
Searching for an element
Displaying the heap in Binomial Tree format
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:
38
Advanced Data Structures Lab Manual B3CS104PC
B 0 is a single node.
B k is made by linking two Bk−1 trees, making one the leftmost child of the other.
Properties:
Height of B is k.
k
Number of nodes is 2 . k
Binomial Heap
A Binomial Heap is a collection of Binomial Trees satisfying:
Major Operations
1. Union Operation The most important operation:
sibling pointers
child pointers
39
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>
40
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.
Insert operation frequently triggers union-heaps mechanism.
Delete-Min efficiently removes minimum using list reversal of children.
Search operation is recursive across sibling and child trees.
At all times, heap maintains at most one tree of each degree.
Time Complexity Analysis
Insert: O(log n)
Delete-Min: O(log n)
Search: O(n)
Union: O(log n)
41
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.
42
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
Delete a node from an AVL Tree
Search for a key in the AVL Tree
Automatically rebalance the tree using rotations
Display the tree using preorder traversal
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:
43
Advanced Data Structures Lab Manual B3CS104PC
Valid values:
BF = −1, 0, +1
When the balance factor goes beyond this range, rotations are performed.
Types of Rotations
LL Rotation (Right Rotation): Left-heavy subtree.
RR Rotation (Left Rotation): Right-heavy subtree.
LR Rotation (Left-Right): Left child right-heavy.
RL Rotation (Right-Left): Right child left-heavy.
These rotations restructure the AVL Tree to restore balance.
Key Concepts
AVL tree keeps a height field in each node.
After every insertion or deletion, heights are updated bottom-up.
If imbalance is detected, an appropriate rotation is applied.
Algorithm
1. Insertion Algorithm
1. Insert the key as in a normal BST.
BF = height(lef t) − height(right)
3. Search Algorithm
1. Compare the key with current node.
4. Traversal
Preorder traversal prints:
Program
1 #include <stdio.h>
2 #include <stdlib.h>
3
45
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
46
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
47
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
48
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
49
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 }
50
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.
After every insertion or deletion, node heights are recalculated.
AVL Tree ensures height remains O(log n).
Preorder traversal displays structure accurately after 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.
51
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(lef t) − height(right)
52
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
Perform search on an RBT
Apply rotations and recoloring to maintain RBT properties
Display the inorder traversal with node colors
Description
Red–Black Trees balance themselves using color properties and rotations. They are widely
used in:
STL map/set (C++)
Linux kernel process scheduler
Java TreeMap, TreeSet
Memory management modules
Each node is either RED or BLACK, and NIL (leaf) nodes are always BLACK.
53
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.
Right Rotation – pushes heavier right subtree downward.
Recoloring – flips colors to maintain Black-Height.
Fix-Up – applied after insertion to restore RBT properties.
Algorithm
1. Insertion Algorithm
1. Insert new node like in a regular BST (color = RED).
2. Search Algorithm
1. Compare key with root.
54
Advanced Data Structures Lab Manual B3CS104PC
3. Inorder Traversal
Displays nodes in sorted order with colors:
23 // Left Rotation
24 void leftRotate(RBNode **root, RBNode *x) {
25 RBNode *y = x->right;
26
27 x->right = y->left;
28 if (y->left != NIL) y->left->parent = x;
29
30 y->parent = x->parent;
31 if (x->parent == NIL)
32 *root = y;
33 else if (x == x->parent->left)
34 x->parent->left = y;
55
Advanced Data Structures Lab Manual B3CS104PC
35 else
36 x->parent->right = y;
37
38 y->left = x;
39 x->parent = y;
40 }
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 = x;
59 }
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 }
75 else {
56
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
57
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
58
Advanced Data Structures Lab Manual B3CS104PC
157 NIL->left = NIL->right = NIL->parent = NIL;
158
173 case 2:
174 printf("Enter key: ");
175 scanf("%d", &key);
176 printf(searchRB(root, key) != NIL ? "Found\n" :
"Not found\n");
177 break;
178
179 case 3:
180 inorder(root);
181 printf("\n");
182 break;
183
184 case 4:
185 exit(0);
186 }
187 }
188 return 0;
189 }
Sample Input
1
Enter key: 20
59
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.
Rotations and recoloring ensure RBT properties remain valid.
Root always becomes BLACK after insertion.
Inorder traversal prints keys in sorted order with node colors.
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.
60
Advanced Data Structures Lab Manual B3CS104PC
4. What is the purpose of rotations?
Rotations restore BST structure and maintain balancing properties.
61
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
Search for a key
Delete a key
Display the hash table
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:
62
Advanced Data Structures Lab Manual B3CS104PC
Special markers used:
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.
63
Advanced Data Structures Lab Manual B3CS104PC
5. Display Operation
1. For each index i:
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) {
12 return key % TABLE_SIZE;
13 }
14
30 if (index == start) {
64
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
65
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:
66
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
67
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.
Linear probing resolves collisions by checking the next available slot.
Deletion leaves DELETED markers to preserve probing sequences.
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.
68
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.
Ensures linear-time performance: O(n + m).
Particularly efficient for long patterns and repetitive strings.
69
Advanced Data Structures Lab Manual B3CS104PC
LPS (Longest Proper Prefix–Suffix) Array
For each prefix of the pattern, LP S[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
Step 1: Compute LPS Array
1. Initialize LPS array with 0 at index 0.
2. Maintain a length variable ‘len‘ to track the current prefix-suffix match length.
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;
71
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
72
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.
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.
73
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.
Always checks from left to right.
74
Advanced Data Structures Lab Manual B3CS104PC
Useful for small-scale and simple applications.
Performs poorly on long texts with repeated characters.
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)
Worst Case: O(nm) (repeated characters, e.g., text = “AAAAAA”, pattern =
“AAA”)
75
Advanced Data Structures Lab Manual B3CS104PC
14 }
15 if (j == m)
16 printf("Pattern found at index %d\n", i);
17 }
18 }
19
20 int main() {
21 char txt[200], pat[100];
22
31 bruteForceMatch(txt, pat);
32
33 return 0;
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.
At every matching position, all characters of the pattern match sequentially.
When mismatch occurs, only one shift is made—no skipping optimizations.
76
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.
77
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:
Algorithm
Step 1: Preprocessing (Bad-Character Table)
1. Initialize an array badchar[256] with all values set to −1.
3. If mismatch occurs:
Time Complexity
Best Case: O(n/m) due to large jumps.
Average Case: Sub-linear time O(n).
Worst Case: O(n · m) (rare).
79
Advanced Data Structures Lab Manual B3CS104PC
Program (Bad-Character Heuristic)
1 #include <stdio.h>
2 #include <string.h>
3
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
80
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]];
42 if (shift < 1) shift = 1;
43 s += shift;
44 }
45 }
46 }
47
48 int main() {
49 char txt[200], pat[100];
50
59 boyerMoore(txt, pat);
60 return 0;
61 }
Expected Output
Pattern found at index 10
Result
The Boyer–Moore pattern matching algorithm was successfully implemented using the
Bad-Character heuristic. The program efficiently located pattern occurrences within the
81
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.
82