0% found this document useful (0 votes)
11 views

Ads Lab Manual-b.tech

The document is a lab manual for the Advanced Data Structures & Algorithm Analysis course for B.Tech II Year students at Tirumala Institute of Technology and Science. It outlines the course objectives, experiments, sample programs, and reference materials related to data structures and algorithms. Key topics include AVL trees, B-Trees, graph traversals, sorting techniques, and various algorithmic problems.

Uploaded by

cseaboys2026
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Ads Lab Manual-b.tech

The document is a lab manual for the Advanced Data Structures & Algorithm Analysis course for B.Tech II Year students at Tirumala Institute of Technology and Science. It outlines the course objectives, experiments, sample programs, and reference materials related to data structures and algorithms. Key topics include AVL trees, B-Trees, graph traversals, sorting techniques, and various algorithmic problems.

Uploaded by

cseaboys2026
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 49

DEPT : CSE TITS

ADVANCED DATA STRUCTURES & ALGORITHM


ANALYSIS LAB
(R23D5 )

LAB MANUAL

B.TECH II YEAR– I SEM (R23)

(2024-2025)

Dr.KOPPULA CHINABUSI
Professor

DEPARTMENT OFCOMPUTER SCIENCE AND


ENGINEERING

TIRUMALA INSTITUTE OF TECHNOLOGY AND SCINCE


ApprovedbyAICTE&AffiliatedToJNTUK,Kakinada.
Salluru,Narasaraopet,Palnadu(D.T),AndhraPradesh

(Autonomous Institution – UGC, Govt. of India)

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

The objectives of the course is to


 acquire practical skills in constructing and managing Data structures
 apply the popular algorithm design methods in problem-solving scenarios

Experiments covering the Topics:


 Operations on AVL trees, B-Trees, Heap Trees
 Graph Traversals
 Sorting techniques
 Minimum cost spanning trees
 Shortest path algorithms
 0/1 Knapsack Problem
 Travelling Salesperson problem
 Optimal Binary Search Trees
 N-Queens Problem
 Job Sequencing

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

11. Use Backtracking strategy to solve 0/1 Knapsack problem.


12. Implement Travelling Sales Person problem using Branch and Bound approach.

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

Online Learning Resources:


1. http://cse01-iiith.vlabs.ac.in/
2. http://peterindia.net/Algorithms.html

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.

// Including necessary header files


#include <stdio.h>
#include <stdlib.h>

// Structure for a tree node


struct TreeNode {
int data;
struct TreeNode* left;
struct TreeNode* right;
int height; // Height of the node
};

// Function to get the height of a node


int height(struct TreeNode* node) {
if (node == NULL)
return 0;
return node->height;
}

// Function to get the maximum of two integers


int max(int a, int b) {
return (a > b) ? a : b;
}

// Function to create a new node with a given key


struct TreeNode* createNode(int key) {
struct TreeNode* newNode = (struct TreeNode*)malloc(sizeof(struct TreeNode));
if (newNode != NULL) {
newNode->data = key;
newNode->left = NULL;
newNode->right = NULL;
newNode->height = 1; // New node is initially at height 1
}
DEPT : CSE TITS

return newNode;
}

// Function to right rotate subtree rooted with y


struct TreeNode* rightRotate(struct TreeNode* y) {
struct TreeNode* x = y->left;
struct TreeNode* 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;
}

// Function to left rotate subtree rooted with x


struct TreeNode* leftRotate(struct TreeNode* x) {
struct TreeNode* y = x->right;
struct TreeNode* 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;
}
DEPT : CSE TITS

// Function to get the balance factor of a node


int getBalance(struct TreeNode* node) {
if (node == NULL)
return 0;
return height(node->left) - height(node->right);
}

// Function to insert a key into the AVL tree


