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

design and analysis of algorithm lab file

1. Program for Recursive Binary & Linear Search. 2. Program for Heap Sort. 3. Program for Merge Sort. 4. Program for Selection Sort. 5. Program for Insertion Sort. 6. Program for Quick Sort. 7. Knapsack Problem using Greedy Solution 8. Perform Travelling Salesman Problem 9. Find Minimum Spanning Tree using Kruskal’s Algorithm 10. Implement N Queen Problem using Backtracking

Uploaded by

prajjwals2050
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

design and analysis of algorithm lab file

1. Program for Recursive Binary & Linear Search. 2. Program for Heap Sort. 3. Program for Merge Sort. 4. Program for Selection Sort. 5. Program for Insertion Sort. 6. Program for Quick Sort. 7. Knapsack Problem using Greedy Solution 8. Perform Travelling Salesman Problem 9. Find Minimum Spanning Tree using Kruskal’s Algorithm 10. Implement N Queen Problem using Backtracking

Uploaded by

prajjwals2050
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

ExpErimEnt no.

objEctivE : program for rEcursivE binary &


LinEar sEarch.

1) program for rEcursivE LinEar sEarch:

#include <iostream>
using namespace std;
int linearSearch(const int arr[], int size, int key) {
if (size == 0)
return -1;
if (arr[size - 1] == key)
return size - 1;
return linearSearch(arr, size - 1, key);
}
int main() {
int arr[] = {1, 3, 5, 7, 9, 11, 13};
int size = sizeof(arr) / sizeof(arr[0]);
int key;
cout << "Enter the key to search: ";
cin >> key;
int result = linearSearch(arr, size, key);
if (result != -1)
cout << "Key found at index: " << result << endl;
else
cout << "Key not found." << endl;
return 0;
}
2) ) program for rEcursivE binary sEarch:

#include <iostream>
using namespace std;

int binarySearch(const int arr[], int left, int right, int key) {
if (left > right)
return -1;
int mid = left + (right - left) / 2;
if (arr[mid] == key)
return mid;
if (arr[mid] > key)
return binarySearch(arr, left, mid - 1, key);
return binarySearch(arr, mid + 1, right, key);
}

int main() {
int arr[] = {1, 3, 5, 7, 9, 11, 13};
int size = sizeof(arr) / sizeof(arr[0]);
int key;

cout << "Enter the key to search: ";


cin >> key;

int result = binarySearch(arr, 0, size - 1, key);


if (result != -1)
cout << "Key found at index: " << result << endl;
else
cout << "Key not found." << endl;

return 0;
}
output :

1.for rEcursivE LinEar sEarch :

2.for rEcursivE binary sEarch :


ExpErimEnt no. 2

objEctivE : program for hEap sort.


program:
#include <iostream>
using namespace std;

void heapify(int arr[], int n, int i) {


int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;

if (left < n && arr[left] > arr[largest])


largest = left;

if (right < n && arr[right] > arr[largest])


largest = right;

if (largest != i) {
swap(arr[i], arr[largest]);
heapify(arr, n, largest);
}
}

void heapSort(int arr[], int n) {


for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);

for (int i = n - 1; i > 0; i--) {


swap(arr[0], arr[i]);
heapify(arr, i, 0);
}
}
int main() {
int arr[] = {4, 10, 3, 5, 1};
int n = sizeof(arr) / sizeof(arr[0]);

heapSort(arr, n);

cout << "Sorted array: ";


for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
return 0;
}
output :

1.for hEap sort:


ExpErimEnt no. 3

objEctivE : program for mErgE sort.


program:
#include <iostream>
using namespace std;

void merge(int arr[], int left, int mid, int right) {


int n1 = mid - left + 1;
int n2 = right - mid;
int L[n1], R[n2];

for (int i = 0; i < n1; i++)


L[i] = arr[left + i];
for (int i = 0; i < n2; i++)
R[i] = arr[mid + 1 + i];
int i = 0, j = 0, k = left;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++; }
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}}
void mergeSort(int arr[], int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2;
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}}
int main() {
int arr[] = {12, 11, 13, 5, 6, 7};
int n = sizeof(arr) / sizeof(arr[0]);
mergeSort(arr, 0, n - 1);
cout << "Sorted array: ";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;

return 0;
}

output :

1.for mErgE sort:


ExpErimEnt no. 4

objEctivE : program for insErtion sort.


program:
#include <iostream>
using namespace std;

void merge(int arr[], int left, int mid, int right) {


int n1 = mid - left + 1;
int n2 = right - mid;
int L[n1], R[n2];

for (int i = 0; i < n1; i++)


L[i] = arr[left + i];
for (int i = 0; i < n2; i++)
R[i] = arr[mid + 1 + i];
int i = 0, j = 0, k = left;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++; }
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}}
void mergeSort(int arr[], int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2;
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}}
int main() {
int arr[] = {12, 11, 13, 5, 6, 7};
int n = sizeof(arr) / sizeof(arr[0]);
mergeSort(arr, 0, n - 1);
cout << "Sorted array: ";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;

return 0;
}

output :

