Data Structures Record
Data Structures Record
1.
Write a program that uses functions to perform the following operations on singly linked
Aim
Program Logic
1. createList(): This function allows the user to create nodes for a linked list by inputting values until
-1 is entered, which stops node creation.
2. insertNode(): This function inserts a new node at a specified position in the list (0 for beginning).
3. deleteNode(): This function deletes a node at a specified position in the list (0 for beginning).
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
};
// Function Prototypes
void createList();
void insertNode();
void deleteNode();
2
void traverseList();
int main() {
int choice;
while (1) {
// Menu
printf("1. Create List\n2. Insert Node\n3. Delete Node\n4. Traverse List\n5. Exit\n");
scanf("%d", &choice);
switch (choice) {
// Function Definitions
// i) Creation
void createList() {
int value;
3
scanf("%d", &value);
newNode->data = value;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
} else {
temp = temp->next;
temp->next = newNode;
scanf("%d", &value);
// ii) Insertion
void insertNode() {
scanf("%d", &position);
scanf("%d", &value);
newNode->data = value;
newNode->next = NULL;
if (position == 0) {
newNode->next = head;
head = newNode;
} else {
temp = temp->next;
if (temp == NULL) {
free(newNode);
} else {
newNode->next = temp->next;
temp->next = newNode;
// iii) Deletion
5
void deleteNode() {
int position;
scanf("%d", &position);
if (position == 0) {
if (head != NULL) {
head = head->next;
free(temp);
} else {
printf("List is empty.\n");
} else {
prev = temp;
temp = temp->next;
if (temp == NULL) {
} else {
prev->next = temp->next;
free(temp);
}
6
// iv) Traversal
void traverseList() {
if (temp == NULL) {
printf("List is empty.\n");
} else {
temp = temp->next;
printf("NULL\n");
• Output:
o The program displays a menu with options to create, insert, delete, and traverse the linked
list.
o Upon selecting Create List, the user can input values for nodes until -1 is entered to stop.
o Insert Node allows inserting a new node at a specific position in the list.
• Results:
o The program successfully performs singly linked list operations as chosen by the user,
modifying and displaying the list accordingly.
7
2. Write a program that uses functions to perform the following operations on doubly linked
Aim
Program Logic
1. createList(): Allows the user to input values to create nodes in a doubly linked list until -1 is
entered, which stops node creation.
2. insertNode(): Inserts a new node at a specified position in the list (0 for beginning).
4. traverseList(): Prints all elements in the doubly linked list from head to tail.
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
};
// Function Prototypes
void createList();
void insertNode();
void deleteNode();
8
void traverseList();
int main() {
int choice;
while (1) {
// Menu
printf("1. Create List\n2. Insert Node\n3. Delete Node\n4. Traverse List\n5. Exit\n");
scanf("%d", &choice);
switch (choice) {
// Function Definitions
// i) Creation
void createList() {
int value;
9
scanf("%d", &value);
newNode->data = value;
if (head == NULL) {
head = newNode;
} else {
temp = head;
temp = temp->next;
temp->next = newNode;
newNode->prev = temp;
scanf("%d", &value);
// ii) Insertion
void insertNode() {
scanf("%d", &position);
scanf("%d", &value);
newNode->data = value;
if (position == 0) {
if (head != NULL) {
newNode->next = head;
head->prev = newNode;
head = newNode;
} else {
temp = temp->next;
if (temp == NULL) {
free(newNode);
} else {
newNode->next = temp->next;
if (temp->next != NULL) {
temp->next->prev = newNode;
11
temp->next = newNode;
newNode->prev = temp;
// iii) Deletion
void deleteNode() {
int position;
scanf("%d", &position);
if (position == 0) {
if (head != NULL) {
head = head->next;
if (head != NULL) {
head->prev = NULL;
free(temp);
} else {
printf("List is empty.\n");
} else {
temp = temp->next;
}
12
if (temp == NULL) {
} else {
if (temp->prev != NULL) {
temp->prev->next = temp->next;
if (temp->next != NULL) {
temp->next->prev = temp->prev;
free(temp);
// iv) Traversal
void traverseList() {
if (temp == NULL) {
printf("List is empty.\n");
} else {
temp = temp->next;
printf("NULL\n");
}
13
• Output:
o The program displays a menu with options to create, insert, delete, and traverse the
doubly linked list.
o Upon selecting Create List, the user can input values for nodes until -1 is entered to stop.
o Insert Node allows inserting a new node at a specific position in the list.
o Traverse List displays all nodes in the list from head to tail.
• Results:
o The program successfully performs doubly linked list operations as chosen by the user,
modifying and displaying the list accordingly.
3. Write a program that uses functions to perform the following operations on circular linked
Aim
Program Logic
1. createList(): Allows the user to input values to create nodes in a circular linked list until -1 is
entered, which stops node creation.
2. insertNode(): Inserts a new node at a specified position in the list (0 for beginning).
4. traverseList(): Prints all elements in the circular linked list starting from the head and looping back
to it.
#include <stdio.h>
#include <stdlib.h>
struct Node {
14
int data;
};
// Function Prototypes
void createList();
void insertNode();
void deleteNode();
void traverseList();
int main() {
int choice;
while (1) {
// Menu
printf("1. Create List\n2. Insert Node\n3. Delete Node\n4. Traverse List\n5. Exit\n");
scanf("%d", &choice);
switch (choice) {
// Function Definitions
// i) Creation
void createList() {
int value;
scanf("%d", &value);
newNode->data = value;
newNode->next = newNode;
if (head == NULL) {
head = newNode;
newNode->next = head;
} else {
temp = head;
temp = temp->next;
}
16
temp->next = newNode;
newNode->next = head;
scanf("%d", &value);
// ii) Insertion
void insertNode() {
scanf("%d", &position);
scanf("%d", &value);
newNode->data = value;
newNode->next = NULL;
if (position == 0) {
if (head == NULL) {
head = newNode;
newNode->next = head;
} else {
temp = temp->next;
newNode->next = head;
temp->next = newNode;
head = newNode;
} else {
temp = temp->next;
newNode->next = temp->next;
temp->next = newNode;
// iii) Deletion
void deleteNode() {
int position;
scanf("%d", &position);
if (head == NULL) {
printf("List is empty.\n");
return;
}
18
if (position == 0) {
if (head->next == head) {
free(head);
head = NULL;
} else {
temp = temp->next;
temp->next = head->next;
free(head);
head = temp->next;
} else {
prev = temp;
temp = temp->next;
if (temp == head) {
} else {
prev->next = temp->next;
free(temp);
// iv) Traversal
void traverseList() {
19
if (head == NULL) {
printf("List is empty.\n");
} else {
do {
temp = temp->next;
printf("(back to head)\n");
• Output:
o The program displays a menu with options to create, insert, delete, and traverse the
circular linked list.
o Upon selecting Create List, the user can input values for nodes until -1 is entered to stop.
o Insert Node allows inserting a new node at a specific position in the list.
o Traverse List displays all nodes in the list starting from head and looping back to head.
• Results:
o The program successfully performs circular linked list operations as chosen by the user,
modifying and displaying the list accordingly.
Aim
Program Logic
1. push(): Adds an element to the top of the stack if it's not full.
#include <stdio.h>
#define MAX 5
// Array-based Stack
int stack[MAX];
// Function Prototypes
void push();
void pop();
void display();
int main() {
int choice;
while (1) {
// Menu
scanf("%d", &choice);
21
switch (choice) {
// Push operation
void push() {
int value;
if (top == MAX - 1) {
printf("Stack Overflow!\n");
} else {
scanf("%d", &value);
stack[++top] = value;
// Pop operation
void pop() {
if (top == -1) {
printf("Stack Underflow!\n");
} else {
void display() {
if (top == -1) {
printf("Stack is empty.\n");
} else {
printf("\n");
• Output: The program displays options to push, pop, display, or exit the stack operations.
• Results: This program successfully performs stack operations using arrays, displaying stack
elements and handling overflow and underflow conditions appropriately.
Aim
Program Logic
1. push(): Creates a new node and inserts it at the top of the stack.
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
};
// Function Prototypes
void push();
void pop();
void display();
int main() {
int choice;
while (1) {
// Menu
scanf("%d", &choice);
switch (choice) {
// Push operation
void push() {
int value;
if (newNode == NULL) {
} else {
scanf("%d", &value);
newNode->data = value;
newNode->next = top;
top = newNode;
// Pop operation
void pop() {
if (top == NULL) {
printf("Stack Underflow!\n");
} else {
25
top = top->next;
free(temp);
void display() {
if (top == NULL) {
printf("Stack is empty.\n");
} else {
temp = temp->next;
printf("\n");
• Output: This program shows a menu with options to push, pop, display, or exit.
• Results: This program successfully performs stack operations using pointers, handling memory
dynamically and providing stack functionality.
26
Aim
Program Logic
1. enqueue(): Adds an element at the rear of the queue if it's not full.
2. dequeue(): Removes an element from the front if the queue is not empty.
#include <stdio.h>
#define MAX 5
// Array-based Queue
int queue[MAX];
// Function Prototypes
void enqueue();
void dequeue();
void display();
int main() {
int choice;
while (1) {
// Menu
scanf("%d", &choice);
switch (choice) {
// Enqueue operation
void enqueue() {
int value;
if (rear == MAX - 1) {
printf("Queue Overflow!\n");
} else {
scanf("%d", &value);
queue[++rear] = value;
// Dequeue operation
28
void dequeue() {
printf("Queue Underflow!\n");
} else {
void display() {
if (front == -1) {
printf("Queue is empty.\n");
} else {
printf("\n");
• Results: This program successfully performs queue operations using arrays, with overflow and
underflow checks.
29
Aim
Program Logic
1. enqueue(): Creates a new node and adds it at the rear of the queue.
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
};
// Function Prototypes
void enqueue();
void dequeue();
void display();
int main() {
int choice;
while (1) {
30
// Menu
scanf("%d", &choice);
switch (choice) {
// Enqueue operation
void enqueue() {
int value;
if (newNode == NULL) {
} else {
scanf("%d", &value);
newNode->data = value;
newNode->next = NULL;
31
if (rear == NULL) {
} else {
rear->next = newNode;
rear = newNode;
// Dequeue operation
void dequeue() {
if (front == NULL) {
printf("Queue Underflow!\n");
} else {
front = front->next;
if (front == NULL) {
rear = NULL;
free(temp);
void display() {
if (front == NULL) {
32
printf("Queue is empty.\n");
} else {
temp = temp->next;
printf("\n");
• Output: This program shows a menu with options to enqueue, dequeue, display, or exit.
• Results: The program performs queue operations successfully using pointers, handling dynamic
memory and maintaining the front and rear nodes properly.
6. Write a program that implements the following sorting methods to sort a given list of integers
in ascending order
Aim
To implement the Quick Sort algorithm to sort a list of integers in ascending order.
Program Logic
Quick Sort: A divide-and-conquer algorithm that partitions the array around a pivot element and
recursively sorts the subarrays.
33
#include <stdio.h>
int main() {
int n;
scanf("%d", &n);
int arr[n];
scanf("%d", &arr[i]);
quickSort(arr, 0, n - 1);
printf("\n");
return 0;
quickSort(arr, pi + 1, high);
// Partition function
i++;
arr[i] = arr[j];
arr[j] = temp;
arr[i + 1] = arr[high];
arr[high] = temp;
return (i + 1);
}
35
Aim
To implement the Heap Sort algorithm to sort a list of integers in ascending order.
Program Logic
Heap Sort: Builds a max heap from the array, then repeatedly extracts the maximum element and
rebuilds the heap.
#include <stdio.h>
int main() {
int n;
scanf("%d", &n);
int arr[n];
scanf("%d", &arr[i]);
heapSort(arr, n);
printf("\n");
return 0;
heapify(arr, n, i);
arr[0] = arr[i];
arr[i] = temp;
heapify(arr, i, 0);
// Heapify function
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
largest = left;
}
37
largest = right;
if (largest != i) {
arr[i] = arr[largest];
arr[largest] = temp;
heapify(arr, n, largest);
Aim
To implement the Merge Sort algorithm to sort a list of integers in ascending order.
Program Logic
Merge Sort: A divide-and-conquer algorithm that divides the array into two halves, recursively
sorts them, and then merges the sorted halves.
#include <stdio.h>
int main() {
int n;
scanf("%d", &n);
int arr[n];
scanf("%d", &arr[i]);
mergeSort(arr, 0, n - 1);
printf("\n");
return 0;
}
39
// Merge function
int i = 0, j = 0, k = left;
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
k++;
arr[k] = L[i];
i++;
k++;
40
arr[k] = R[j];
j++;
k++;
Each program takes an input list of integers, sorts it in ascending order, and displays the sorted list. The
output demonstrates that the sorting methods work correctly for each algorithm.
7. Write a program to implement the tree traversal methods( Recursive and Non Recursive).
Aim
To implement recursive tree traversal methods (Preorder, Inorder, and Postorder) for a binary tree, with
the tree structure provided by the user at runtime.
Program Logic
1. Recursive Traversals: The traversal is done using recursive functions to visit each node.
#include <stdio.h>
#include <stdlib.h>
struct Node {
41
int data;
};
// Function declarations
if (root == NULL) {
return createNode(data);
char choice;
return root;
int main() {
int n, rootValue;
42
scanf("%d", &rootValue);
scanf("%d", &n);
int data;
scanf("%d", &data);
preorder(root);
printf("\n");
inorder(root);
printf("\n");
postorder(root);
printf("\n");
return 0;
43
newNode->data = data;
return newNode;
if (root != NULL) {
preorder(root->left);
preorder(root->right);
if (root != NULL) {
inorder(root->left);
inorder(root->right);
if (root != NULL) {
postorder(root->left);
postorder(root->right);
Aim
To implement non-recursive tree traversal methods (Preorder, Inorder, and Postorder) using a stack, with
the tree structure provided by the user at runtime.
Program Logic
1. Non-Recursive Traversals: We use a stack to simulate the recursion in the traversal process.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
struct Node {
int data;
};
45
struct Stack {
int top;
int capacity;
};
// Function declarations
if (root == NULL) {
return createNode(data);
char choice;
return root;
int main() {
int n, rootValue;
scanf("%d", &rootValue);
scanf("%d", &n);
int data;
scanf("%d", &data);
preorder(root);
printf("\n");
inorder(root);
printf("\n");
47
postorder(root);
printf("\n");
return 0;
newNode->data = data;
return newNode;
stack->capacity = capacity;
stack->top = -1;
return stack;
}
48
stack->arr[++stack->top] = node;
return stack->arr[stack->top--];
push(stack, root);
while (!isEmpty(stack)) {
if (node->right != NULL) {
push(stack, node->right);
if (node->left != NULL) {
push(stack, node->left);
}
49
push(stack, curr);
curr = curr->left;
curr = pop(stack);
curr = curr->right;
push(stack1, root);
50
while (!isEmpty(stack1)) {
push(stack2, node);
if (node->left != NULL) {
push(stack1, node->left);
if (node->right != NULL) {
push(stack1, node->right);
while (!isEmpty(stack2)) {
Explanation:
o Then, users can specify where each new node should be inserted (left or right of a
specified node).
2. For each traversal (Preorder, Inorder, Postorder), the program displays the result after traversal
using either recursion or a stack for non-recursive traversal.
Sample Input/Output:
Example Input:
Example Output:
Aim
To implement a Binary Search Tree (BST) and perform the following operations:
• Insertion
Program Logic
1. Insertion: Insert a node into the BST by comparing its value with the current node.
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
};
// Function declarations
int main() {
int n, data;
scanf("%d", &n);
scanf("%d", &data);
inorder(root);
printf("\n");
preorder(root);
printf("\n");
postorder(root);
printf("\n");
return 0;
newNode->data = data;
return newNode;
if (root == NULL) {
return createNode(data);
54
} else {
return root;
if (root != NULL) {
inorder(root->left);
inorder(root->right);
if (root != NULL) {
preorder(root->left);
preorder(root->right);
if (root != NULL) {
postorder(root->left);
postorder(root->right);
Output:
Inorder Traversal: 2 5 7 10 15
Preorder Traversal: 10 5 2 7 15
Postorder Traversal: 2 7 5 15 10
Results:
• Inorder Traversal: 2 5 7 10 15
• Preorder Traversal: 10 5 2 7 15
• Postorder Traversal: 2 7 5 15 10
Program 2: B-Tree
Aim
• Insertion
• Traversal
Program Logic
1. Insertion: Insert a node into the B-tree by following the properties of the B-tree.
56
#include <stdio.h>
#include <stdlib.h>
struct BTreeNode {
int numKeys;
int isLeaf;
};
// Function declarations
int main() {
int n, data;
scanf("%d", &n);
57
scanf("%d", &data);
insert(&root, data);
inorder(root);
printf("\n");
return 0;
node->isLeaf = isLeaf;
node->numKeys = 0;
node->children[i] = NULL;
return node;
if (*root == NULL) {
*root = createNode(1);
}
58
if ((*root)->numKeys == M - 1) {
newRoot->children[0] = *root;
splitChild(newRoot, 0, *root);
*root = newRoot;
insertNonFull(*root, key);
newChild->numKeys = M / 2;
if (!child->isLeaf) {
child->numKeys = M / 2;
parent->children[i + 1] = parent->children[i];
59
parent->children[index + 1] = newChild;
parent->keys[i + 1] = parent->keys[i];
parent->numKeys++;
int i = node->numKeys - 1;
if (node->isLeaf) {
node->keys[i + 1] = node->keys[i];
i--;
node->keys[i + 1] = key;
node->numKeys++;
} else {
i--;
i++;
if (node->children[i]->numKeys == M - 1) {
splitChild(node, i, node->children[i]);
i++;
insertNonFull(node->children[i], key);
if (root != NULL) {
inorder(root->children[i]);
inorder(root->children[root->numKeys]);
Output:
Results:
• Inorder Traversal: 5 10 15 20 25
61
Program 3: B+ Tree
Aim
• Insertion
• Traversal
Program Logic
#include <stdio.h>
#include <stdlib.h>
struct BPlusNode {
int numKeys;
int isLeaf;
};
// Function declarations
int main() {
int n, data;
scanf("%d", &n);
scanf("%d", &data);
insert(&root, data);
inorder(root);
printf("\n");
return 0;
node->isLeaf = isLeaf;
node->numKeys = 0;
node->next = NULL;
node->children[i] = NULL;
63
return node;
if (*root == NULL) {
*root = createNode(1);
if ((*root)->numKeys == M - 1) {
newRoot->children[0] = *root;
splitChild(newRoot, 0, *root);
*root = newRoot;
insertNonFull(*root, key);
newChild->numKeys = M / 2;
}
64
if (!child->isLeaf) {
child->numKeys = M / 2;
parent->children[i + 1] = parent->children[i];
parent->children[index + 1] = newChild;
parent->keys[i + 1] = parent->keys[i];
parent->numKeys++;
int i = node->numKeys - 1;
if (node->isLeaf) {
node->keys[i + 1] = node->keys[i];
i--;
node->keys[i + 1] = key;
65
node->numKeys++;
} else {
i--;
i++;
if (node->children[i]->numKeys == M - 1) {
splitChild(node, i, node->children[i]);
i++;
insertNonFull(node->children[i], key);
if (root != NULL) {
inorder(root->children[i]);
inorder(root->children[root->numKeys]);
Output:
Results:
• Inorder Traversal: 5 10 15 20 25
Aim
To implement an AVL Tree (a self-balancing binary search tree) and perform the following operations:
• Insertion
Program Logic
1. Insertion: Insert nodes into the AVL Tree while ensuring that the tree remains balanced after each
insertion.
2. Balancing: Perform rotations (left and right) when necessary to maintain the AVL property (the
height of the left and right subtrees can differ by at most 1).
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
int height;
};
// Function declarations
int main() {
int n, data;
scanf("%d", &n);
scanf("%d", &data);
}
68
inorder(root);
printf("\n");
preorder(root);
printf("\n");
postorder(root);
printf("\n");
return 0;
node->data = data;
return node;
if (node == NULL)
return 0;
return node->height;
69
return (a > b) ? a : b;
if (node == NULL)
return 0;
// Right rotation
x->right = y;
y->left = T2;
return x;
// Left rotation
70
y->left = x;
x->right = T2;
return y;
if (node == NULL)
return createNode(data);
else
return node;
return rightRotate(node);
return leftRotate(node);
node->left = leftRotate(node->left);
return rightRotate(node);
node->right = rightRotate(node->right);
return leftRotate(node);
return node;
// Inorder Traversal
if (root != NULL) {
inorder(root->left);
inorder(root->right);
}
72
// Preorder Traversal
if (root != NULL) {
preorder(root->left);
preorder(root->right);
// Postorder Traversal
if (root != NULL) {
postorder(root->left);
postorder(root->right);
Output:
Inorder Traversal: 5 10 20 25 30
Preorder Traversal: 20 10 5 25 30
Postorder Traversal: 5 10 25 30 20
73
Results:
• Inorder Traversal: 5 10 20 25 30
• Preorder Traversal: 20 10 5 25 30
• Postorder Traversal: 5 10 25 30 20
Aim
• Insertion
• Traversal
Program Logic
1. Insertion: Insert a node into the tree and then fix any violations of the Red-Black Tree properties
(color of the nodes, root properties, and balancing).
3. Red nodes cannot have red children (no two consecutive red nodes).
4. Every path from a node to its descendant NULL nodes must have the same number of black nodes.
Operations:
1. Insertion: Insert nodes while ensuring the Red-Black properties are maintained using rotations
(left and right) and color flips.
Approach:
2. Rebalance the tree by checking the violation of the Red-Black properties and performing
necessary rotations.
#include <stdio.h>
#include <stdlib.h>
#define RED 0
#define BLACK 1
struct Node {
int data;
};
newNode->data = data;
return newNode;
x->right = y->left;
if (y->left != NULL) {
y->left->parent = x;
y->parent = x->parent;
if (x->parent == NULL) {
*root = y;
} else if (x == x->parent->left) {
x->parent->left = y;
} else {
x->parent->right = y;
y->left = x;
x->parent = y;
y->left = x->right;
if (x->right != NULL) {
x->right->parent = y;
x->parent = y->parent;
if (y->parent == NULL) {
*root = x;
} else if (y == y->parent->left) {
y->parent->left = x;
} else {
76
y->parent->right = x;
x->right = y;
y->parent = x;
if (node->parent == node->parent->parent->left) {
uncle = node->parent->parent->right;
node->parent->color = BLACK;
uncle->color = BLACK;
node->parent->parent->color = RED;
node = node->parent->parent;
} else {
if (node == node->parent->right) {
node = node->parent;
leftRotate(root, node);
node->parent->color = BLACK;
node->parent->parent->color = RED;
rightRotate(root, node->parent->parent);
} else {
uncle = node->parent->parent->left;
77
node->parent->color = BLACK;
uncle->color = BLACK;
node->parent->parent->color = RED;
node = node->parent->parent;
} else {
if (node == node->parent->left) {
node = node->parent;
rightRotate(root, node);
node->parent->color = BLACK;
node->parent->parent->color = RED;
leftRotate(root, node->parent->parent);
(*root)->color = BLACK;
while (x != NULL) {
y = x;
x = x->left;
78
} else {
x = x->right;
newNode->parent = y;
if (y == NULL) {
*root = newNode;
y->left = newNode;
} else {
y->right = newNode;
fixInsert(root, newNode);
// Inorder Traversal
if (root != NULL) {
inorder(root->left);
inorder(root->right);
int main() {
int n, data;
79
scanf("%d", &n);
scanf("%d", &data);
insert(&root, data);
inorder(root);
printf("\n");
return 0;
Output:
Inorder Traversal: 5 10 15 20 25
Results:
• Inorder Traversal: 5 10 15 20 25
80
Aim
The graph will be represented using an adjacency matrix, and the traversal methods will be implemented
using recursive and iterative approaches.
Program Logic
1. BFS (Breadth-First Search): It explores the graph level by level starting from a given vertex. BFS
uses a queue to explore each level in the graph.
2. DFS (Depth-First Search): It explores as deep as possible along each branch before backtracking.
DFS uses recursion or a stack to explore nodes in depth first.
Aim:
To implement Breadth-First Search (BFS) on a graph represented using an adjacency matrix. The BFS will
explore the graph level by level starting from a given vertex.
Program Logic:
3. Use the queue to explore all neighbors of the current vertex, and visit unvisited nodes.
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTICES 10
// Graph structure
struct Graph {
};
// Function declarations
// Main function
int main() {
scanf("%d", &vertices);
initGraph(&graph, vertices);
scanf("%d", &edges);
addEdge(&graph, u, v);
scanf("%d", &startVertex);
82
BFS(&graph, startVertex);
return 0;
graph->numVertices = vertices;
graph->adjMatrix[i][j] = 0;
graph->adjMatrix[u][v] = 1;
// BFS algorithm
visited[startVertex] = 1;
83
queue[rear++] = startVertex;
queue[rear++] = i;
visited[i] = 1;
printf("\n");
01
02
13
14
24
35
45
84
BFS Traversal: 0 1 2 3 4 5
Aim:
To implement Depth-First Search (DFS) on a graph represented using an adjacency matrix. The DFS will
explore the graph by going deep into the graph as far as possible along each branch before backtracking.
Program Logic:
3. Explore the graph by visiting the unvisited adjacent nodes from each vertex.
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTICES 10
// Graph structure
struct Graph {
};
// Function declarations
// Main function
int main() {
scanf("%d", &vertices);
initGraph(&graph, vertices);
scanf("%d", &edges);
addEdge(&graph, u, v);
scanf("%d", &startVertex);
return 0;
}
86
graph->numVertices = vertices;
graph->adjMatrix[i][j] = 0;
graph->adjMatrix[u][v] = 1;
visited[startVertex] = 1;
DFS(graph, i, visited);
}
87
01
02
13
14
24
35
45
DFS Traversal: 0 1 3 5 4 2
Explanation:
• BFS uses a queue to explore nodes level by level starting from a given vertex.
• DFS uses recursion to explore as deeply as possible along each branch before backtracking.
Both BFS and DFS are essential algorithms in graph theory, where BFS is used in problems like finding the
shortest path in an unweighted graph, and DFS is useful for problems like topological sorting and finding
connected components.
Conclusion:
Aim:
To implement the Boyer-Moore algorithm for pattern matching, which efficiently searches for a substring
(pattern) in a given text by scanning from right to left of the pattern.
Program Logic:
o Bad Character Heuristic: If a mismatch occurs, the pattern is shifted so that the
mismatched character in the text aligns with the last occurrence of that character in the
pattern.
o Good Suffix Heuristic: If a mismatch occurs, the pattern is shifted to align the longest suffix
of the matched part with the pattern.
#include <stdio.h>
#include <string.h>
// Function to preprocess the pattern and calculate the bad character heuristic
badChar[i] = -1;
badChar[(int)pattern[i]] = i;
}
89
int m = strlen(pattern);
int n = strlen(text);
int badChar[ALPHABET_SIZE];
badCharacterHeuristic(pattern, m, badChar);
while (s <= n - m) {
int j = m - 1;
// Find the rightmost character in the pattern that matches the text
j--;
// If pattern is found
if (j < 0) {
} else {
}
90
int main() {
text[strcspn(text, "\n")] = 0;
pattern[strcspn(pattern, "\n")] = 0;
boyerMooreSearch(text, pattern);
return 0;
Aim:
To implement the Knuth-Morris-Pratt (KMP) algorithm for pattern matching, which improves the
efficiency of substring search by using a preprocessing phase to build a partial match table (also called
"prefix table").
Program Logic:
1. The KMP algorithm uses a partial match table to avoid unnecessary re-evaluations.
2. This table helps in skipping the comparisons of characters that have already been matched and
reduces the time complexity to O(n + m).
#include <stdio.h>
#include <string.h>
// Function to preprocess the pattern and calculate the longest prefix suffix array
int i = 1;
while (i < m) {
if (pattern[i] == pattern[length]) {
length++;
lps[i] = length;
i++;
} else {
if (length != 0) {
} else {
92
lps[i] = 0;
i++;
int m = strlen(pattern);
int n = strlen(text);
computeLPSArray(pattern, m, lps);
while (i < n) {
if (pattern[j] == text[i]) {
i++;
j++;
if (j == m) {
j = lps[j - 1];
if (j != 0) {
j = lps[j - 1];
} else {
i++;
int main() {
text[strcspn(text, "\n")] = 0;
pattern[strcspn(pattern, "\n")] = 0;
KMPsearch(text, pattern);
return 0;
• Boyer-Moore Algorithm:
o The Boyer-Moore algorithm is faster in practice than other pattern matching algorithms
because it skips over large sections of the text based on mismatches and the bad character
heuristic.
o The KMP algorithm avoids redundant comparisons by using the LPS (Longest Prefix Suffix)
array.
o It efficiently matches patterns in a single pass, with a time complexity of O(n + m), where
n is the length of the text and m is the length of the pattern.
Both algorithms are more efficient than brute force algorithms, especially for larger texts.