struct TreeNode* insert(struct TreeNode* root, int key) {
// Perform standard BST insert
if (root == NULL)
return createNode(key);

if (key < root->data)


root->left = insert(root->left, key);
else if (key > root->data)
root->right = insert(root->right, key);
else // Duplicate keys not allowed
return root;

// Update height of the current node


root->height = 1 + max(height(root->left), height(root->right));

// Get the balance factor to check whether this node became unbalanced
int balance = getBalance(root);

// Left Left Case


if (balance > 1 && key < root->left->data)
return rightRotate(root);

// Right Right Case


if (balance < -1 && key > root->right->data)
return leftRotate(root);

// Left Right Case


if (balance > 1 && key > root->left->data) {
root->left = leftRotate(root->left);
DEPT : CSE TITS

return rightRotate(root);
}

// Right Left Case


if (balance < -1 && key < root->right->data) {
root->right = rightRotate(root->right);
return leftRotate(root);
}

// Return the unchanged node pointer


return root;
}

// Function to find the node with the minimum value


struct TreeNode* minValueNode(struct TreeNode* node) {
struct TreeNode* current = node;
while (current->left != NULL)
current = current->left;
return current;
}

// Function to delete a key from the AVL tree


struct TreeNode* deleteNode(struct TreeNode* root, int key) {
if (root == NULL)
return root;

// Perform standard BST delete


if (key < root->data)
root->left = deleteNode(root->left, key);
else if (key > root->data)
root->right = deleteNode(root->right, key);
else {
// Node with only one child or no child
if ((root->left == NULL) || (root->right == NULL)) {
struct TreeNode* temp = root->left ? root->left : root->right;

// 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);

// Copy the inorder successor's data to this node


root->data = temp->data;

// Delete the inorder successor


root->right = deleteNode(root->right, temp->data);
}
}

// If the tree had only one node, then return


if (root == NULL)
return root;

// Update height of the current node


root->height = 1 + max(height(root->left), height(root->right));

// Get the balance factor to check whether this node became unbalanced
int balance = getBalance(root);

// Left Left Case


if (balance > 1 && getBalance(root->left) >= 0)
return rightRotate(root);

// Left Right Case


if (balance > 1 && getBalance(root->left) < 0) {
root->left = leftRotate(root->left);
return rightRotate(root);
DEPT : CSE TITS

// Right Right Case


if (balance < -1 && getBalance(root->right) <= 0)
return leftRotate(root);

// Right Left Case


if (balance < -1 && getBalance(root->right) > 0) {
root->right = rightRotate(root->right);
return leftRotate(root);
}

return root;
}

// Function to perform in-order traversal of the AVL tree


void inOrderTraversal(struct TreeNode* root) {
if (root != NULL) {
inOrderTraversal(root->left);
printf("%d ", root->data);
inOrderTraversal(root->right);
}
}

// Function to free the memory allocated for the AVL tree


void freeAVLTree(struct TreeNode* root) {
if (root != NULL) {
freeAVLTree(root->left);
freeAVLTree(root->right);
free(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");
}

} while (choice != 4);

return 0;
DEPT : CSE TITS

Output:

AVL Tree Operations:


1. Insert a node
2. Delete a node
3. In-order Traversal
4. Exit
Enter your choice: 1
Enter the key to insert: 87

AVL Tree Operations:


1. Insert a node
2. Delete a node
3. In-order Traversal
4. Exit
Enter your choice: 3
In-order Traversal: 87

AVL Tree Operations:


1. Insert a node
2. Delete a node
3. In-order Traversal
4. Exit
Enter your choice: 1
Enter the key to insert: 45

AVL Tree Operations:


1. Insert a node
2. Delete a node
3. In-order Traversal
4. Exit
Enter your choice: 1
Enter the key to insert: 34

AVL Tree Operations:


1. Insert a node
2. Delete a node
3. In-order Traversal
4. Exit
Enter your choice: 3
In-order Traversal: 34 45 87

AVL Tree Operations:


1. Insert a node
2. Delete a node
3. In-order Traversal
4. Exit
Enter your choice: 2
Enter the key to delete: 87

AVL Tree Operations:


1. Insert a node
2. Delete a node
DEPT : CSE TITS

3. In-order Traversal
4. Exit
Enter your choice: 3
In-order Traversal: 34 45

AVL Tree Operations:


1. Insert a node
2. Delete a node
3. In-order Traversal
4. Exit
Enter your choice: 4
Exiting...

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
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

return search(root->children[i], key);


}
void insertNonFull(BTreeNode *node, int key);
void splitChild(BTreeNode *parent, int i, BTreeNode *child);
void insert(BTreeNode **root, int key) {
BTreeNode *r = *root;
if (r->numKeys == ORDER - 1) {
BTreeNode *s = createNode(0);
*root = s;
s->children[0] = r;
splitChild(s, 0, r);
insertNonFull(s, key);
} else {
insertNonFull(r, key);
}
}
void insertNonFull(BTreeNode *node, int key) {
int i = node->numKeys - 1;
if (node->isLeaf) {
while (i >= 0 && node->keys[i] > key) {
node->keys[i + 1] = node->keys[i];
i--;
}
node->keys[i + 1] = key;
node->numKeys++;
} else {
while (i >= 0 && node->keys[i] > key) {
i--;
}
i++;
if (node->children[i]->numKeys == ORDER - 1) {
splitChild(node, i, node->children[i]);
if (node->keys[i] < key) {
i++;
}
}
insertNonFull(node->children[i], key);
}
}
void splitChild(BTreeNode *parent, int i, BTreeNode *child) {
BTreeNode *z = createNode(child->isLeaf);
z->numKeys = (ORDER - 1) / 2;
for (int j = 0; j < (ORDER - 1) / 2; j++) {
DEPT : CSE TITS

z->keys[j] = child->keys[j + (ORDER + 1) / 2];


}
if (!child->isLeaf) {
for (int j = 0; j <= (ORDER - 1) / 2; j++) {
z->children[j] = child->children[j + (ORDER + 1) / 2];
}
}
child->numKeys = (ORDER - 1) / 2;
for (int j = parent->numKeys; j >= i + 1; j--) {
parent->children[j + 1] = parent->children[j];
}
parent->children[i + 1] = z;
for (int j = parent->numKeys - 1; j >= i; j--) {
parent->keys[j + 1] = parent->keys[j];
}
parent->keys[i] = child->keys[(ORDER - 1) / 2];
parent->numKeys++;
}
void deleteKey(BTreeNode *root, int key);
void delete(BTreeNode **root, int key) {
deleteKey(*root, key);
if ((*root)->numKeys == 0) {
BTreeNode *temp = *root;
if ((*root)->isLeaf) {
*root = NULL;
} else {
*root = (*root)->children[0];
}
free(temp);
}
}
void deleteKey(BTreeNode *node, int key) {
// Implementation of delete operation here
// This part is complex and involves multiple cases
}
int main() {
BTreeNode *root = createNode(1);
// Insert 100 random elements
for (int i = 0; i < 100; i++) {
insert(&root, rand() % 1000);
}
// Search for a key
int key = 500;
DEPT : CSE TITS

BTreeNode *searchResult = search(root, key);


if (searchResult != NULL) {
printf("Key %d found.\n", key);
} else {
printf("Key %d not found.\n", key);
}
// Delete a key
delete(&root, key);
// Search for the key again
searchResult = search(root, key);
if (searchResult != NULL) {
printf("Key %d found.\n", key);
} else {
printf("Key %d not found.\n", key);
}
return 0;
}
alloc(sizeof(BTreeNode));
newNode->isLeaf = isLeaf;
newNode->numKeys = 0;
for (int i = 0; i < ORDER; i++) {
newNode->children[i] = NULL;
}
return newNode;
}

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;
}

