0% found this document useful (0 votes)
11 views34 pages

Shivam final daa lab file.pdf

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

Shivam final daa lab file.pdf

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

AMITY UNIVERSITY MADHYA

PRADESH, GWALIOR

PRACTICAL FILE OF

DESIGN AND ANALYSIS OF ALGORITHMS


[CSE 323]

SUBMITTED TO: SUBMITTED BY:


Mrs. APOORVA SHARMA Shivam Rathore

ASST. PROF. ASET A60205222086


B.TECH. (CSE)
SEC -B(2)

SEMESTER – 5th

DEPARTMENT OF COMPUTER SCIENCE ENGINEERING


AMITY SCHOOL OF ENGINEERING AND TECHNOLOGY
INDEX
S.NO. PROGRAM PAGE DATE SIGN REMARK
NO.
1. Write a program to implement Quick
sort algorithm for sorting a list of 1–2 21-08-24
integers in ascending order.
2. Write a program to implement Merge
sort algorithm for sorting a list of 3– 5 28-08-24
integers in ascending order.
3. Write a program to implement the 6–7 06-09-24
DFS algorithm for a graph.
4. Write a program to implement the 8 – 10 13-09-24
BFS algorithm for a graph.
5. Write a program to implement 11 – 13 20-09-24
the backtracking algorithm for
N queens problem.
6. Write a program to implement the 14 – 15 27-09-24
backtracking algorithm for the sum of
subsets problem.
7. Write a program to implement the 16 – 18 04-10-24
the backtracking algorithm for
Hamiltonian Circuits problem.
8. Write a program to implement greedy 19 – 20 19-10-24
algorithm for job sequencing with
deadlines.
9. Write a program to implement 21 – 23 25-10-24
Dijkstra’s algorithm for the Single
source shortest path problem.
10. Write a program that implements 24 – 26 08-11-24
prim’s algorithm to generate
minimum cost spanning tree.
11. Write a program that implements 27 – 30 22-11-24
Kruskal’s algorithm to generate
minimum cost spanning tree.
12. Write a program to implement 31 – 32 29-11-24
Dynamic Programming algorithm for
the 0/1 Knapsack.
LAB - (1)

Write a program to implement Quick sort algorithm for sorting a list of


integers in ascending order

#include <iostream>
using namespace std;

void swap(int& a, int& b) {


int temp = a;
a = b;
b = temp;
}
int partition(int arr[], int low, int high) {
int pivot = arr[high];
int i = low - 1;

for (int j = low; j < high; j++) {


if (arr[j] <= pivot) {
i++;
swap(arr[i], arr[j]);
}
}
swap(arr[i + 1], arr[high]);
return i + 1;
}
void quickSort(int arr[], int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}

SHIVAM RATHORE 1 A60205222086


void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}

int main() {
int arr[] = {10, 70, 80, 90, 11, 59};
int n = sizeof(arr) / sizeof(arr[0]);

cout<<"Shivam Rathore"<<endl;

cout << "Unsorted array: ";


printArray(arr, n);

quickSort(arr, 0, n - 1);

cout << "Sorted array: ";


printArray(arr, n);

return 0;
}

SHIVAM RATHORE 2 A60205222086


LAB - (2)

Write a program to implement Merge sort algorithm for sorting a list of


integers in ascending order

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

SHIVAM RATHORE 3 A60205222086


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);
}
}
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}
int main() {
int arr[] = {100, 30, 50, 45, 90, 200};
int arr_size = sizeof(arr) / sizeof(arr[0]);
cout<<"Shivam Rathore"<<endl;
cout << "Given array: ";
printArray(arr, arr_size);

SHIVAM RATHORE 4 A60205222086


mergeSort(arr, 0, arr_size - 1);
cout << "Sorted array: ";
printArray(arr, arr_size);
return 0;
}

SHIVAM RATHORE 5 A60205222086


LAB - (3)

Write a program to implement DFS algorithm for a graph.

#include <iostream>
#include <vector>
using namespace std;

void DFS(int node, vector<int> adj[], bool visited[]) {


visited[node] = true;
cout << node << " ";
for (int adjacent : adj[node]) {
if (!visited[adjacent]) {
DFS(adjacent, adj, visited);
}
}
}
int main() {
int V = 4;
vector<int> adj[V];
adj[0].push_back(1);
adj[0].push_back(2);
adj[1].push_back(2);
adj[2].push_back(3);
bool visited[V] = {false};
cout<<”Shivam Rathore”<<endl;
cout << "DFS traversal starting from vertex 0:" << endl;
DFS(0, adj, visited);
return 0; }

SHIVAM RATHORE 6 A60205222086


SHIVAM RATHORE 7 A60205222086
LAB - (4)