1.for insErtion sort:


ExpErimEnt no. 5

objEctivE : KnapsacK probLEm using grEEdy


soLution.
program:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Item {
int value;
int weight;
};
double knapsackGreedy(vector<Item>& items, int capacity) {
auto compare = [](Item a, Item b) {
return (double)a.value / a.weight > (double)b.value / b.weight;
};
sort(items.begin(), items.end(), compare);
double totalValue = 0.0;
for (auto& item : items) {
if (capacity >= item.weight) {
capacity -= item.weight;
totalValue += item.value;
} else {
totalValue += item.value * ((double)capacity / item.weight);
break;
}
}
return totalValue;
}

int main() {
int n, capacity;
cout << "Enter number of items and knapsack capacity: ";
cin >> n >> capacity;

vector<Item> items(n);
cout << "Enter value and weight for each item:" << endl;
for (int i = 0; i < n; ++i) {
cout << "Item " << i+1 << ": ";
cin >> items[i].value >> items[i].weight;
}
cout << "Maximum value achievable: " << knapsackGreedy(items, capacity) << endl;
return 0;
}
output :

1. KnapsacK probLEm using grEEdy soLution:


ExpErimEnt no. 6

objEctivE : find minimum spanning trEE using


KrusKaL’s aLgorithm
program
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

struct Edge {
int src, dest, weight;
};
int findParent(int node, vector<int>& parent) {
if (parent[node] == node)
return node;
return parent[node] = findParent(parent[node], parent); // Path compression
}
void unionSets(int u, int v, vector<int>& parent, vector<int>& rank) {
int rootU = findParent(u, parent);
int rootV = findParent(v, parent);
if (rootU != rootV) {
if (rank[rootU] > rank[rootV])
parent[rootV] = rootU;
else if (rank[rootU] < rank[rootV])
parent[rootU] = rootV;
else {
parent[rootV] = rootU;
rank[rootU]++;
}
}
}
vector<Edge> kruskalMST(int V, vector<Edge>& edges) {
// Sort edges by weight
sort(edges.begin(), edges.end(), [](Edge a, Edge b) {
return a.weight < b.weight;
});
vector<int> parent(V);
vector<int> rank(V, 0);
for (int i = 0; i < V; ++i)
parent[i] = i;

vector<Edge> mst; // Store edges of MST


for (auto& edge : edges) {
if (findParent(edge.src, parent) != findParent(edge.dest, parent)) {
mst.push_back(edge);
unionSets(edge.src, edge.dest, parent, rank);
}}
return mst;
}