swap(&array[i], &array[size - 1]);


size -= 1;
for (int i = size / 2 - 1; i >= 0; i--)
{
heapify(array, size, i);
}
}
void printArray(int array[], int size)
{
for (int i = 0; i < size; ++i)
printf("%d ", array[i]);
printf("\n");
}
int main()
{
int array[10];

insert(array, 3);
insert(array, 4);
insert(array, 9);
insert(array, 5);
insert(array, 2);

printf("Max-Heap array: ");


printArray(array, size);

deleteRoot(array, 4);
DEPT : CSE TITS

printf("After deleting an element: ");

printArray(array, size);
}

4.Implement BFT and DFT for given graph, when graph is represented by
a) Adjacency Matrix b) Adjacency Lists

// a). C program for the above approach Adjacency Matrix


#include <stdio.h>

// N vertices and M Edges


int N, M;
DEPT : CSE TITS

// Function to create Adjacency Matrix


void createAdjMatrix(int Adj[][N + 1],
int arr[][2])
{

// Initialise all value to this


// Adjacency list to zero
for (int i = 0; i < N + 1; i++) {

for (int j = 0; j < N + 1; j++) {


Adj[i][j] = 0;
}
}

// Traverse the array of Edges


for (int i = 0; i < M; i++) {

// Find X and Y of Edges


int x = arr[i][0];
int y = arr[i][1];

// Update value to 1
Adj[x][y] = 1;
Adj[y][x] = 1;
}
}

