Ds Lab Manual
Ds Lab Manual
DS lab Manual
1)Construct an AVL tree for a given set of elements which are stored in a file. And
implement insert and delete operation on the constructed tree. Write contents of tree
into a new file using in-order.
#include <stdio.h>
#include <stdlib.h>
// An AVL tree node
struct Node {
int key;
struct Node* left;
struct Node* right;
int height;
};
// A utility function to get the height of the tree
int height(struct Node* N) {
if (N == NULL)
return 0;
return N->height;
}
// A utility function to get maximum of two integers
int max(int a, int b) {
return (a > b) ? a : b;
}
// A utility function to allocate a new node with the given key and NULL left and right pointers.
struct Node* newNode(int key) {
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->key = key;
node->left = NULL;
node->right = NULL;
node->height = 1; // new node is initially added at leaf
return (node);
}
// A utility function to right rotate subtree rooted with y
struct Node* rightRotate(struct Node* y) {
struct Node* x = y->left;
struct Node* T2 = x->right;
// Perform rotation
x->right = y;
y->left = T2;
// Update heights
y->height = max(height(y->left), height(y->right)) + 1;
x->height = max(height(x->left), height(x->right)) + 1;
// Return new root
return x;
}
// A utility function to left rotate subtree rooted with x
struct Node* leftRotate(struct Node* x) {
struct Node* y = x->right;
struct Node* T2 = y->left;
// Perform rotation
y->left = x;
x->right = T2;
// Update heights
x->height = max(height(x->left), height(x->right)) + 1;
y->height = max(height(y->left), height(y->right)) + 1;
// Return new root
return y;
}
// A utility function to find the node with the minimum key value found in that tree.
struct Node* minValueNode(struct Node* node) {
struct Node* current = node;
// Recursive function to delete a node with given key from subtree with given root. It returns root of
the modified subtree.
struct Node* deleteNode(struct Node* root, int key) {
// STEP 1: PERFORM STANDARD BST DELETE
if (root == NULL)
return root;
// If the key to be deleted is smaller than the root's key, then it lies in left subtree
if (key < root->key)
root->left = deleteNode(root->left, key);
// If the key to be deleted is greater than the root's key, then it lies in right subtree
else if (key > root->key)
root->right = deleteNode(root->right, key);
// No child case
if (temp == NULL) {
temp = root;
root = NULL;
} else // One child case
*root = *temp; // Copy the contents of the non-empty child
free(temp);
} else {
// node with two children: Get the inorder successor (smallest in the right subtree)
struct Node* temp = minValueNode(root->right);
// STEP 3: GET THE BALANCE FACTOR OF THIS NODE (to check whether this node became
unbalanced)
int balance = getBalance(root);
return root;
}
fclose(file);
return root;
}
int main() {
struct Node* root = NULL;
// Write the contents of the tree to a new file using in-order traversal
FILE* outputFile = fopen("output.txt", "w");
if (!outputFile) {
printf("Unable to open file\n");
return 1;
}
inorder(root, outputFile);
fclose(outputFile);
return 0;
}
2. Construct B-Tree an order of 5 with a set of 100 random elements stored in array. Implement
searching, insertion and deletion operations.
#include <stdio.h>
#include <stdlib.h>
#define ORDER 5 // Maximum number of children a node can have
typedef struct BTreeNode {
int keys[ORDER - 1];
struct BTreeNode* children[ORDER];
int n; // Current number of keys
int leaf; // 1 if leaf node, otherwise 0
} BTreeNode;
BTree* createTree() {
BTree* tree = (BTree*)malloc(sizeof(BTree));
tree->root = createNode(1);
return tree;
}
BTreeNode* search(BTreeNode* node, int key) {
int i = 0;
while (i < node->n && key > node->keys[i]) {
i++;
}
if (i < node->n && key == node->keys[i]) {
return node;
}
if (node->leaf) {
return NULL;
}
return search(node->children[i], key);
}
void splitChild(BTreeNode* parent, int index, BTreeNode* child) {
BTreeNode* newChild = createNode(child->leaf);
newChild->n = ORDER / 2;
int i = 0;
if (newRoot->keys[0] < key) {
i++;
}
insertNonFull(newRoot->children[i], key);
tree->root = newRoot;
} else {
insertNonFull(root, key);
}
}
void merge(BTreeNode* node, int index) {
BTreeNode* child = node->children[index];
BTreeNode* sibling = node->children[index + 1];
child->keys[ORDER / 2 - 1] = node->keys[index];
child->n += sibling->n + 1;
node->n--;
free(sibling);
}
child->n += 1;
sibling->n -= 1;
} else if (index != node->n && node->children[index + 1]->n >= ORDER / 2) {
BTreeNode* child = node->children[index];
BTreeNode* sibling = node->children[index + 1];
child->keys[child->n] = node->keys[index];
if (!(child->leaf)) {
child->children[child->n + 1] = sibling->children[0];
}
node->keys[index] = sibling->keys[0];
// Perform deletion
delete(tree, key);
result = search(tree->root, key);
if (result != NULL) {
return 0;
}
3.Construct Min and Max Heap using arrays, delete any element and display the content
of the Heap.
#include <stdio.h>
#include <stdlib.h>
minHeapify(heap, smallest);
}
}
printf("\n");
}
typedef struct MaxHeap {
int size;
int arr[MAX_SIZE];
} MaxHeap;
void maxHeapify(MaxHeap *heap, int index) {
int largest = index;
int left = 2 * index + 1;
int right = 2 * index + 2;
printf("Min Heap:\n");
displayMinHeap(&minHeap);
printf("Max Heap:\n");
displayMaxHeap(&maxHeap);
return 0;
}
4.Implement BFT and DFT for given graph, when graph is represented by
a) Adjacency Matrix b) Adjacency Lists
#include <stdio.h>
#include <stdlib.h>
visited[startVertex] = 1;
queue[rear++] = startVertex;
newNode = createNode(src);
newNode->next = graph->adjLists[dest];
graph->adjLists[dest] = newNode; // For undirected graph
}
visited[startVertex] = 1;
queue[rear++] = startVertex;
int main() {
// Example for Adjacency Matrix
GraphMatrix graphMatrix;
initGraphMatrix(&graphMatrix, 5);
addEdgeMatrix(&graphMatrix, 0, 1);
addEdgeMatrix(&graphMatrix, 0, 4);
addEdgeMatrix(&graphMatrix, 1, 2);
addEdgeMatrix(&graphMatrix, 1, 3);
addEdgeMatrix(&graphMatrix, 1, 4);
addEdgeMatrix(&graphMatrix, 2, 3);
addEdgeMatrix(&graphMatrix, 3, 4);
return 0;
}
Node* adjLists[MAX_VERTICES];
bool visited[MAX_VERTICES];
int disc[MAX_VERTICES];
int low[MAX_VERTICES];
int parent[MAX_VERTICES];
bool ap[MAX_VERTICES]; // Articulation points
} Graph;
newNode = createNode(src);
newNode->next = graph->adjLists[dest];
graph->adjLists[dest] = newNode; // For undirected graph
}
typedef struct Stack {
int top;
int array[MAX_VERTICES];
int count;
} Stack;
push(stack, v);
BCCUtil(graph, v, stack, time);
if (!isStackEmpty(&stack)) {
printf("Biconnected Component: ");
while (!isStackEmpty(&stack)) {
printf("%d ", pop(&stack));
}
printf("\n");
}
}
int main() {
Graph graph;
initGraph(&graph, 5);
addEdge(&graph, 0, 1);
addEdge(&graph, 0, 2);
addEdge(&graph, 1, 2);
addEdge(&graph, 1, 3);
addEdge(&graph, 3, 4);
addEdge(&graph, 2, 3);
return 0;
}
6.Implement Quick sort and Merge sort and observe the execution time for various
input sizes (Average, Worst and Best cases).
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
}
}
swap(&arr[i + 1], &arr[high]);
return i + 1;
}
int i = 0, j = 0, k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
arr[k] = L[i];
i++;
k++;
}
7.Compare the performance of Single Source Shortest Paths using Greedy method when
the graph is represented by adjacency matrix and adjacency lists.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <limits.h>
#include <time.h>
graph->numVertices = numVertices;
for (int i = 0; i < numVertices; i++) {
for (int j = 0; j < numVertices; j++) {
graph->adjMatrix[i][j] = INF;
}
}
}
return min_index;
}
dist[src] = 0;
return min_index;
}
dist[src] = 0;
}
void generateGraphMatrix(GraphMatrix* graph, int numEdges) {
for (int i = 0; i < numEdges; i++) {
int src = rand() % graph->numVertices;
int dest = rand() % graph->numVertices;
int weight = rand() % 100 + 1;
addEdgeMatrix(graph, src, dest, weight);
}
}
int main() {
int sizes[] = {10, 50, 100, 500, 1000};
int numSizes = sizeof(sizes) / sizeof(sizes[0]);
srand(time(0));
GraphMatrix graphMatrix;
initGraphMatrix(&graphMatrix, size);
generateGraphMatrix(&graphMatrix, numEdges);
GraphList graphList;
initGraphList(&graphList, size);
generateGraphList(&graphList, numEdges);
return 0;
}
// A utility function to find the maximum deadline in the given array of jobs
int findMaxDeadline(Job jobs[], int n) {
int maxDeadline = jobs[0].deadline;
for (int i = 1; i < n; i++) {
if (jobs[i].deadline > maxDeadline) {
maxDeadline = jobs[i].deadline;
}
}
return maxDeadline;
}
printf("Given jobs:\n");
for (int i = 0; i < n; i++) {
printf("Job %c: Deadline = %d, Profit = %d\n", jobs[i].id, jobs[i].deadline, jobs[i].profit);
}
jobSequencingWithDeadlines(jobs, n);
return 0;
}
return K[n][W];
}
return 0;
}
#define N 8 // You can change N to any number to solve the N-Queens problem for different
board sizes
}
}
return true;
}
// Consider this column and try placing this queen in all rows one by one
for (int i = 0; i < N; i++) {
// Check if the queen can be placed on board[i][col]
if (isSafe(board, i, col)) {
// Place this queen in board[i][col]
board[i][col] = 1;
// If placing queen in board[i][col] doesn't lead to a solution, then remove queen from
board[i][col]
board[i][col] = 0; // Backtrack
}
}
// If the queen cannot be placed in any row in this column col, then return false
return false;
}
// This function solves the N-Queens problem using Backtracking. It mainly uses solveNQUtil()
to solve the problem. It returns false if queens cannot be placed, otherwise, it returns true and
prints the placement of queens in the form of 1s. Please note that there may be more than one
solutions, this function prints one of the feasible solutions.
bool solveNQ() {
int board[N][N] = {0};
if (!solveNQUtil(board, 0)) {
printf("Solution does not exist");
return false;
}
printSolution(board);
return true;
}
if (included[i]) {
printf("Item %d\n", items[i]);
}
}
}
int maxValue = 0;
int included[n];
int solution[n];
for (int i = 0; i < n; i++) {
included[i] = 0;
solution[i] = 0;
}
return 0;
}
12.Implement Travelling Sales Person problem using Branch and Bound approach
C program to solve the TSP using the Branch and Bound approach
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <stdbool.h>
#define N 4 // Change this value to solve TSP for different numbers of cities
// Function to print the solution
void printSolution(int path[]) {
printf("Path: ");
for (int i = 0; i < N; i++) {
printf("%d ", path[i]);
}
printf("%d\n", path[0]);
}
// Function to find the second minimum edge cost having an end at the vertex i
int secondMin(int graph[N][N], int i) {
int first = INT_MAX, second = INT_MAX;
for (int j = 0; j < N; j++) {
if (i == j) continue;
if (graph[i][j] <= first) {
second = first;
first = graph[i][j];
} else if (graph[i][j] <= second && graph[i][j] != first) {
second = graph[i][j];
}
}
return second;
}
if (level == 1) {
curr_bound -= ((firstMin(graph, curr_path[level - 1]) + firstMin(graph, i)) / 2);
} else {
curr_bound -= ((secondMin(graph, curr_path[level - 1]) + firstMin(graph, i)) / 2);
}
int curr_bound = 0;
for (int i = 0; i < N; i++) {
curr_bound += (firstMin(graph, i) + secondMin(graph, i));
}
visited[0] = true;
curr_path[0] = 0;
return 0;
}