int main() {
int V, E;
cout << "Enter the number of vertices and edges: ";
cin >> V >> E;
vector<Edge> edges(E);
cout << "Enter each edge as source, destination, and weight:\n";
for (int i = 0; i < E; ++i) {
cout << "Edge " << i + 1 << ": ";
cin >> edges[i].src >> edges[i].dest >> edges[i].weight;
}
vector<Edge> mst = kruskalMST(V, edges);
cout << "\nEdges in the Minimum Spanning Tree:\n";
int mstWeight = 0;
for (auto& edge : mst) {
cout << "Source: " << edge.src << ", Destination: " << edge.dest
<< ", Weight: " << edge.weight << endl;
mstWeight += edge.weight;
}
cout << "Total weight of MST: " << mstWeight << endl;

return 0;
output :

1. find minimum spanning trEE using KrusKaL’s


aLgorithm:
ExpErimEnt no. 7

objEctivE : impLEmEnt , thE 0/1 KnapsacK


probLEm using
(a) dynamic programming mEthod
program
#include <iostream>
#include <vector>
using namespace std;
int knapsackDP(int W, const vector<int>& weights, const vector<int>& values, int n) {
// Create a DP table with dimensions (n+1) x (W+1)
vector<vector<int>> dp(n + 1, vector<int>(W + 1, 0));
for (int i = 1; i <= n; ++i) {
for (int w = 1; w <= W; ++w) {
if (weights[i - 1] <= w) {
dp[i][w] = max(dp[i - 1][w], values[i - 1] + dp[i - 1][w - weights[i - 1]]);
} else {
dp[i][w] = dp[i - 1][w];
}
}
}

return dp[n][W]; // Return the maximum value that can be obtained


}

int main() {
int n, W;
cout << "Enter the number of items and knapsack capacity: ";
cin >> n >> W;

vector<int> values(n), weights(n);


cout << "Enter the value and weight for each item:\n";
for (int i = 0; i < n; ++i) {
cout << "Item " << i + 1 << ": ";
cin >> values[i] >> weights[i];
}
cout << "Maximum value in the knapsack: " << knapsackDP(W, weights, values, n) << endl;

return 0;
}

output :

thE 0/1 KnapsacK probLEm using


(a) dynamic programming mEthod
ExpErimEnt no. 8

objEctivE : from a givEn vErtEx in a wEightEd


connEctEd graph, find shortEst paths to othEr
vErticEs using dijKstra's aLgorithm.
program:
#include <iostream>
#include <vector>
#include <queue>
#include <climits>
using namespace std;
struct Edge {
int vertex;
int weight;
};
vector<int> dijkstra(int src, const vector<vector<Edge>>& graph) {
int V = graph.size();
vector<int> dist(V, INT_MAX);
dist[src] = 0;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> pq;
pq.push({0, src});

while (!pq.empty()) {
int currDist = pq.top().first;
int currVertex = pq.top().second;
pq.pop();

if (currDist > dist[currVertex]) continue; // Ignore outdated distances


for (const auto& edge : graph[currVertex]) {
int nextVertex = edge.vertex;
int weight = edge.weight;
if (dist[currVertex] + weight < dist[nextVertex]) {
dist[nextVertex] = dist[currVertex] + weight;
return dist;
}

int main() {
int V, E;
cout << "Enter the number of vertices and edges: ";
cin >> V >> E;

vector<vector<Edge>> graph(V);

cout << "Enter the edges (source, destination, weight):\n";


for (int i = 0; i < E; ++i) {
int u, v, w;
cin >> u >> v >> w;
graph[u].push_back({v, w});
graph[v].push_back({u, w}); // For undirected graphs, add both directions
}

int src;
cout << "Enter the source vertex: ";
cin >> src;
vector<int> distances = dijkstra(src, graph);
cout << "\nShortest distances from vertex " << src << ":\n";
for (int i = 0; i < V; ++i) {
cout << "Vertex " << i << ": ";
if (distances[i] == INT_MAX)
cout << "Not reachable";
else
cout << distances[i];
cout << endl;
}

return 0;
}
output :

1. from agivEn vErtEx in a wEightEd


connEctEd graph, find shortEst paths to
othEr vErticEs using dijKstra's aLgorithm:
ExpErimEnt no. 9

objEctivE : find minimum spanning trEE using


KrusKaL’s aLgorithm
program:
#include <iostream>
#include <vector>
#include <queue>
#include <climits>

using namespace std;

int primMST(int V, vector<vector<pair<int, int>>>& graph) {


priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> pq;
vector<bool> inMST(V, false);
vector<int> key(V, INT_MAX);
vector<int> parent(V, -1);
int totalCost = 0;

key[0] = 0;
pq.push({0, 0});

while (!pq.empty()) {
int currVertex = pq.top().second;
pq.pop();

if (inMST[currVertex])
continue;

inMST[currVertex] = true;
totalCost += key[currVertex];

for (const auto& edge : graph[currVertex]) {


int nextVertex = edge.first;
int weight = edge.second;

if (!inMST[nextVertex] && weight < key[nextVertex]) {


key[nextVertex] = weight;
parent[nextVertex] = currVertex;
pq.push({key[nextVertex], nextVertex});
}
}
}

cout << "\nEdges in the Minimum Spanning Tree:\n";


for (int i = 1; i < V; ++i) {
if (parent[i] != -1) {
cout << "Edge: " << parent[i] << " - " << i << " | Weight: " << key[i] << endl;
}
}

return totalCost;
}

int main() {
int V, E;
cout << "Enter the number of vertices and edges: ";
cin >> V >> E;

vector<vector<pair<int, int>>> graph(V);

cout << "Enter each edge as source, destination, and weight:\n";


for (int i = 0; i < E; ++i) {
int u, v, w;
cin >> u >> v >> w;
graph[u].push_back({v, w});
graph[v].push_back({u, w});
}

int totalCost = primMST(V, graph);


cout << "\nTotal cost of the Minimum Spanning Tree: " << totalCost << endl;
output :

1).prim's aLgorithm to find thE minimum cost


spanning trEE (mst)
ExpErimEnt no. 10

objEctivE : writE programs to (a) impLEmEnt


aLL-pairs shortEst paths probLEm using fLoyd's
aLgorithm.
program:
#include <iostream>
#include <vector>
#include <climits>

using namespace std;

void floydWarshall(vector<vector<int>>& graph, int V) {


vector<vector<int>> dist = graph;

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


for (int i = 0; i < V; ++i) {
for (int j = 0; j < V; ++j) {
if (dist[i][k] != INT_MAX && dist[k][j] != INT_MAX && dist[i][k] + dist[k][j] <
dist[i][j]) {
dist[i][j] = dist[i][k] + dist[k][j];
}}}}
cout << "\nAll-Pairs Shortest Paths:\n";
for (int i = 0; i < V; ++i) {
for (int j = 0; j < V; ++j) {
if (dist[i][j] == INT_MAX)
cout << "INF ";
else
cout << dist[i][j] << " ";
}
cout << endl;
}}
int main() {
int V;
cout << "Enter the number of vertices: ";
cin >> V;

vector<vector<int>> graph(V, vector<int>(V, INT_MAX));


cout << "Enter the adjacency matrix (use a large number like 10000 for no direct path):\n";
for (int i = 0; i < V; ++i) {
for (int j = 0; j < V; ++j) {
cin >> graph[i][j];
if (i == j) graph[i][j] = 0;
}
}
floydWarshall(graph, V);
return 0;
}

output :

1) aLL-pairs shortEst paths probLEm


using fLoyd’s aLgorithm.

You might also like