// Function to print the created


// Adjacency Matrix
void printAdjMatrix(int Adj[][N + 1])
{

// Traverse the Adj[][]


for (int i = 1; i < N + 1; i++) {
for (int j = 1; j < N + 1; j++) {

// Print the value at Adj[i][j]


DEPT : CSE TITS

printf("%d ", Adj[i][j]);


}
printf("\n");
}
}

// 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]);

// For Adjacency Matrix


int Adj[N + 1][N + 1];

// Function call to create


// Adjacency Matrix
createAdjMatrix(Adj, arr);

// Print Adjacency Matrix


printAdjMatrix(Adj);

return 0;
}

// b).Adjascency List representation in C

#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;

graph->adjLists = malloc(vertices * sizeof(struct node*));

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;

// Add edge from d to s


newNode = createNode(s);
newNode->next = graph->adjLists[d];
graph->adjLists[d] = newNode;
}

// Print the graph


void printGraph(struct Graph* graph) {
int v;
for (v = 0; v < graph->numVertices; v++) {
struct node* temp = graph->adjLists[v];
DEPT : CSE TITS

printf("\n Vertex %d\n: ", v);


while (temp) {
printf("%d -> ", temp->vertex);
temp = temp->next;
}
printf("\n");
}
}

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;
}

5. Write a program for finding the biconnected components in a given graph.


DEPT : CSE TITS

// A Java program to find biconnected components in a given


// undirected graph
import java.io.*;
import java.util.*;

// This class represents a directed graph using adjacency


// list representation
class Graph {
private int V, E; // No. of vertices & Edges respectively
private LinkedList<Integer> adj[]; // Adjacency List

// Count is number of biconnected components. time is


// used to find discovery times
static int count = 0, time = 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();
}

// Function to add an edge into the graph


DEPT : CSE TITS

void addEdge(int v, int w)


{
adj[v].add(w);
E++;
}

// A recursive function that finds and prints strongly connected


// components using DFS traversal
// u --> The vertex to be visited next
// disc[] --> Stores discovery times of visited vertices
// low[] -- >> earliest visited vertex (the vertex with minimum
// discovery time) that can be reached from subtree
// rooted with current vertex
// *st -- >> To store visited edges
void BCCUtil(int u, int disc[], int low[], LinkedList<Edge> st,
int parent[])
{

// Initialize discovery time and low value


disc[u] = low[u] = ++time;
int children = 0;

// Go through all vertices adjacent to this


Iterator<Integer> it = adj[u].iterator();
while (it.hasNext()) {
int v = it.next(); // v is current adjacent of 'u'

// If v is not visited yet, then recur for it


if (disc[v] == -1) {
children++;
parent[v] = u;

// store the edge in stack


st.add(new Edge(u, v));
BCCUtil(v, disc, low, st, parent);

// Check if the subtree rooted with 'v' has a


DEPT : CSE TITS

// connection to one of the ancestors of 'u'


// Case 1 -- per Strongly Connected Components Article
if (low[u] > low[v])
low[u] = low[v];

// 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++;
}
}

// Update low value of 'u' only if 'v' is still in stack


// (i.e. it's a back edge, not cross edge).
// Case 2 -- per Strongly Connected Components Article
else if (v != parent[u] && disc[v] < disc[u] ) {
if (low[u] > disc[v])
low[u] = disc[v];

st.add(new Edge(u, v));


}
}
}