Write a program to implement BFS algorithm for a graph.


#include <iostream>
using namespace std;

class Queue {
public:
int size;
int f;
int r;
int* arr;

Queue(int s) {
size = s;
f = r = 0;
arr = new int[size];
}

bool isEmpty() {
return r == f;
}

bool isFull() {
return r == size - 1;
}

void enqueue(int val) {


if (isFull()) {
cout << "This queue is full" << endl;
}

SHIVAM RATHORE 8 A60205222086


else {
r++;
arr[r] = val;
}
}
int dequeue() {
int a = -1;
if (isEmpty()) {
cout << "This queue is empty" << endl;
} else {
f++;
a = arr[f];
}
return a;
}
~Queue() {
delete[] arr;
}
};
int main() {
Queue q(400);
q.enqueue(10);
q.enqueue(20);
cout << "Dequeued: " << q.dequeue() << endl;
cout << "Dequeued: " << q.dequeue() << endl;
cout << "Dequeued: " << q.dequeue() << endl;
return 0;
}

SHIVAM RATHORE 9 A60205222086


SHIVAM RATHORE 10 A60205222086
LAB - (5)

Write a programs to implement backtracking algorithm for the N-queens


problem.

#include <bits/stdc++.h>
using namespace std;

void printSolution(vector<vector<int>>& board) {


int n = board.size();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
if(board[i][j])
cout << "Q ";
else
cout << ". ";
cout << "\n";
}
}
bool isSafe(vector<vector<int>>& board,
int row, int col) {
int n = board.size();
int i, j;

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


if (board[row][i])
return false;

for (i = row, j = col; i >= 0 &&


j >= 0; i--, j--)
if (board[i][j])
return false;

SHIVAM RATHORE 11 A60205222086


for (i = row, j = col; j >= 0 &&
i < n; i++, j--)
if (board[i][j])
return false;

return true;
}

bool solveNQUtil(vector<vector<int>>& board, int col) {


int n = board.size();

if (col >= n)

return true;

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


if (isSafe(board, i, col)) {
board[i][col] = 1;
if (solveNQUtil(board, col + 1))
return true;
board[i][col] = 0;
}
}
return false;
}

bool solveNQ(int n) {
vector<vector<int>> board(n, vector<int>(n, 0));
if (solveNQUtil(board, 0) == false) {
cout << "Solution does not exist";
return false;
}

SHIVAM RATHORE 12 A60205222086


printSolution(board);
return true;
}

int main() {
int n = 4;
solveNQ(n);
return 0;
}

SHIVAM RATHORE 13 A60205222086


LAB - (6)

Write a program to implement the backtracking algorithm for the sum of


subsets problem.

#include <bits/stdc++.h>
using namespace std;
bool flag = 0;

void PrintSubsetSum(int i, int n, int set[], int targetSum, vector<int>& subset)


{
if (targetSum == 0) {
flag = 1;
cout << "[ ";
for (int i = 0; i < subset.size(); i++) {
cout << subset[i] << " ";
}
cout << "]";
return;
}
if (i == n) {
return;
}
PrintSubsetSum(i + 1, n, set, targetSum, subset);

if (set[i] <= targetSum) {


subset.push_back(set[i]);
PrintSubsetSum(i + 1, n, set, targetSum - set[i], subset);
subset.pop_back();
}
}

SHIVAM RATHORE 14 A60205222086


int main()
{
int n, targetSum;

cout << "Enter the number of elements in the set: ";


cin >> n;

int set[n];
cout << "Enter the elements of the set: ";
for (int i = 0; i < n; i++) {
cin >> set[i];
}

cout << "Enter the target sum: ";


cin >> targetSum;

vector<int> subset;
cout << "Subsets with sum equal to " << targetSum << ":" << endl;
PrintSubsetSum(0, n, set, targetSum, subset);
if (!flag) {
cout << "There is no such subset";
}

return 0;
}

SHIVAM RATHORE 15 A60205222086


LAB - (7)

Write a program to implement the backtracking algorithm for the


Hamiltonian Circuits problem
#include <iostream>
#include <vector>
using namespace std;

#define V 5

bool isSafe(int v, const vector<vector<int>>& graph, const vector<int>& path, int pos) {

if (graph[path[pos - 1]][v] == 0)
return false;

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


if (path[i] == v)
return false;
}
return true;
}

