DS Record 25 Final
DS Record 25 Final
2024-2025
BONAFIDE CERTIFICATE
Register Number:
Create a C program to
implement a singly linked
list,Doubly, Circular linked list
2) Perform basic operations:
insertion, deletion,
traversal,and search.
Implementation of Stack,
Queue and its
3) Applications.Perform basic
operations: insertion, deletion,
traversal,and search.
Write a C program to
implement the binary search
tree and AVL tree using the
4) following operations- Insertion,
searching, deletion and
traversal.
Create a C program to
implement the DFS and BFS
algorithm and set of
operations.
1. Finding the shortest path in
5) an unweighted graph,
like finding the shortest path
between friends on a
social network.
2. Navigation through maze
Write a C program to
implementation of searching
and
6) sorting algorithms.
1. sorting students grade
2.E-commerce
3.Library systems.
S.NO DATE LIST OF EXPERIMENTS MARKS PAGE SIGNATURE
NO
Write a C program to sort a list of
7) employees by their salary in
ascending order using any sorting
algorithm.
Implementation of Hashing and
Collision Resolution
Techniques.
8) 1. Separate chaining program
using Hash technique
Aim:
To write a c program to read the five values into an array and print them out in reverse
order(Usetwo independent for loops)
Algorithm:
1. Read Five Values:
• Step 1: Use a for loop to read five integer values from the user and store them in
the
array.
2. Insert a New Value:
・Step 1: Read the index where the new value should be inserted.
・Step 2: Shift elements from the end to the specified index to make room for the new
value.
・Step 3: Insert the new value at the specified index.
3. Update a Value:
・Step 1: Read the index of the value to be updated.
・Step 2: Update the value at the specified index.
4. Delete a Value:
・Step 1: Read the index of the value to be deleted.
・Step 2: Shift elements from the index of the deletion to the end to fill the gap.
・Step 3: Optionally, set the last value to zero.
5. Sort the Array:
・Step: Use Bubble Sort to sort the array in ascending order.
6. Traverse in Reverse Order:
・Step 1: Use a for loop to print the array elements in reverse order.
・Step 2: Determine the number of elements in the array.
・Step 3: Use another for loop to print the elements starting from the end.
Program:
#include <stdio.h>
#define SIZE 5
// Function to print an array
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
// Function to sort an array using Bubble Sort
void sortArray(int arr[], int size) {
int temp;
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main() {
int arr[SIZE];
int newValue, index, i;// Step 1: Read five values into the array
printf("Enter 5 values:\n");
for (i = 0; i < SIZE; i++) {
scanf("%d", &arr[i]);
}
printf("Original array:\n");
printArray(arr, SIZE);
// Step 2: Insert a new value
printf("Enter the index (0-4) to insert a new value: ");
scanf("%d", &index);
if (index < 0 || index >= SIZE) {
printf("Invalid index.\n");
}
else {
// Shift elements to the right
for (i = SIZE - 1; i > index; i--) {
arr[i] = arr[i - 1];
}
// Insert new value
printf("Enter the new value: ");
scanf("%d", &newValue);
arr[index] = newValue;
}
printf("Array after insertion:\n");
printArray(arr, SIZE);
// Step 3: Update a value
printf("Enter the index (0-4) to update a value: ");
scanf("%d", &index);
if (index < 0 || index >= SIZE) {
printf("Invalid index.\n");
} else {
printf("Enter the new value: ");
scanf("%d", &newValue);
arr[index] = newValue;
}
printf("Array after update:\n");
printArray(arr, SIZE);
// Step 4: Delete a value
printf("Enter the index (0-4) to delete a value: ");
scanf("%d", &index);
if (index < 0 || index >= SIZE) {
printf("Invalid index.\n");
} else {
// Shift elements to the left
for (i = index; i < SIZE - 1; i++) {
arr[i] = arr[i + 1];
printf("Array after deletion:\n");
printArray(arr, SIZE);
// Step 5: Sort the array
sortArray(arr, SIZE);
}
// Step 5: Sort the array
sortArray(arr, SIZE);printf("Sorted array:\n");
printArray(arr, SIZE);
// Step 6: Traverse the array in reverse order using two
independent for loops
printf("Array in reverse order:\n");
// First for loop to determine the number of elements
int numElements = SIZE;
// Second for loop to print elements in reverse order
for (i = numElements - 1; i >= 0; i--) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Output:
Enter 5 values:
22
33
44
55
66
Original array:
22 33 44 55 66
Enter the index (0-4) to insert a new value: 2
Enter the new value: 70
Array after insertion:
22 33 70 44 55
Enter the index (0-4) to update a value: 1
Enter the new value: 56
Array after update:
22 56 70 44 55
Enter the index (0-4) to delete a value: 5
Invalid index.
Array after deletion:
22 56 70 44 55
Sorted array:
22 44 55 56 70
Array in reverse order:
70 56 55 44 22
Result:
Thus the C program was implemented an array in reverse order and executed
successfully.
EX NO: 2(A) IMPLEMENTATION OF SINGLY LINKED
LIST,DOUBLY AND CIRCULAR LINLED LIST
DATE :
Aim:
To write a c program to implement singly linked list to perform the operations.
Algorithm:
1. Create a Node:
・Define a structure for the node with data and a pointer to the next node.
2. Insert a Node:
・Allocate memory for a new node.
・Set its data and adjust pointers to maintain the linked list.
3. Delete a Node:
・Traverse the list to find the node to delete.
・Adjust pointers to remove the node.
4. Traverse and Display:
・Traverse through the list from the head node and print data.
Program:
#include <stdio.h>
#include <stdlib.h>
// Define a node in the singly linked list
struct Node {
int data;
struct Node* next;
};
// Function to create a new node
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// Function to insert a node at the end
void insertEnd(struct Node** head, int data) {
struct Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
} else {
struct Node* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}
// Function to delete a node by value
void deleteNode(struct Node** head, int data) {
struct Node *temp = *head, *prev = NULL;
if (temp != NULL && temp->data == data) {
*head = temp->next;
free(temp);
return;
}
while (temp != NULL && temp->data != data) {
prev = temp;
temp = temp->next;
}
if (temp == NULL) return;
prev->next = temp->next;
free(temp);
}
// Function to display the list
void displayList(struct Node* head) {
struct Node* temp = head;
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
int main() {
struct Node* head = NULL;
insertEnd(&head, 1);
insertEnd(&head, 2);
insertEnd(&head, 3);
printf("Singly Linked List: ");
displayList(head);
deleteNode(&head, 2);
printf("After deleting 2: ");
displayList(head);
return 0;
}
Output:
Singly Linked List: 1 -> 2 -> 3 -> NULL
After deleting 2: 1 -> 3 -> NULL
Result:
Thus the C program was implemented an array in reverse order and executed
successfully.
EX NO: 2(B)
IMPLEMENTATION OF DOUBLY LINKE LIST
DATE :
Aim:
To write a c program to implement doubly linked list to perform the operations.
Algorithm:
1. Create a Node:
・Define a structure for the node with data, and pointers to the previous and next
nodes.
2. Insert a Node:
・Allocate memory for a new node.
・Adjust pointers to insert the node at the end.
3. Delete a Node:
• Traverse the list to find the node to delete.
・Adjust pointers to remove the node.
4. Traverse and Display:
・Traverse forward and backward to display the list.
Program:
#include <stdio.h>
#include <stdlib.h>
// Define a node in the doubly linked list
struct Node {
int data;
struct Node* prev;
struct Node* next;
};
// Function to create a new node
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->prev = NULL;
newNode->next = NULL;
return newNode;
}
// Function to insert a node at the end
void insertEnd(struct Node** head, int data) {
struct Node* newNode = createNode(data);
struct Node* temp = *head;
if (*head == NULL) {
*head = newNode;
} else {
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
newNode->prev = temp;
}
}
// Function to delete a node by value
void deleteNode(struct Node** head, int data) {
struct Node* temp = *head;
while (temp != NULL && temp->data != data) {
temp = temp->next;
}
if (temp == NULL) return;
if (temp->prev != NULL) {
temp->prev->next = temp->next;
} else {
*head = temp->next;
}
if (temp->next != NULL) {
temp->next->prev = temp->prev;
}
free(temp);
}
// Function to display the list in forward direction
void displayForward(struct Node* head) {
struct Node* temp = head;
while (temp != NULL) {
printf("%d <-> ", temp->data);
temp = temp->next;
}
printf("NULL\n");}
// Function to display the list in backward direction
void displayBackward(struct Node* head) {
struct Node* temp = head;
if (temp == NULL) return;
while (temp->next != NULL) {
temp = temp->next;
}
while (temp != NULL) {
printf("%d <-> ", temp->data);
temp = temp->prev;
}
printf("NULL\n");
}
int main() {
struct Node* head = NULL;
insertEnd(&head, 1);
insertEnd(&head, 2);
insertEnd(&head, 3);
deleteNode(&head, 2);
printf("After deleting 2, Forward: ");
displayForward(head);
printf("After deleting 2, Backward: “);
displayBackward(head);
return 0;
Output:
Doubly Linked List Forward: 1 <-> 2 <-> 3 <-> NULL
After deleting 2, Forward: 1 <-> 3 <-> NULL
After deleting 2, Backward: 3 <-> 1 <-> NULL
Result:
Thus the C program was implemented doubly linked list and executed successfully.
EX NO: 2(c)
IMPLEMENTATION OF CIRCULAR LINKE LIST
DATE :
Aim:
To write a c program to implement circular linked list to perform the operations.
Algorithm:
1. Create a Node:
・Define a structure for the node with data and a pointer to the next node.
2. Insert a Node:
・Allocate memory for a new node.
・Adjust pointers to maintain circularity.
3. Delete a Node:
・Traverse the list to find the node to delete.
・Adjust pointers to remove the node and maintain circularity.
4. Traverse and Display:
・Traverse the list starting from the head node until you return to the head.
Program:
#include <stdio.h>
#include <stdlib.h>
// Define a node in the circular linked list
struct Node {
int data;
struct Node* next;
};
// Function to create a new node
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// Function to insert a node at the end
void insertEnd(struct Node** head, int data) {
struct Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
newNode->next = *head;
} else {
struct Node* temp = *head;
while (temp->next != *head) {
temp = temp->next;
}
temp->next = newNode;
newNode->next = *head;
}
// Function to delete a node by value
void deleteNode(struct Node** head, int data) {
struct Node *temp = *head, *prev = NULL;
if (temp != NULL && temp->data == data) {
prev = *head;
while (prev->next != *head) {
prev = prev->next;
}
if (*head == (*head)->next) {
free(*head);
*head = NULL;
} else {
prev->next = temp->next;
free(temp);
*head = prev->next;
}
return;
}
while (temp->next != *head && temp->next->data != data) {
temp = temp->next;
}
if (temp->next == *head) return;
struct Node* toDelete = temp->next;
temp->next = toDelete->next;
free(toDelete);
}
// Function to display the list
void displayList(struct Node* head) {
if (head == NULL) return;
struct Node* temp = head;
do {
printf("%d -> ", temp->data);
temp = temp->next;
} while (temp != head);
printf("(head)\n");
}
int main() {
struct Node* head = NULL;
insertEnd(&head, 1);
insertEnd(&head, 2);
insertEnd(&head, 3);
printf("Circular Linked List: ");
displayList(head);
deleteNode(&head, 2);
printf("After deleting 2: ");
displayList(head);
return 0; }
Output:
Circular Linked List: 1 -> 2 -> 3 -> (head)
After deleting 2: 1 -> 3 -> (head)
Result:
Thus the c program was implemented circular linked list and output is verified.
EX NO: 3(A)
IMPLEMENTATION OF STACK
DATE :
Aim:
To write a c program to implement circular linked list to perform the operations.
Algorithm:
1. Create a Stack:
・Define a stack structure with an array and an integer to keep track of the top index.
2. Push Operation:
・Check if the stack is full.
・Increment the top index and add the new element.
3. Pop Operation:
・Check if the stack is empty.
・Return the element at the top index and decrement the top index.
4. Peek Operation:
・Return the element at the top index without modifying the stack.
5. Traversal:
・Print elements from the bottom to the top of the stack.
6. Search Operation:
・Search for an element in the stack.
Program:
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
// Define a stack structure
typedef struct {
int arr[MAX];
int top;
} Stack;
// Initialize the stack
void initStack(Stack* stack) {
stack->top = -1;
}
// Check if the stack is full
int isFull(Stack* stack) {
return stack->top == MAX - 1;
}
// Check if the stack is empty
int isEmpty(Stack* stack) {
return stack->top == -1;
}
// Push operation
void push(Stack* stack, int value) {
if (isFull(stack)) {
printf("Stack is full.\n");return;
}
stack->arr[++stack->top] = value;
}
// Pop operation
int pop(Stack* stack) {
if (isEmpty(stack)) {
printf("Stack is empty.\n");
return -1;
}
return stack->arr[stack->top--];
}
// Peek operation
int peek(Stack* stack) {
if (isEmpty(stack)) {
printf("Stack is empty.\n");
return -1;
}
return stack->arr[stack->top];
}
// Traverse the stack
void traverseStack(Stack* stack) {
if (isEmpty(stack)) {
printf("Stack is empty.\n");
return;
}
for (int i = 0; i <= stack->top; i++) {
printf("%d ", stack->arr[i]);
}
printf("\n");
}
// Search operation
int searchStack(Stack* stack, int value) {
for (int i = 0; i <= stack->top; i++) {
if (stack->arr[i] == value) {
return i;
}}
return -1;
}
int main() {
Stack stack;
initStack(&stack);
push(&stack, 10);
push(&stack, 20);
push(&stack, 30);
printf("Stack elements: ");
traverseStack(&stack);
printf("Popped element: %d\n", pop(&stack));
printf("Stack elements after pop: ");
traverseStack(&stack);
int valueToSearch = 20;
int index = searchStack(&stack,
valueToSearch);
if (index != -1) {
printf("Element %d found at index %d.\n",
valueToSearch, index);
} else {
printf("Element %d not found.\n",
valueToSearch);
}
return 0;
Output:
Stack elements: 10 20 30
Popped element: 30
Stack elements after pop: 10 20
Element 20 found at index 1.
Result:
Thus the C program was implemented stack and executed successfully.
EX NO: 3(B)
IMPLEMENTATION OF QUEUE
DATE :
Aim:
To write a c program to implement the queue to perform the operations.
Algorithm:
1. Create a Queue:
・Define a queue structure with an array, front and rear indices, and the size of the
queue.
2. Enqueue Operation:
・Check if the queue is full.
・Add the new element at the rear index and adjust the rear index.
3. Dequeue Operation:
・Check if the queue is empty.
・Remove the element from the front index and adjust the front index.
4. Peek Operation:
・Return the element at the front index without modifying the queue.
5. Traversal:
・Print elements from the front to the rear of the queue.
6. Search Operation:
・Search for an element in the queue.
Program:
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
// Define a queue structure
typedef struct {
int arr[MAX];
int front, rear, size;
} Queue;
// Initialize the queue
void initQueue(Queue* queue) {
queue->front = 0;
queue->rear = -1;
queue->size = 0;}
// Check if the queue is full
int isFull(Queue* queue) {
return queue->size == MAX;}
// Check if the queue is empty
int isEmpty(Queue* queue) {
return queue->size == 0;
}
// Enqueue operation
void enqueue(Queue* queue, int value) {if (isFull(queue)) {
printf("Queue is full.\n");
return;
}
queue->rear = (queue->rear + 1) % MAX;
queue->arr[queue->rear] = value;
queue->size++;
}
// Dequeue operation
int dequeue(Queue* queue) {
if (isEmpty(queue)) {
printf("Queue is empty.\n");
return -1;
}
int value = queue->arr[queue->front];
queue->front = (queue->front + 1) % MAX;
queue->size--;
return value;
}
// Peek operation
int peekQueue(Queue* queue) {
if (isEmpty(queue)) {
printf("Queue is empty.\n");
return -1;
}
return queue->arr[queue->front];
}
// Traverse the queue
void traverseQueue(Queue* queue) {
if (isEmpty(queue)) {
printf("Queue is empty.\n");
return;
}
int i = queue->front;
int count = queue->size;
while (count--) {
printf("%d ", queue->arr[i]);
i = (i + 1) % MAX;
}
printf("\n");
}
// Search operation
int searchQueue(Queue* queue, int value) {
int i = queue->front;
int count = queue->size;
while (count--) {
if (queue->arr[i] == value) {
return i;
}
i = (i + 1) % MAX;
}
return -1;
}
int main() {
Queue queue;
initQueue(&queue);enqueue(&queue, 10);
enqueue(&queue, 20);
enqueue(&queue, 30);
printf("Queue elements: ");
traverseQueue(&queue);
printf("Dequeued element: %d\n", dequeue(&queue));
printf("Queue elements after dequeue: ");
traverseQueue(&queue);
int valueToSearch = 20;
int index = searchQueue(&queue, valueToSearch);
if (index != -1) {
printf("Element %d found at index %d.\n", valueToSearch, index);
} else {
printf("Element %d not found.\n", valueToSearch);
}
return 0;
}
Output:
Queue elements: 10 20 30
Dequeued element: 10
Queue elements after dequeue: 20 30
Element 20 found at index 1.
Result:
Thus the C program was implemented queue operations and executed successfully.
EX NO: 4(A) IMPLEMENTATION OF BINARY SEARCH TREE
DATE :
Aim:
Write a C program to implement the binary search tree and AVL tree using the
following operations- Insertion, searching, deletion and traversal.
Algorithm:
1. Step 1: Define Node Structure
◦ Create a struct Node with an integer data and two pointers left and right to represent child
nodes.
2. Step 2: Create a New Node
◦ Implement a function createNode(int data) that allocates memory, initializes the node with
data, and sets its child pointers to NULL.
3. Step 3: Insert a Node
◦ Implement findMin(struct Node* root) to return the leftmost node of the tree, which holds
the minimum value.
6. Step 6: Delete a Node
◦ Implement inOrder(struct Node* root) to recursively visit the left subtree, print the current
node, and then visit the right subtree.
8. Step 8: Perform Operations
◦ In the main function, insert nodes, display the tree using in-order traversal, delete a node, and
search for a specific value.
Program:
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* left;
struct Node* right;
};
// Create a new node
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
// Insertion in BST
struct Node* insert(struct Node* root, int data) {
if (root == NULL) {
return createNode(data);
}
if (data < root->data) {
root->left = insert(root->left, data);
} else if (data > root->data) {
root->right = insert(root->right, data);
}
return root;
}
// Searching in BST
struct Node* search(struct Node* root, int data) {
if (root == NULL || root->data == data) {
return root;
}
if (data < root->data) {
return search(root->left, data);
}
return search(root->right, data);
}
// Find the minimum node
struct Node* findMin(struct Node* root) {
while (root->left != NULL) {
root = root->left;
}
return root;
}
// Deletion in BST
struct Node* deleteNode(struct Node* root, int data) {
if (root == NULL) return root;
if (data < root->data) {
root->left = deleteNode(root->left, data);
} else if (data > root->data) {
root->right = deleteNode(root->right, data);
} else {
// Node with one child or no child
if (root->left == NULL) {
struct Node* temp = root->right;
free(root);
return temp;
} else if (root->right == NULL) {
struct Node* temp = root->left;
free(root);
return temp;
}
// Node with two children
struct Node* temp = findMin(root->right);
root->data = temp->data;
root->right = deleteNode(root->right, temp->data);
}
return root;
}
// In-order traversal of BST
void inOrder(struct Node* root) {
if (root != NULL) {
inOrder(root->left);
printf("%d ", root->data);
inOrder(root->right);
}
}
int main() {
struct Node* root = NULL;
root = insert(root, 50);
root = insert(root, 30);
root = insert(root, 20);
root = insert(root, 40);
root = insert(root, 70);
root = insert(root, 60);
root = insert(root, 80);
printf("Inorder traversal of the BST: ");
inOrder(root);
printf("\n");
root = deleteNode(root, 20);
printf("Inorder traversal after deletion of 20: ");
inOrder(root);
printf("\n");
struct Node* found = search(root, 70);
if (found) {
printf("Node 70 found in the BST.\n");
} else {
printf("Node 70 not found in the BST.\n");
}
return 0;
}
Output:
Inorder traversal of the BST: 20 30 40 50 60 70 80
Inorder traversal after deletion of 20: 30 40 50 60 70 80
Node 70 found in the BST.
Result:
The above program has been executed successfully and the output is verified.
EX NO: 4(B) IMPLEMENTATION OF AVL TREE
DATE :
Aim:
To write a C program to implement the binary search tree and AVL tree using the following
operations- Insertion, searching, deletion and traversal.
Algorithm:
1. Step 1: Define AVL Node Structure
◦ Create a struct AVLNode with an integer data, two pointers left and right, and an integer
height to store the height of the node.
2. Step 2: Create a New AVL Node
◦ Implement a function createAVLNode(int data) that initializes a new node with data, sets
its left and right pointers to NULL, and assigns the height as 1 (leaf node).
3. Step 3: Insert a Node
◦ Define getBalance(struct AVLNode* node) to return the difference in height between the
left and right subtrees.
6. Step 6: Delete a Node
◦ Implement inOrderAVL(struct AVLNode* root) to recursively traverse and print the tree
in sorted order by visiting the left subtree, current node, and then the right subtree.
8. Step 8: Perform Operations
◦ In the main function, insert nodes, display the tree using in-order traversal, delete a node, and
optionally search for a specific value (e.g., node 70).
Program:
#include <stdio.h>
#include <stdlib.h>
struct AVLNode {
int data;
struct AVLNode* left;
struct AVLNode* right;
int height;
};
int height(struct AVLNode* node) {
if (node == NULL)
return 0;
return node->height;
}
struct AVLNode* createAVLNode(int data) {
struct AVLNode* node = (struct AVLNode*)malloc(sizeof(struct AVLNode));
node->data = data;
node->left = NULL;
node->right = NULL;
node->height = 1; // New node is added at leaf
return node;
}
int max(int a, int b) {
return (a > b) ? a : b;
}
struct AVLNode* rightRotate(struct AVLNode* y) {
struct AVLNode* x = y->left;
struct AVLNode* T2 = x->right;
x->right = y;
y->left = T2;
y->height = max(height(y->left), height(y->right)) + 1;
x->height = max(height(x->left), height(x->right)) + 1;
return x;
}
// Left rotate
struct AVLNode* leftRotate(struct AVLNode* x) {
struct AVLNode* y = x->right;
struct AVLNode* T2 = y->left;
y->left = x;
x->right = T2;
x->height = max(height(x->left), height(x->right)) + 1;
y->height = max(height(y->left), height(y->right)) + 1;
return y;
}
// Get balance factor of node
int getBalance(struct AVLNode* node) {
if (node == NULL)
return 0;
return height(node->left) - height(node->right);
}
// Insert node in AVL tree
struct AVLNode* insertAVL(struct AVLNode* node, int data) {
if (node == NULL)
return createAVLNode(data);
if (data < node->data)
node->left = insertAVL(node->left, data);
else if (data > node->data)
node->right = insertAVL(node->right, data);
else
return node;
node->height = 1 + max(height(node->left), height(node->right));
int balance = getBalance(node);
// Left Left Case
if (balance > 1 && data < node->left->data)
return rightRotate(node);
// Right Right Case
if (balance < -1 && data > node->right->data)
return leftRotate(node);
// Left Right Case
if (balance > 1 && data > node->left->data) {
node->left = leftRotate(node->left);
return rightRotate(node);
}
// Right Left Case
if (balance < -1 && data < node->right->data) {
node->right = rightRotate(node->right);
return leftRotate(node);
}
return node;
}
// Find the node with the minimum value
struct AVLNode* findMinAVL(struct AVLNode* node) {
while (node->left != NULL)
node = node->left;
return node;
}
// Delete node in AVL tree
struct AVLNode* deleteAVL(struct AVLNode* root, int data) {
if (root == NULL)
return root;
if (data < root->data)
root->left = deleteAVL(root->left, data);
else if (data > root->data)
root->right = deleteAVL(root->right, data);
else {
if ((root->left == NULL) || (root->right == NULL)) {
struct AVLNode* temp = root->left ? root->left : root->right;
if (temp == NULL) {
temp = root;
root = NULL;
} else {
*root = *temp;
}
free(temp);
} else {
struct AVLNode* temp = findMinAVL(root->right);
root->data = temp->data;
root->right = deleteAVL(root->right, temp->data);
}
}
if (root == NULL)
return root;
root->height = max(height(root->left), height(root->right)) + 1;
int balance = getBalance(root);
if (balance > 1 && getBalance(root->left) >= 0)
return rightRotate(root);
if (balance > 1 && getBalance(root->left) < 0) {
root->left = leftRotate(root->left);
return rightRotate(root);
}
if (balance < -1 && getBalance(root->right) <= 0)
return leftRotate(root);
if (balance < -1 && getBalance(root->right) > 0) {
root->right = rightRotate(root->right);
return leftRotate(root);
}
return root;
}
// In-order traversal of AVL tree
void inOrderAVL(struct AVLNode* root) {
if (root != NULL) {
inOrderAVL(root->left);
printf("%d ", root->data);
inOrderAVL(root->right);
}
}
int main() {
struct AVLNode* root = NULL;
root = insertAVL(root, 50);
root = insertAVL(root, 30);
root = insertAVL(root, 20);
root = insertAVL(root, 40);
root = insertAVL(root, 70);
root = insertAVL(root, 60);
root = insertAVL(root, 80);
printf("Inorder traversal of the AVL Tree: ");
inOrderAVL(root);
printf("\n");
root = deleteAVL(root, 20);
printf("Inorder traversal after deletion of 20: ");
inOrderAVL(root);
printf("\n");
struct AVLNode* found = search(root, 70);
if (found) {
printf("Node 70 found in the AVL Tree.\n");
} else {
printf("Node 70 not found in the AVL Tree.\n");
}
return 0;
}
Output:
Inorder traversal of the AVL Tree: 20 30 40 50 60 70 80
Inorder traversal after deletion of 20: 30 40 50 60 70 80
Node 70 found in the AVL Tree.
Result:
The above program has been executed successfully and the output is verified.
EX NO: 5
IMPLEMENTATION OF DFS & BFS ALGORITHM
DATE :
Aim:
To create a C program to implement the DFS and BFS algorithm and set of operations.
1. Finding the shortest path in an unweighted graph, like finding the shortest path
between friends on a social network.2. Navigation through maze.
Algorithm:
1. Step 1: Define AVL Node Structure
◦ Create a struct AVLNode with an integer data, two pointers left and right, and an integer
height to store the height of the node.
2. Step 2: Create a New AVL Node
◦ Implement a function createAVLNode(int data) that initializes a new node with data, sets
its left and right pointers to NULL, and assigns the height as 1 (leaf node).
3. Step 3: Insert a Node
◦ Define getBalance(struct AVLNode* node) to return the difference in height between the
left and right subtrees.
6. Step 6: Delete a Node
◦ Implement inOrderAVL(struct AVLNode* root) to recursively traverse and print the tree
in sorted order by visiting the left subtree, current node, and then the right subtree.
8. Step 8: Perform Operations
◦ In the main function, insert nodes, display the tree using in-order traversal, delete a node, and
optionally search for a specific value (e.g., node 70).
Program:
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
#define INF 9999999
// Structure for graph
struct Graph {
int vertices;
int adj[MAX][MAX]; // Adjacency matrix
};
// Queue structure for BFS
struct Queue {
int items[MAX];
int front, rear;
};
// Stack structure for DFS
struct Stack {
int items[MAX];
int top;
};
// Initialize a graph
struct Graph* createGraph(int vertices) {
struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));
graph->vertices = vertices;
for (int i = 0; i < vertices; i++) {
for (int j = 0; j < vertices; j++) {
graph->adj[i][j] = 0;
}
}
return graph;
// Add edge to the graph
void addEdge(struct Graph* graph, int src, int dest) {
graph->adj[src][dest] = 1;
graph->adj[dest][src] = 1; // Since the graph is undirected
}
// Initialize the queue for BFS
struct Queue* createQueue() {
struct Queue* queue = (struct Queue*)malloc(sizeof(struct Queue));
queue->front = -1;
queue->rear = -1;
return queue;
}
// Check if the queue is empty
int isEmptyQueue(struct Queue* queue) {
return queue->rear == -1;
}
// Enqueue for BFS
void enqueue(struct Queue* queue, int value) {
if (queue->rear == MAX - 1)
return;
else {
if (queue->front == -1)
queue->front = 0;
queue->rear++;
queue->items[queue->rear] = value;
}
}
// Dequeue for BFS
int dequeue(struct Queue* queue) {
int item;
if (isEmptyQueue(queue)) {
return -1;
} else {
item = queue->items[queue->front];
queue->front++;
if (queue->front > queue->rear) {
queue->front = queue->rear = -1;
}
return item;
}
}
// Initialize stack for DFS
struct Stack* createStack() {
struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack));
stack->top = -1;
return stack;
}
// Check if the stack is empty
int isEmptyStack(struct Stack* stack) {
return stack->top == -1;
}
// Push to stack for DFS
void push(struct Stack* stack, int value) {
if (stack->top == MAX - 1)
return;
else {
stack->top++;
stack->items[stack->top] = value;
}
}
// Pop from stack for DFS
int pop(struct Stack* stack) {
if (isEmptyStack(stack))
return -1;
else {
int item = stack->items[stack->top];
stack->top--;
return item;
}
}
// Breadth-First Search (BFS)
void BFS(struct Graph* graph, int startVertex) {
struct Queue* queue = createQueue();
int visited[MAX] = {0}; // Track visited vertices
enqueue(queue, startVertex);
visited[startVertex] = 1;
printf("BFS Traversal: ");
while (!isEmptyQueue(queue)) {
int currentVertex = dequeue(queue);
printf("%d ", currentVertex);
for (int i = 0; i < graph->vertices; i++) {
if (graph->adj[currentVertex][i] == 1 && !visited[i]) {
enqueue(queue, i);
visited[i] = 1;
}
}
}
printf("\n");
}
// Depth-First Search (DFS)
void DFS(struct Graph* graph, int startVertex) {
struct Stack* stack = createStack();
int visited[MAX] = {0}; // Track visited vertices
push(stack, startVertex);
visited[startVertex] = 1;
printf("DFS Traversal: ");
while (!isEmptyStack(stack)) {
int currentVertex = pop(stack);
printf("%d ", currentVertex);
for (int i = 0; i < graph->vertices; i++) {
if (graph->adj[currentVertex][i] == 1 && !visited[i]) {
push(stack, i);
visited[i] = 1;
}
}
}
printf("\n");
}
// Find the shortest path in an unweighted graph (using BFS)
void findShortestPath(struct Graph* graph, int startVertex, int targetVertex) {
struct Queue* queue = createQueue();
int visited[MAX] = {0};
int distance[MAX];
int predecessor[MAX];
// Initialize distances and predecessors
for (int i = 0; i < graph->vertices; i++) {
distance[i] = INF;
predecessor[i] = -1;
}
enqueue(queue, startVertex);
visited[startVertex] = 1;
distance[startVertex] = 0;
while (!isEmptyQueue(queue)) {
int currentVertex = dequeue(queue);
for (int i = 0; i < graph->vertices; i++) {
if (graph->adj[currentVertex][i] == 1 && !visited[i]) {
enqueue(queue, i);
visited[i] = 1;
distance[i] = distance[currentVertex] + 1;
predecessor[i] = currentVertex;
// Stop if we found the target
if (i == targetVertex)
break;
}
}
}
// Print the shortest path
printf("Shortest path from %d to %d is: ", startVertex, targetVertex);
int crawl = targetVertex;
if (predecessor[targetVertex] == -1) {
printf("No path found.\n");
return;
}
printf("%d ", targetVertex);
while (predecessor[crawl] != -1) {
printf("<- %d ", predecessor[crawl]);
crawl = predecessor[crawl];
}
printf("\nPath length: %d\n", distance[targetVertex]); }
// Maze navigation using DFS
void navigateMaze(int maze[MAX][MAX], int size, int startX, int startY, int
endX, int endY) {
struct Stack* stack = createStack();
int visited[MAX][MAX] = {0}; // Track visited cells
int directions[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; // Up, Down, Left,
Right
push(stack, startX * size + startY); // Push starting point
visited[startX][startY] = 1;
printf("Navigating the maze using DFS:\n");
while (!isEmptyStack(stack)) {
int pos = pop(stack);
int x = pos / size;
int y = pos % size;
printf("At position (%d, %d)\n", x, y);
if (x == endX && y == endY) {
printf("Reached the goal (%d, %d)\n", endX, endY);
return;
}
Result:
The above program has been executed successfully and the output is verified.
EX NO: 6(A)
IMPLEMENTATION OF SORTING STUDENTS GRADE
DATE :
Aim:
To write a C program to implementation of searching and sorting algorithms- sorting
students grade.
Algorithm:
1. Step 1: Define Student Structure
◦ Create a struct Student to store student information, which includes a name and
an int for grade.
2. Step 2: Input Student Data
◦ Prompt the user to enter the number of students and their respective names and
grades, storing the information in an array of struct Student.
3. Step 3: Implement Bubble Sort
◦ Define the function bubbleSort(struct Student students[], int n):
▪ Compare adjacent students' grades and swap them if they are out of
order.
▪ Repeat this process to sort the students in ascending order of their grades.
4. Step 4: Display Sorted Students
◦ Implement the function displayStudents(struct Student students[], int n) to print
the sorted list of students along with their grades.
5. Step 5: Implement Binary Search
◦ Define the function binarySearch(struct Student students[], int n, int
targetGrade):
▪ Perform a binary search on the sorted array to find the student with the
target grade.
▪ Return the index of the student if the grade is found, or -1 if not found.
6. Step 6: Search for a Grade
◦ Prompt the user to enter the grade they want to search for and use the
binarySearch function to find the student with that grade.
7. Step 7: Display Search Result
◦ If the grade is found, print the student's name and grade; otherwise, display a
message indicating that the grade was not found.
8. Step 8: Main Function Execution
◦ In the main function, take input for students, sort their grades using bubbleSort,
display the sorted list, and allow the user to search for a specific grade using
Program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 100
struct Student {
char name[50];
int grade;
};
void bubbleSort(struct Student students[], int n) {
int i, j;
struct Student temp;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (students[j].grade > students[j + 1].grade) {
// Swap the students
temp = students[j];
students[j] = students[j + 1];
students[j + 1] = temp;
}
}
}
}
void displayStudents(struct Student students[], int n) {
printf("\nSorted Students' Grades:\n");
printf("Name\t\tGrade\n");
printf(" --------------------- \n");
for (int i = 0; i < n; i++) {
printf("%-15s %d\n", students[i].name, students[i].grade);
}}
// Binary Search to search for a student's grade
int binarySearch(struct Student students[], int n, int targetGrade) {
int low = 0, high = n - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (students[mid].grade == targetGrade) {
return mid;
} else if (students[mid].grade < targetGrade) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1; // Grade not found
}
int main() {
int n, i, targetGrade, foundIndex;
// Input number of students
printf("Enter the number of students: ");
scanf("%d", &n);
struct Student students[MAX];
// Input student names and grades
for (i = 0; i < n; i++) {
printf("Enter the name of student %d: ", i + 1);
scanf("%s", students[i].name);
printf("Enter the grade of student %d: ", i + 1);
scanf("%d", &students[i].grade);
}
// Sort the students' grades using Bubble Sort
bubbleSort(students, n);
// Display the sorted list of students
displayStudents(students, n);
// Searching for a student's grade using Binary Search
printf("\nEnter the grade to search for: ");
scanf("%d", &targetGrade);
foundIndex = binarySearch(students, n, targetGrade);
if (foundIndex != -1) {
printf("\nGrade %d found for student: %s\n",
students[foundIndex].grade, students[foundIndex].name);
} else {
printf("\nGrade %d not found.\n", targetGrade);
}
return 0;
}
Output:
Input :
Enter the number of students: 5
Enter the name of student 1: Alice
Enter the grade of student 1: 85
Enter the name of student 2: Bob
Enter the grade of student 2: 92
Enter the name of student 3: Charlie
Enter the grade of student 3: 78
Enter the name of student 4: David
Enter the grade of student 4: 95
Enter the name of student 5: Eve
Enter the grade of student 5: 88
Output:
Sorted Students' Grades:
Name Grade
Charlie 78
Alice 85
Eve 88
Bob 92
David 95
Result:
The above program has been executed successfully and the output is verified.
EX NO: 6(B)
IMPLEMENTATION OF E-COMMERCE
DATE :
Aim:
To write a C program to implementation of searching and sorting algorithms- sorting
students grade.
Algorithm:
1. Step 1: Define Product Structure
◦ Create a struct Product to store product information, which includes a name (string) and
price (float).
2. Step 2: Input Product Data
◦ Prompt the user to enter the number of products and their respective names and prices.
Store this information in an array of struct Product.
3. Step 3: Implement Bubble Sort
◦ Prompt the user to enter the name of the product they want to search for, and use the
linearSearch function to find the product.
7. Step 7: Display Search Result
◦ If the product is found, print its name and price; otherwise, display a message indicating
that the product was not found.
8. Step 8: Main Function Execution
◦ In the main function, take input for the products, sort their prices using bubbleSort,
display the sorted list, and allow the user to search for a specific product by name using
linear search.
◦ binary search.
Program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_PRODUCTS 100
// Structure to represent a product
struct Product {
char name[50];
float price;
};
// Function to perform Bubble Sort on products by price
void bubbleSort(struct Product products[], int n) {
int i, j;
struct Product temp;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (products[j].price > products[j + 1].price) {
// Swap products
temp = products[j];
products[j] = products[j + 1];
products[j + 1] = temp;
}
}
}
}
// Function to display all products
void displayProducts(struct Product products[], int n) {
printf("\nProducts List:\n");
printf("Name\t\tPrice\n");
printf(" --------------------- \n");
for (int i = 0; i < n; i++) {
printf("%-15s %.2f\n", products[i].name, products[i].price);
}
}
// Function to search for a product by name using Linear Search
int linearSearch(struct Product products[], int n, char* targetName) {
for (int i = 0; i < n; i++) {
if (strcmp(products[i].name, targetName) == 0) {
return i; // Return index if found
}
}
return -1; // Return -1 if not found
}
int main() {
int n, foundIndex;
char targetName[50];
Output:
Products List:
Name Price
Mouse 25.50
Keyboard 45.99
Headphones 79.99
Monitor 199.99
Laptop 999.99
Result:
The above program has been executed successfully and the output is verified.
EX NO: 6(C) IMPLEMENTATION OF LIBRARY SYSTEMS
DATE :
Aim:
To write a C program to implementation of searching and sorting algorithms- sorting
students grade.
Algorithm:
1. Step 1: Define Book Structure
◦ Create a struct Book to store book information, including title, author, and year.
2. Step 2: Input Book Details
◦ Prompt the user to enter the number of books and their respective titles, authors, and
publication years. Store this data in an array of struct Book.
3. Step 3: Implement Bubble Sort
◦ Implement the function displayBooks(struct Book books[], int n) to print the sorted list
of books, including their titles, authors, and publication years.
5. Step 5: Implement Linear Search
◦ Prompt the user to enter the title of the book they want to search for, and use the
linearSearch function to find the book.
7. Step 7: Display Search Result
◦ If the book is found, print its title, author, and publication year; otherwise, display a
message indicating that the book was not found.
8. Step 8: Main Function Execution
◦ In the main function, take input for the books, sort their titles using bubbleSort, display
the sorted list, and allow the user to search for a specific book by title using linear
search.
Program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_BOOKS 100
// Structure to represent a book
struct Book {
char title[100];
char author[100];
int year;
};
// Function to perform Bubble Sort on books by title
void bubbleSort(struct Book books[], int n) {
int i, j;
struct Book temp;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (strcmp(books[j].title, books[j + 1].title) > 0) {
// Swap books
temp = books[j];
books[j] = books[j + 1];
books[j + 1] = temp;
}
}
}
}
// Function to display all books
void displayBooks(struct Book books[], int n) {
printf("\nLibrary Books:\n");
printf("Title\t\t\tAuthor\t\tYear\n");
printf(" ------------------------------------------ \n");
for (int i = 0; i < n; i++) {
printf("%-20s %-20s %d\n", books[i].title, books[i].author,
books[i].year);
}
}
// Function to search for a book by title using Linear Search
int linearSearch(struct Book books[], int n, char* targetTitle) {
for (int i = 0; i < n; i++) {
if (strcmp(books[i].title, targetTitle) == 0) {
return i; // Return index if found
}
}
return -1; // Return -1 if not found
}
int main() {
int n, foundIndex;
char targetTitle[100];
// Input the number of books
printf("Enter the number of books: ");
scanf("%d", &n);
getchar(); // To consume the newline character after the number input
struct Book books[MAX_BOOKS];
// Input book details
for (int i = 0; i < n; i++) {
printf("Enter the title of book %d: ", i + 1);
fgets(books[i].title, sizeof(books[i].title), stdin);
books[i].title[strcspn(books[i].title, "\n")] = 0; // Remove newline
character
printf("Enter the author of book %d: ", i + 1);
fgets(books[i].author, sizeof(books[i].author), stdin);
books[i].author[strcspn(books[i].author, "\n")] = 0; // Remove newline
character
printf("Enter the year of publication of book %d: ", i + 1);
scanf("%d", &books[i].year);
getchar(); // To consume the newline character after the year input
}
// Sort the books by title
bubbleSort(books, n);
// Display the sorted list of books
displayBooks(books, n);
// Searching for a book by title
printf("\nEnter the title of the book to search for: ");
fgets(targetTitle, sizeof(targetTitle), stdin);
targetTitle[strcspn(targetTitle, "\n")] = 0; // Remove newline character
foundIndex = linearSearch(books, n, targetTitle);
if (foundIndex != -1) {
printf("\nBook found: %s by %s (%d)\n", books[foundIndex].title,
books[foundIndex].author, books[foundIndex].year);
} else {
printf("\nBook '%s' not found in the library.\n", targetTitle);
}
return 0;
}
Output:
Input:
Enter the number of books: 3
Enter the title of book 1: The Great Gatsby
Enter the author of book 1: F. Scott Fitzgerald
Enter the year of publication of book 1: 1925
Enter the title of book 2: To Kill a Mockingbird
Enter the author of book 2: Harper Lee
Enter the year of publication of book 2: 1960
Enter the title of book 3: 1984
Enter the author of book 3: George Orwell
Enter the year of publication of book 3: 1949
Output:
Library Books:
Title Author Year
Result:
The above program has been executed successfully and the output is verified.
EX NO: 7
IMPLEMENTATION OF EMPLOYEE SALARY
DATE :
Aim:
Algorithm:
1. Step 1 : Define Employee Structure
o Create a struct Employee with fields: name, id, and salary.
2. Step 2 : Input Employee Data
o Prompt the user to enter the number of employees, and accept each employee's ID,
name, and salary.
3. Step 3 : Implement Bubble Sort
o Define the function bubbleSort(struct Employee emp[], int n) that:
Compares adjacent employees' salaries.
Swaps them if they are out of order.
Repeats the process to sort in ascending order.
4. Step 4 : Display Sorted Employee List
o Define the function displayEmployees(struct Employee emp[], int n) to print the
sorted employee records.
5. Step 5 : Main Function Execution
o In main(), call input, sorting, and display functions in sequence.
Program :
#include <stdio.h>
#include <string.h>
// Employee structure
struct Employee {
char name[50];
int id;
float salary;
};
// Display function
void displayEmployees(struct Employee emp[], int n) {
printf("\nSorted Employee List by Salary (Ascending):\n");
printf("ID\tName\t\tSalary\n");
printf("--------------------------------------\n");
for (int i = 0; i < n; i++) {
printf("%d\t%-15s %.2f\n", emp[i].id, emp[i].name, emp[i].salary);
}
}
// Main function
int main() {
int n;
struct Employee emp[MAX];
return 0;
}
Output :
Input :
Enter the number of employees: 3
Enter details of employee 1:
ID: 101
Name: Alice
Salary: 50000
Enter details of employee 2:
ID: 102
Name: Bob
Salary: 45000
Enter details of employee 3:
ID: 103
Name: Charlie
Salary: 60000
Output :
Sorted Employee List by Salary (Ascending):
ID Name Salary
--------------------------------------
102 Bob 45000.00
101 Alice 50000.00
103 Charlie 60000.00
Result:
The above C program for sorting employee records based on salary using
Bubble Sort has been successfully executed and verified with correct output.
EX NO: 8
Implementation of Hashing and Collision Resolution
DATE :
Aim:
To implementation of Hashing and Collision Resolution Techniques.Separate chaining
program using Hash technique .
Algorithm:
1. Step 1: Define Node Structure
◦ Create a struct HashTable that contains an array of linked lists (struct Node** table),
which will hold keys based on the hash index.
3. Step 3: Create Hash Table
◦ Create a simple hash function hash(int key) that returns the modulus of the key by the table
size. This will determine the index where the key is placed.
5. Step 5: Insert Keys into the Hash Table
◦ Implement the display(struct HashTable* ht) function to show all buckets of the hash
table.
◦ For each bucket, display the keys and their connections (using -> to indicate the linked list
structure).
Program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TABLE_SIZE 10
// Structure to represent a node in the linked list
struct Node {
int key;
struct Node* next;
};
Result:
The above program has been executed successfully and the output is verified.
EX NO : 9
Display the Length of the Longest and Shortest
DATE : Chains in a Hash Table
Aim:
To write a C program that implements a hash table using separate chaining, and
displays the lengths of the longest and shortest chains after multiple insertions.
Algorithm:
#include <stdio.h>
#include <stdlib.h>
#define TABLE_SIZE 10
// Node structure
struct Node {
int key;
struct Node* next;
};
// HashTable structure
struct HashTable {
struct Node** table;
};
// Hash function
int hash(int key) {
return key % TABLE_SIZE;
}
// Main function
int main() {
struct HashTable* ht = createHashTable();
// Clean up
freeHashTable(ht);
return 0;
}
Output :
Hash Table:
Bucket 0: NULL
Bucket 1: NULL
Bucket 2: NULL
Bucket 3: 3 -> 13 -> 23 -> NULL
Bucket 4: NULL
Bucket 5: 5 -> 15 -> 25 -> 35 -> 45 -> NULL
Bucket 6: NULL
Bucket 7: NULL
Bucket 8: 8 -> 18 -> 28 -> 38 -> 48 -> NULL
Bucket 9: NULL
Result :
The above C program was successfully executed. It correctly calculated and
displayed the length of the shortest and longest chains in the hash table using
separate chaining after multiple insertions.