// The function to do DFS traversal. It uses BCCUtil()


void BCC()
{
int disc[] = new int[V];
DEPT : CSE TITS

int low[] = new int[V];


int parent[] = new int[V];
LinkedList<Edge> st = new LinkedList<Edge>();

// Initialize disc and low, and parent arrays


for (int i = 0; i < V; i++) {
disc[i] = -1;
low[i] = -1;
parent[i] = -1;
}

for (int i = 0; i < V; i++) {


if (disc[i] == -1)
BCCUtil(i, disc, low, st, parent);

int j = 0;

// If stack is not empty, pop all edges from stack


while (st.size() > 0) {
j = 1;
System.out.print(st.getLast().u + "--" + st.getLast().v + " ");
st.removeLast();
}
if (j == 1) {
System.out.println();
count++;
}
}
}

public static void main(String args[])


{
Graph g = new Graph(12);
g.addEdge(0, 1);
g.addEdge(1, 0);
g.addEdge(1, 2);
g.addEdge(2, 1);
DEPT : CSE TITS

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();

System.out.println("Above are " + g.count + " biconnected components in


graph");
}
}
// This code is contributed by Aakash Hasija
DEPT : CSE TITS

6.Implement Quick sort and Merge sort and observe the execution time for various input sizes
(Average, Worst and Best cases).

#include<stdio.h>

// Function to swap the elements

void swap_elements(int* first, int* second)

int temp = *first;

*first = *second;

*second = temp;

// In partition function l represents low and h represents high

int partition_function(int arr[], int l, int h)

int p = arr[h]; // pivot is the last element

int i = (l - 1); // Index of smaller element


DEPT : CSE TITS

for (int j = l; j <= h- 1; j++)

// If current element is smaller than the pivot

if (arr[j] < p)

i++;

swap_elements(&arr[i], &arr[j]); // swapping the elements

swap_elements(&arr[i + 1], &arr[h]);

return (i + 1);

void quick_sort(int arr[], int l, int h)

if (l < h)

int p_index = partition_function(arr, l, h);

quick_sort(arr, l, p_index - 1);


DEPT : CSE TITS

quick_sort(arr, p_index + 1, h);

//Function to print the elements of the array

void print_Array(int arr[], int len)

int i;

for (i=0; i < len; i++)

printf("%d ", arr[i]);

// Main Function or driver function

int main()

int array[] = {14, 17, 8, 90, 11, 2}; //Static array

int length = sizeof(array)/sizeof(array[0]); //For finding the length of the array

printf("Before Sorting the array: ");

print_Array(array, length);

printf("\n");
DEPT : CSE TITS

printf("After Sorting the array: ");

//Indexing starts from 0(zero) in array (that is why length-1)

quick_sort(array, 0, length-1);

print_Array(array, length);

return 0;

Output of the program:

Before Sorting the array: 14 17 8 90 11 2

After Sorting the array: 2 8 11 14 17 90

QuickSort in Java
import java.util.*;

public class QuickSortDemo

static void quickSort(int[] a,int p,int r)

if(p<r)

{int q=partition(a,p,r);

quickSort(a,p,q-1);

quickSort(a,q+1,r);
DEPT : CSE TITS

static int partition(int[] a,int b,int r) // partition method

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;

static void display(int[] a) // method to display the array

for(int i=0;i<a.length;i++)

System.out.println(a[i]+" ");

public static void main(String[] args) // main method

Scanner in=new Scanner(System.in);

System.out.println(“enter size of array”);

int n=in.nextInt();
DEPT : CSE TITS

int[] a =new int[n];

System.out.println(“enter the elements of array”);

for(int i=0;i<a.length;i++)

a[i]=in.nextInt();

quickSort(a,0,n-1);

System.out.println(“Array after sorting the elements: ”);

display(a);

// C program for Merge Sort


#include <stdio.h>
#include <stdlib.h>

// Merges two subarrays of arr[].


// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int arr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;

// Create temp arrays


int L[n1], R[n2];

// Copy data to temp arrays


DEPT : CSE TITS

// L[] and R[]


for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];

