AADS_pracfile
AADS_pracfile
AADS_pracfile
Name: Jaspreet singh | Course: B.Sc (Hons) Computer Science | Roll no: 2022CSC1048
Q1. Write a program to sort the elements of an array using Randomized Quick
Sort (the program should report the number of comparisons).
Click here to run the code
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int comparisons = 0;
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
int randomizedPartition(int arr[], int low, int high) {
int pivotIndex = low + rand() % (high - low + 1);
swap(arr[pivotIndex], arr[high]);
int pivot = arr[high];
int i = low - 1;
for (int j = low; j < high; j++) {
comparisons++;
if (arr[j] < pivot) {
i++;
swap(arr[i], arr[j]);
}
}
swap(arr[i + 1], arr[high]);
return i + 1;
}
void randomizedQuickSort(int arr[], int low, int high) {
if (low < high) {
int pi = randomizedPartition(arr, low, high);
randomizedQuickSort(arr, low, pi - 1);
randomizedQuickSort(arr, pi + 1, high);
}
}
void sortArray(int arr[], int size) {
srand(time(0));
comparisons = 0;
randomizedQuickSort(arr, 0, size - 1);
}
int main() {
int arr[] = {10, 7, 8, 9, 1, 5};
int size = sizeof(arr) / sizeof(arr[0]);
cout << "Original array: ";
printArray(arr, size);
sortArray(arr, size);
cout << "Sorted array: ";
printArray(arr, size);
cout << "Total comparisons: " << comparisons << endl;
return 0;
}
int kruskal() {
sort(edges.begin(), edges.end());
DisjointSet ds(V);
int mstWeight = 0;
for (const Edge& edge : edges) {
int u = edge.u, v = edge.v;
if (ds.find(u) != ds.find(v)) {
ds.unionSets(u, v);
mstWeight += edge.weight;
}
}
return mstWeight;
}
};
int main() {
Graph g(4);
g.addEdge(0, 1, 10);
g.addEdge(0, 2, 6);
g.addEdge(0, 3, 5);
g.addEdge(1, 3, 15);
g.addEdge(2, 3, 4);
cout << "Minimum Spanning Tree Weight: " << g.kruskal() << endl;
return 0;
}
Q12 Write a program to implement Kruskal’s algorithm using Union Find Data
Structure.
Click here to run the code
#include <iostream>
#include <vector>
#include <algorithm>
struct Edge {
int u, v, weight;
};
class UnionFind {
public:
UnionFind(int size) {
parent.resize(size);
rank.resize(size, 0);
for (int i = 0; i < size; ++i) {
parent[i] = i;
}
}
int find(int u) {
if (parent[u] != u) {
parent[u] = find(parent[u]);
}
return parent[u];
}
if (root_u != root_v) {
private:
vector<int> parent;
vector<int> rank;
};
class Graph {
public:
Graph(int vertices) : V(vertices) {}
void kruskal() {
sort(edges.begin(), edges.end(), [](const Edge &a, const Edge &b) {
return a.weight < b.weight;
});
UnionFind uf(V);
vector<Edge> mst;
int totalWeight = 0;
private:
int V;
vector<Edge> edges;
};
int main() {
Graph g(4);
g.addEdge(0, 1, 10);
g.addEdge(0, 2, 6);
g.addEdge(0, 3, 5);
g.addEdge(1, 3, 15);
g.addEdge(2, 3, 4);
g.kruskal();
return 0;
}