bool hamCycleUtil(const vector<vector<int>>& graph, vector<int>& path, int pos) {

if (pos == V) {

if (graph[path[pos - 1]][path[0]] == 1)
return true;
return false;
}

SHIVAM RATHORE 16 A60205222086


for (int v = 1; v < V; v++) {

if (isSafe(v, graph, path, pos)) {


path[pos] = v;

if (hamCycleUtil(graph, path, pos + 1))


return true;

path[pos] = -1;
}
}
return false;
}
bool hamCycle(const vector<vector<int>>& graph) {
vector<int> path(V, -1);
path[0] = 0;

if (!hamCycleUtil(graph, path, 1)) {


cout << "Solution does not exist" << endl;
return false;
}
cout << "Hamiltonian Cycle exists: ";
for (int i = 0; i < V; i++)
cout << path[i] << " ";
cout << path[0] << endl;
return true;
}

SHIVAM RATHORE 17 A60205222086


int main() {
vector<vector<int>> graph = {
{0, 1, 0, 1, 0},
{1, 0, 1, 1, 1},
{0, 1, 0, 0, 1},
{1, 1, 0, 0, 1},
{0, 1, 1, 1, 0}
};
cout<<"Shivam Rathore"<<endl;

hamCycle(graph);
return 0;
}

SHIVAM RATHORE 18 A60205222086


LAB - (8)

Write a program to implement greedy algorithm for job sequencing with


deadlines.

#include <algorithm>
#include <iostream>
using namespace std;
struct Job {
char id;
int dead;
int profit;
};
bool comparison(Job a, Job b) {
return (a.profit > b.profit);
}

void printJobScheduling(Job arr[], int n) {


sort(arr, arr + n, comparison);

int result[n];
bool slot[n];

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


slot[i] = false;
for (int i = 0; i < n; i++) {
for (int j = min(n, arr[i].dead) - 1; j >= 0; j--) {
if (slot[j] == false) {
result[j] = i;
slot[j] = true;
break;
}
}
}
SHIVAM RATHORE 19 A60205222086
for (int i = 0; i < n; i++)
if (slot[i])
cout << arr[result[i]].id << " ";
}

int main() {

int n;
cout << "Enter the number of jobs: ";
cin >> n;
cout<<"Shivam Rathore"<<endl;
Job arr[n];
for (int i = 0; i < n; i++) {
cout << "Enter job id, deadline, and profit for job " << i + 1 << ": ";
cin >> arr[i].id >> arr[i].dead >> arr[i].profit;
}

cout << "Following is maximum profit sequence of jobs:\n";


printJobScheduling(arr, n);

return 0;
}

SHIVAM RATHORE 20 A60205222086


LAB - (9)

Write a program to implement Dijkstra’s algorithm for the Single source


shortest path problem

#include <iostream>
#include <vector>
#include <queue>
#include <climits>

using namespace std;


typedef pair<int, int> pii;

vector<int> dijkstra(int V, vector<vector<pii>>& adj, int start) {


vector<int> dist(V, INT_MAX);
dist[start] = 0;

priority_queue<pii, vector<pii>, greater<pii>> pq;


pq.push({0, start});

while (!pq.empty()) {
int u = pq.top().second;
int d = pq.top().first;
pq.pop();

if (d > dist[u]) {
continue;
}

for (auto& neighbor : adj[u]) {


int v = neighbor.first;
int weight = neighbor.second;

SHIVAM RATHORE 21 A60205222086


if (dist[u] + weight < dist[v]) {
dist[v] = dist[u] + weight;
pq.push({dist[v], v});
}
}
}

return dist;
}

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

cout << "Enter the number of edges: ";


cin >> E;

vector<vector<pii>> adj(V);
cout << "Enter the edges (format: u v weight), where u and v are vertex indices (0
to " << V-1 << "):" << endl;
for (int i = 0; i < E; ++i) {
int u, v, weight;
cin >> u >> v >> weight;
adj[u].push_back({v, weight});
adj[v].push_back({u, weight});
}
int start;
cout << "Enter the starting node: ";
cin >> start;

SHIVAM RATHORE 22 A60205222086


vector<int> shortestPaths = dijkstra(V, adj, start);

cout << "\nShortest distances from node " << start << ":\n";
for (int i = 0; i < V; ++i) {
if (shortestPaths[i] == INT_MAX) {
cout << "Distance to " << i << " is INF\n";
} else {
cout << "Distance to " << i << " is " << shortestPaths[i] << "\n";
}
}

return 0;
}

SHIVAM RATHORE 23 A60205222086


LAB - (10)

Write a program that implements Prim’s algorithm to generate minimum


cost spanning tree.

#include <iostream>
#include <vector>
#include <climits>
#include <queue>
using namespace std;

typedef pair<int, int> pii;