// Merge the temp arrays back


// into arr[l..r]
// Initial index of first subarray
i = 0;

// Initial index of second subarray


j = 0;

// Initial index of merged subarray


k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
}
else {
arr[k] = R[j];
j++;
}
k++;
}

// Copy the remaining elements


// of L[], if there are any
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}

// Copy the remaining elements of


DEPT : CSE TITS

// R[], if there are any


while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}

// l is for left index and r is


// right index of the sub-array
// of arr to be sorted
void mergeSort(int arr[], int l, int r)
{
if (l < r) {
// Same as (l+r)/2, but avoids
// overflow for large l and r
int m = l + (r - l) / 2;

// Sort first and second halves


mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);

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]);

printf("Given array is \n");


printArray(arr, arr_size);

mergeSort(arr, 0, arr_size - 1);

printf("\nSorted array is \n");


printArray(arr, arr_size);
return 0;
}

7.Compare the performance of Single Source Shortest Paths using


Greedy method when the graph is represented by adjacency matrix and
adjacency lists.

// C program for Dijkstra's single source shortest path


// algorithm. The program is for adjacency matrix
// representation of the graph

#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
DEPT : CSE TITS

// Number of vertices in the graph


#define V 9

// A utility function to find the vertex with minimum


// distance value, from the set of vertices not yet included
// in shortest path tree
int minDistance(int dist[], bool sptSet[])
{
// Initialize min value
int min = INT_MAX, min_index;

for (int v = 0; v < V; v++)


if (sptSet[v] == false && dist[v] <= min)
min = dist[v], min_index = v;

return min_index;
}

// A utility function to print the constructed distance


// array
void printSolution(int dist[])
{
printf("Vertex \t\t Distance from Source\n");
for (int i = 0; i < V; i++)
printf("%d \t\t\t\t %d\n", i, dist[i]);
}

// Function that implements Dijkstra's single source


// shortest path algorithm for a graph represented using
// adjacency matrix representation
void dijkstra(int graph[V][V], int src)
{
int dist[V]; // The output array. dist[i] will hold the
// shortest
// distance from src to i
DEPT : CSE TITS

bool sptSet[V]; // sptSet[i] will be true if vertex i is


// included in shortest
// path tree or shortest distance from src to i is
// finalized

// Initialize all distances as INFINITE and stpSet[] as


// false
for (int i = 0; i < V; i++)
dist[i] = INT_MAX, sptSet[i] = false;

// Distance of source vertex from itself is always 0


dist[src] = 0;

// Find shortest path for all vertices


for (int count = 0; count < V - 1; count++) {
// Pick the minimum distance vertex from the set of
// vertices not yet processed. u is always equal to
// src in the first iteration.
int u = minDistance(dist, sptSet);

// Mark the picked vertex as processed


sptSet[u] = true;

// Update dist value of the adjacent vertices of the


// picked vertex.
for (int v = 0; v < V; v++)

// Update dist[v] only if is not in sptSet,


// there is an edge from u to v, and total
// weight of path from src to v through u is
// smaller than current value of dist[v]
if (!sptSet[v] && graph[u][v]
&& dist[u] != INT_MAX
&& dist[u] + graph[u][v] < dist[v])
dist[v] = dist[u] + graph[u][v];
}
DEPT : CSE TITS

// print the constructed distance array


printSolution(dist);
}

// 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:

Vertex Distance from Source


0 0
1 4
2 12
DEPT : CSE TITS

3 19
4 21
5 11
6 9
7 8
8 14

