Ads Lab Manual-b.tech
Ads Lab Manual-b.tech
LAB MANUAL
(2024-2025)
Dr.KOPPULA CHINABUSI
Professor
Page 1
Dr.KCB
DEPT : CSE TITS
JAWAHARLALNEHRUTECHNOLOGICALUNIVERSITY:KAKINADA
KAKINADA–533003,AndhraPradesh,India
L T P C
B.TECH II
Year - I 0 0 4 2
Semester
Advanced
Course DataStructures&Algorithms
Objectives: Analysis Lab
Sample Programs:
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.
2. Construct B-Tree an order of 5 with a set of 100 random elements stored in
array. Implement searching, insertion and deletion operations.
3. Construct Min and Max Heap using arrays, delete any element and display the
content of the Heap.
4. Implement BFT and DFT for given graph, when graph is represented by
a) Adjacency Matrix b) Adjacency Lists
5. Write a program for finding the biconnected components in a given graph.
6. Implement Quick sort and Merge sort and observe the execution time for
various input sizes (Average, Worst and Best cases).
7. Compare the performance of Single Source Shortest Paths using Greedy method
when the graph is represented by adjacency matrix and adjacency lists.
8. Implement Job Sequencing with deadlines using Greedy strategy.
9. Write a program to solve 0/1 Knapsack problem Using Dynamic Programming.
10. Implement N-Queens Problem Using Backtracking.
Page 2
Dr.KCB
DEPT : CSE TITS
Page 3
Dr.KCB
DEPT : CSE TITS
JAWAHARLALNEHRUTECHNOLOGICALUNIVERSITY:KAKINADA
KAKINADA–533003,AndhraPradesh,India
Reference Books:
1. Fundamentals of Data Structures in C++, Horowitz Ellis, SahniSartaj, Mehta,
Dinesh, 2ndEdition, Universities Press
2. Computer Algorithms/C++ Ellis Horowitz, SartajSahni, SanguthevarRajasekaran,
nd
2 Edition, University Press
3. Data Structures and program design in C, Robert Kruse, Pearson Education Asia
4. An introduction to Data Structures with applications, Trembley& Sorenson,
McGraw Hill
Page 4
Dr.KCB
DEPT : CSE TITS
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.
return newNode;
}
// 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;
// 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;
// Get the balance factor to check whether this node became unbalanced
int balance = getBalance(root);
return rightRotate(root);
}
// No child case
DEPT : CSE TITS
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
struct TreeNode* temp = minValueNode(root->right);
// Get the balance factor to check whether this node became unbalanced
int balance = getBalance(root);
return root;
}
int main() {
struct TreeNode* root = NULL;
int choice, key;
DEPT : CSE TITS
do {
printf("\nAVL Tree Operations:\n");
printf("1. Insert a node\n");
printf("2. Delete a node\n");
printf("3. In-order Traversal\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter the key to insert: ");
scanf("%d", &key);
root = insert(root, key);
break;
case 2:
printf("Enter the key to delete: ");
scanf("%d", &key);
root = deleteNode(root, key);
break;
case 3:
printf("In-order Traversal: ");
inOrderTraversal(root);
printf("\n");
break;
case 4:
// Free allocated memory
freeAVLTree(root);
printf("Exiting...\n");
break;
default:
printf("Invalid choice! Please enter a valid option.\n");
}
return 0;
DEPT : CSE TITS
Output:
3. In-order Traversal
4. Exit
Enter your choice: 3
In-order Traversal: 34 45
#include <stdio.h>
#include <stdlib.h>
#define ORDER 5
typedef struct BTreeNode {
int keys[ORDER - 1];
struct BTreeNode *children[ORDER];
int numKeys;
int isLeaf;
} BTreeNode;
BTreeNode* createNode(int isLeaf) {
BTreeNode *newNode = (BTreeNode *)mBTreeNode* search(BTreeNode *root, int key) {
int i = 0;
while (i < root->numKeys && key > root->keys[i]) {
i++;
}
if (i < root->numKeys && key == root->keys[i]) {
return root;
}
if (root->isLeaf) {
return NULL;
}
DEPT : CSE TITS
3.Construct Min and Max Heap using arrays, delete any element and display
the content of the Heap.
// Max-Heap data structure in C
#include <stdio.h>
int size = 0;
void swap(int *a, int *b)
{
int temp = *b;
*b = *a;
*a = temp;
}
void heapify(int array[], int size, int i)
DEPT : CSE TITS
{
if (size == 1)
{
printf("Single element in the heap");
}
else
{
int largest = i;
int l = 2 * i + 1;
int r = 2 * i + 2;
if (l < size && array[l] > array[largest])
largest = l;
if (r < size && array[r] > array[largest])
largest = r;
if (largest != i)
{
swap(&array[i], &array[largest]);
heapify(array, size, largest);
}
}
}
void insert(int array[], int newNum)
{
if (size == 0)
{
array[0] = newNum;
size += 1;
}
else
{
array[size] = newNum;
size += 1;
for (int i = size / 2 - 1; i >= 0; i--)
{
heapify(array, size, i);
}
}
DEPT : CSE TITS
}
void deleteRoot(int array[], int num)
{
int i;
for (i = 0; i < size; i++)
{
if (num == array[i])
break;
}
insert(array, 3);
insert(array, 4);
insert(array, 9);
insert(array, 5);
insert(array, 2);
deleteRoot(array, 4);
DEPT : CSE TITS
printArray(array, size);
}
4.Implement BFT and DFT for given graph, when graph is represented by
a) Adjacency Matrix b) Adjacency Lists
// Update value to 1
Adj[x][y] = 1;
Adj[y][x] = 1;
}
}
// Driver Code
int main()
{
// Number of vertices
N = 5;
// Given Edges
int arr[][2]
= { { 1, 2 }, { 2, 3 },
{ 4, 5 }, { 1, 5 } };
// Number of Edges
M = sizeof(arr) / sizeof(arr[0]);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
DEPT : CSE TITS
struct node {
int vertex;
struct node* next;
};
struct node* createNode(int);
struct Graph {
int numVertices;
struct node** adjLists;
};
// Create a node
struct node* createNode(int v) {
struct node* newNode = malloc(sizeof(struct node));
newNode->vertex = v;
newNode->next = NULL;
return newNode;
}
// Create a graph
struct Graph* createAGraph(int vertices) {
struct Graph* graph = malloc(sizeof(struct Graph));
graph->numVertices = vertices;
int i;
for (i = 0; i < vertices; i++)
graph->adjLists[i] = NULL;
return graph;
}
// Add edge
void addEdge(struct Graph* graph, int s, int d) {
// Add edge from s to d
struct node* newNode = createNode(d);
newNode->next = graph->adjLists[s];
graph->adjLists[s] = newNode;
int main() {
struct Graph* graph = createAGraph(4);
addEdge(graph, 0, 1);
addEdge(graph, 0, 2);
addEdge(graph, 0, 3);
addEdge(graph, 1, 2);
printGraph(graph);
return 0;
}
class Edge {
int u;
int v;
Edge(int u, int v)
{
this.u = u;
this.v = v;
}
};
// Constructor
Graph(int v)
{
V = v;
E = 0;
adj = new LinkedList[v];
for (int i = 0; i < v; ++i)
adj[i] = new LinkedList();
}
// If u is an articulation point,
// pop all edges from stack till u -- v
if ((disc[u] == 1 && children > 1) || (disc[u] > 1 && low[v] >=
disc[u])) {
while (st.getLast().u != u || st.getLast().v != v) {
System.out.print(st.getLast().u + "--" +
st.getLast().v + " ");
st.removeLast();
}
System.out.println(st.getLast().u + "--" + st.getLast().v
+ " ");
st.removeLast();
count++;
}
}
int j = 0;
g.addEdge(1, 3);
g.addEdge(3, 1);
g.addEdge(2, 3);
g.addEdge(3, 2);
g.addEdge(2, 4);
g.addEdge(4, 2);
g.addEdge(3, 4);
g.addEdge(4, 3);
g.addEdge(1, 5);
g.addEdge(5, 1);
g.addEdge(0, 6);
g.addEdge(6, 0);
g.addEdge(5, 6);
g.addEdge(6, 5);
g.addEdge(5, 7);
g.addEdge(7, 5);
g.addEdge(5, 8);
g.addEdge(8, 5);
g.addEdge(7, 8);
g.addEdge(8, 7);
g.addEdge(8, 9);
g.addEdge(9, 8);
g.addEdge(10, 11);
g.addEdge(11, 10);
g.BCC();
6.Implement Quick sort and Merge sort and observe the execution time for various input sizes
(Average, Worst and Best cases).
#include<stdio.h>
*first = *second;
*second = temp;
if (arr[j] < p)
i++;
return (i + 1);
if (l < h)
int i;
int main()
print_Array(array, length);
printf("\n");
DEPT : CSE TITS
quick_sort(array, 0, length-1);
print_Array(array, length);
return 0;
QuickSort in Java
import java.util.*;
if(p<r)
{int q=partition(a,p,r);
quickSort(a,p,q-1);
quickSort(a,q+1,r);
DEPT : CSE TITS
int pivot=a[r];
int pindex=b-1;
for(int i=b;i<r;i++)
if(a[i]<=pivot)
pindex++;
int t=a[i];
a[i]=a[pindex];
a[pindex]=t;
pindex++;
DEPT : CSE TITS
int t=a[pindex];
a[pindex]=a[r];
a[r]=t;
return pindex;
for(int i=0;i<a.length;i++)
System.out.println(a[i]+" ");
int n=in.nextInt();
DEPT : CSE TITS
for(int i=0;i<a.length;i++)
a[i]=in.nextInt();
quickSort(a,0,n-1);
display(a);
merge(arr, l, m, r);
}
}
// UTILITY FUNCTIONS
// Function to print an array
void printArray(int A[], int size)
{
int i;
for (i = 0; i < size; i++)
printf("%d ", A[i]);
printf("\n");
}
// Driver code
DEPT : CSE TITS
int main()
{
int arr[] = { 12, 11, 13, 5, 6, 7 };
int arr_size = sizeof(arr) / sizeof(arr[0]);
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
DEPT : CSE TITS
return min_index;
}
// driver's code
int main()
{
/* Let us create the example graph discussed above */
int graph[V][V] = { { 0, 4, 0, 0, 0, 0, 0, 8, 0 },
{ 4, 0, 8, 0, 0, 0, 0, 11, 0 },
{ 0, 8, 0, 7, 0, 4, 0, 0, 2 },
{ 0, 0, 7, 0, 9, 14, 0, 0, 0 },
{ 0, 0, 0, 9, 0, 10, 0, 0, 0 },
{ 0, 0, 4, 14, 10, 0, 2, 0, 0 },
{ 0, 0, 0, 0, 0, 2, 0, 1, 6 },
{ 8, 11, 0, 0, 0, 0, 1, 0, 7 },
{ 0, 0, 2, 0, 0, 0, 6, 7, 0 } };
// Function call
dijkstra(graph, 0);
return 0;
}
Out put:
3 19
4 21
5 11
6 9
7 8
8 14
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
Jobs arr[] = {
{ 'a', 2, 100 },
{ 'b', 2, 20 },
{ 'c', 1, 40 },
{ 'd', 3, 35 },
{ 'e', 1, 25 }
};
#include<stdio.h>
int max(int a, int b) {
if(a>b){
return a;
} else {
return b;
}
}
int knapsack(int W, int wt[], int val[], int n) {
int i, w;
DEPT : CSE TITS
int knap[n+1][W+1];
for (i = 0; i <= n; i++) {
for (w = 0; w <= W; w++) {
if (i==0 || w==0)
knap[i][w] = 0;
else if (wt[i-1] <= w)
knap[i][w] = max(val[i-1] + knap[i-1][w-wt[i-1]], knap[i-1][w]);
else
knap[i][w] = knap[i-1][w];
}
}
return knap[n][W];
}
int main() {
int val[] = {20, 25, 40};
int wt[] = {25, 20, 30};
int W = 50;
int n = sizeof(val)/sizeof(val[0]);
printf("The solution is : %d", knapsack(W, wt, val, n));
return 0;
}
#include<stdio.h>
#define BOARD_SIZE 5
void displayChess(int chBoard[BOARD_SIZE][BOARD_SIZE]) {
for (int row = 0; row < BOARD_SIZE; row++) {
for (int col = 0; col < BOARD_SIZE; col++)
printf("%d ", chBoard[row][col]);
printf("\n");
}
}
int isQueenPlaceValid(int chBoard[BOARD_SIZE][BOARD_SIZE], int crntRow, int crntCol) {
// checking if queen is in the left or not
for (int i = 0; i < crntCol; i++)
if (chBoard[crntRow][i])
return 0;
for (int i = crntRow, j = crntCol; i >= 0 && j >= 0; i--, j--)
//checking if queen is in the left upper diagonal or not
if (chBoard[i][j])
return 0;
for (int i = crntRow, j = crntCol; j >= 0 && i < BOARD_SIZE; i++, j--)
//checking if queen is in the left lower diagonal or not
DEPT : CSE TITS
if (chBoard[i][j])
return 0;
return 1;
}
int solveProblem(int chBoard[BOARD_SIZE][BOARD_SIZE], int crntCol) {
//when N queens are placed successfully
if (crntCol >= BOARD_SIZE)
return 1;
// checking placement of queen is possible or not
for (int i = 0; i < BOARD_SIZE; i++) {
if (isQueenPlaceValid(chBoard, i, crntCol)) {
//if validate, place the queen at place (i, col)
chBoard[i][crntCol] = 1;
//Go for the other columns recursively
if (solveProblem(chBoard, crntCol + 1))
return 1;
//When no place is vacant remove that queen
chBoard[i][crntCol] = 0;
}
}
return 0;
}
int displaySolution() {
int chBoard[BOARD_SIZE][BOARD_SIZE];
for(int i = 0; i < BOARD_SIZE; i++)
for(int j = 0; j < BOARD_SIZE; j++)
//set all elements to 0
chBoard[i][j] = 0;
//starting from 0th column
if (solveProblem(chBoard, 0) == 0) {
printf("Solution does not exist");
return 0;
}
displayChess(chBoard);
return 1;
}
int main() {
displaySolution();
return 0;
}
Output:
10000
00010
01000
00001
00 1 0 0
DEPT : CSE TITS
// Driver code
int main()
{
int profit[] = { 60, 100, 120 };
int weight[] = { 10, 20, 30 };
int W = 50;
int n = sizeof(profit) / sizeof(profit[0]);
printf("%d", knapSack(W, weight, profit, n));
return 0;
}
DEPT : CSE TITS
Output: 220
ncity = least(city);
if (ncity == 999) {
ncity = 0;
printf("%d", ncity + 1);
cost += a[city][ncity];
return;
}
mincost(ncity);
}
int least(int c) {
int i, nc = 999;
int min = 999, kmin;
for (i = 0; i < n; i++) {
if ((a[c][i] != 0) && (visited[i] == 0))
if (a[c][i] < min) {
min = a[i][0] + a[c][i];
kmin = a[c][i];
nc = i;
}
}
if (min != 999)
cost += kmin;
return nc;
}
void put() {
printf("\n\nMinimum cost:");
printf("%d", cost);
}
void main()
{
get();
printf("\n\nThe Path is:\n\n");
mincost(0);
put();
}
Output:
Enter No. of Cities: 6
Enter Cost Matrix:
99 10 15 20 99 8
5 99 9 10 8 99
6 13 99 12 99 5
8 8 9 99 6 99
99 10 99 6 99 99
10 99 5 99 99 99
DEPT : CSE TITS
Minimum cost:46