void primMST(int V, vector<vector<pii>>& adj) {

vector<int> key(V, INT_MAX);


vector<int> parent(V, -1);
vector<bool> inMST(V, false);

key[0] = 0;

priority_queue<pii, vector<pii>, greater<pii>> pq;


pq.push({0, 0});

while (!pq.empty()) {

int u = pq.top().second;
pq.pop();
inMST[u] = true;

for (auto& neighbor : adj[u]) {


int v = neighbor.first;
int weight = neighbor.second;

SHIVAM RATHORE 24 A60205222086


\tWeight\n";
for (int i = 1; i < V; ++i) {
cout << parent[i] << " - " << i << "\t" << key[i] << endl;
}
}

int main() {
int V, E;
cout<<"Shivam Rathore"<<endl;

cout << "Enter the number of vertices: ";


cin >> V;

cout << "Enter the number of edges: ";


cin >> E;

vector<vector<pii>> adj(V);

cout << "Enter the edges (u v weight), where u and v are vertex indices (0 to " << V-1
<< "):\n";
for (int i = 0; i < E; ++i) {
int u, v, weight;
cin >> u >> v >> weight;
adj[u].push_back({v, weight});
adj[v].push_back({u, weight});
}

primMST(V, adj);

return 0;
}

SHIVAM RATHORE 25 A60205222086


SHIVAM RATHORE 26 A60205222086
LAB - (11)

Write a program that implements Kruskal’s algorithm to generate minimum


cost spanning tree
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

struct Edge {
int u, v, weight;
bool operator<(const Edge& e) {
return weight < e.weight;
}
};
class DisjointSet {
public:
vector<int> parent, rank;

DisjointSet(int n) {
parent.resize(n);
rank.resize(n, 0);
for (int i = 0; i < n; i++) {
parent[i] = i;
}
}
int find(int x) {
if (parent[x] != x) {
parent[x] = find(parent[x]);
}
return parent[x];
}

SHIVAM RATHORE 27 A60205222086


void unionSets(int x, int y) {
int rootX = find(x);
int rootY = find(y);

if (rootX != rootY) {
if (rank[rootX] > rank[rootY]) {
parent[rootY] = rootX;
} else if (rank[rootX] < rank[rootY]) {
parent[rootX] = rootY;
} else {
parent[rootY] = rootX;
rank[rootX]++;
}
}
}
};

vector<Edge> kruskal(int n, vector<Edge>& edges) {


vector<Edge> mst;
DisjointSet ds(n);

sort(edges.begin(), edges.end());

for (const auto& edge : edges) {


int u = edge.u;
int v = edge.v;

if (ds.find(u) != ds.find(v)) {
mst.push_back(edge);
ds.unionSets(u, v);
}
}

return mst;
}
SHIVAM RATHORE 28 A60205222086
int main() {
cout<<"Shivam Rathore"<<endl;
int n, m;
cout << "Enter number of vertices: ";
cin >> n;
cout << "Enter number of edges: ";
cin >> m;

vector<Edge> edges(m);

cout << "Enter the edges (u, v, weight) :\n";


for (int i = 0; i < m; i++) {
cout << "Edge " << i + 1 << " (u, v, weight): ";
cin >> edges[i].u >> edges[i].v >> edges[i].weight;
}

vector<Edge> mst = kruskal(n, edges);

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


int totalWeight = 0;
for (const auto& edge : mst) {
cout << edge.u << " - " << edge.v << " : " << edge.weight << endl;
totalWeight += edge.weight;
}
cout << "Total weight of MST: " << totalWeight << endl;

return 0;
}

SHIVAM RATHORE 29 A60205222086


SHIVAM RATHORE 30 A60205222086
LAB - (12)

Write a program to implement Dynamic Programming algorithm for the 0/1


Knapsack

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int knapsack(int W, vector<int>& weights, vector<int>& values, int n) {

vector<vector<int>> dp(n + 1, vector<int>(W + 1, 0));

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


for (int w = 0; w <= W; w++) {
if (weights[i - 1] <= w) {
dp[i][w] = max(dp[i - 1][w], dp[i - 1][w - weights[i - 1]] + values[i - 1]);
} else {
dp[i][w] = dp[i - 1][w];
}
}
}

return dp[n][W];
}
int main() {
cout<<"Shivam Rathore"<<endl;
int n, W;

cout << "Enter the number of items: ";


cin >> n;
cout << "Enter the capacity of the knapsack: ";
cin >> W;

SHIVAM RATHORE 31 A60205222086


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

cout << "Enter the weights of the items: ";


for (int i = 0; i < n; i++) {
cin >> weights[i];
}

cout << "Enter the values of the items: ";


for (int i = 0; i < n; i++) {
cin >> values[i];
}

int maxValue = knapsack(W, weights, values, n);

cout << "The maximum value that can be obtained: " << maxValue << endl;

return 0;
}

SHIVAM RATHORE 32 A60205222086

You might also like