8.Implement Job Sequencing with deadlines using Greedy strategy.

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

// A structure to represent a Jobs


typedef struct Jobs {
char id; // Jobs Id
int dead; // Deadline of Jobs
int profit; // Profit if Jobs is over before or on deadline
} Jobs;

// This function is used for sorting all Jobss according to


// profit
int compare(const void* a, const void* b){
Jobs* temp1 = (Jobs*)a;
Jobs* temp2 = (Jobs*)b;
return (temp2->profit - temp1->profit);
}

// Find minimum between two numbers.


int min(int num1, int num2){
return (num1 > num2) ? num2 : num1;
}

int main()
{
Jobs arr[] = {
{ 'a', 2, 100 },
{ 'b', 2, 20 },
{ 'c', 1, 40 },
{ 'd', 3, 35 },
{ 'e', 1, 25 }
};

int n = sizeof(arr) / sizeof(arr[0]);


DEPT : CSE TITS

printf("Following is maximum profit sequence of Jobs: \n");


qsort(arr, n, sizeof(Jobs), compare);
int result[n]; // To store result sequence of Jobs
bool slot[n]; // To keep track of free time slots

// Initialize all slots to be free


for (int i = 0; i < n; i++)
slot[i] = false;

// Iterate through all given Jobs


for (int i = 0; i < n; i++) {

// Find a free slot for this Job


for (int j = min(n, arr[i].dead) - 1; j >= 0; j--) {

// Free slot found


if (slot[j] == false) {
result[j] = i;
slot[j] = true;
break;
}
}
}

// Print the result


for (int i = 0; i < n; i++)
if (slot[i])
printf("%c ", arr[result[i]].id);
return 0;
}

9.Write a program to solve 0/1 Knapsack problem Using Dynamic


Programming.

#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;
}

10. Implement N-Queens Problem Using Backtracking

#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

11.Use Backtracking strategy to solve 0/1 Knapsack problem.

/* A Naive recursive implementation


of 0-1 Knapsack problem */
#include <stdio.h>

// A utility function that returns


// maximum of two integers
int max(int a, int b) { return (a > b) ? a : b; }

// Returns the maximum value that can be


// put in a knapsack of capacity W
int knapSack(int W, int wt[], int val[], int n)
{
// Base Case
if (n == 0 || W == 0)
return 0;

// If weight of the nth item is more than


// Knapsack capacity W, then this item cannot
// be included in the optimal solution
if (wt[n - 1] > W)
return knapSack(W, wt, val, n - 1);

// Return the maximum of two cases:


// (1) nth item included
// (2) not included
else
return max(
val[n - 1]
+ knapSack(W - wt[n - 1], wt, val, n - 1),
knapSack(W, wt, val, n - 1));
}

// 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

12.Implement Travelling Sales Person problem using Branch and Bound


approach.

/*Branch and Bound Algorithm for Travelling Sales Person*/


#include<stdio.h>
#include<conio.h>
int a[10][10], visited[10], n, cost = 0;
void get() {
int i, j;
printf("Enter No. of Cities: ");
scanf("%d", &n);
printf("\nEnter Cost Matrix: \n");
for (i = 0; i < n; i++) {
printf("\n Enter Elements of Row# : %d\n", i + 1);
for (j = 0; j < n; j++)
scanf("%d", &a[i][j]);
visited[i] = 0;
}
printf("\n\nThe cost list is:\n\n");
for (i = 0; i < n; i++) {
printf("\n\n");
for (j = 0; j < n; j++)
printf("\t % d", a[i][j]);
}
}
void mincost(int city) {
int i, ncity;
visited[city] = 1;
printf("%d –>", city + 1);
DEPT : CSE TITS

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

Enter Elements of Row# : 1


Enter Elements of Row# : 2
Enter Elements of Row# : 3
Enter Elements of Row# : 4
Enter Elements of Row# : 5
Enter Elements of Row# : 6

The Path is:

1 –>6 –>3 –>4 –>5 –>2 –>1

Minimum cost:46

You might also like