0% found this document useful (0 votes)
3 views28 pages

ADS(16125)

The document contains multiple programming questions and solutions related to advanced data structures, including implementations of Randomized Quick Sort, Randomized Select, Kruskal’s Algorithm, Bellman-Ford Algorithm, B-Tree, and Binary Search Tree. Each section provides code snippets in C++ along with explanations of the algorithms and their functionalities. The document serves as a comprehensive guide for understanding and implementing these data structures and algorithms.

Uploaded by

Sushant
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)
3 views28 pages

ADS(16125)

The document contains multiple programming questions and solutions related to advanced data structures, including implementations of Randomized Quick Sort, Randomized Select, Kruskal’s Algorithm, Bellman-Ford Algorithm, B-Tree, and Binary Search Tree. Each section provides code snippets in C++ along with explanations of the algorithms and their functionalities. The document serves as a comprehensive guide for understanding and implementing these data structures and algorithms.

Uploaded by

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

Advanced Data Structure

Name: Sumit Kumar


Roll No.: 16125
Course: B.Sc. (H) Computer Science
Section: B

Que 1: Randomized Quick Sort

#include <iostream>

#include <cstdlib> // For rand() and srand()

using namespace std; // Use the standard namespace

// Function to swap two elements

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

int temp = a;

a = b;

b = temp;

// Function to generate a pseudo-random number using cstdlib

int customRandom(int min, int max) {

return min + rand() % (max - min + 1);

// RANDOMIZED-PARTITION function

int randomizedPartition(int arr[], int p, int r, int &comparisonCount) {

int randomPivotIndex = p + customRandom(0, r - p);

swap(arr[randomPivotIndex], arr[r]); // Move random pivot to end


int pivot = arr[r];

int i = p - 1;

for (int j = p; j < r; j++) {

comparisonCount++;

if (arr[j] <= pivot) {

i++;

swap(arr[i], arr[j]);

swap(arr[i + 1], arr[r]);

return i + 1;

// RANDOMIZED-QUICKSORT function

void randomizedQuickSort(int arr[], int p, int r, int &comparisonCount) {

if (p < r) {

int q = randomizedPartition(arr, p, r, comparisonCount);

randomizedQuickSort(arr, p, q - 1, comparisonCount);

randomizedQuickSort(arr, q + 1, r, comparisonCount);

int main() {

srand(time(0)); // Seed for random number generation

int n;

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


cin >> n;

int arr[n];

cout << "Enter the elements of the array: ";

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

cin >> arr[i];

int comparisonCount = 0;

randomizedQuickSort(arr, 0, n - 1, comparisonCount);

cout << "Sorted array: ";

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

cout << arr[i] << " ";

cout << endl;

cout << "Number of comparisons: " << comparisonCount << endl;

return 0;

Que 2: Randomized Select

#include <iostream>

#include <cstdlib>

using namespace std; // Use the standard namespace

// Function to swap two elements


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

int temp = a;

a = b;

b = temp;

// RANDOMIZED-PARTITION function

int randomizedPartition(int arr[], int p, int r) {

int i = p + rand() % (r - p + 1); // Randomly select a pivot index

swap(arr[p], arr[i]); // Swap pivot with the first element

return partition(arr, p, r); // Call the partition function

// PARTITION function

int partition(int arr[], int p, int r) {

int pivot = arr[p];

int i = p;

for (int j = p + 1; j <= r; j++) {

if (arr[j] <= pivot) {

i++;

swap(arr[i], arr[j]);

swap(arr[p], arr[i]);

return i;

// RANDOMIZED-SELECT function

int randomizedSelect(int arr[], int p, int r, int i) {


if (p == r) {

return arr[p];

int q = randomizedPartition(arr, p, r);

int k = q - p + 1;

if (i == k) { // The pivot value is the ith smallest element

return arr[q];

} else if (i < k) {

return randomizedSelect(arr, p, q, i); // Search in the left part

} else {

return randomizedSelect(arr, q + 1, r, i - k); // Search in the right part

int main() {

int n, i;

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

cin >> n;

int arr[n];

cout << "Enter the elements of the array: ";

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

cin >> arr[j];

cout << "Enter the value of i (to find the ith smallest element): ";

cin >> i;
if (i < 1 || i > n) {

cout << "Invalid value of i. It must be between 1 and " << n << "." << endl;

return 1;

int ithSmallest = randomizedSelect(arr, 0, n - 1, i);

cout << "The " << i << "th smallest element is: " << ithSmallest << endl;

return 0;

Que 3: Kruskal’s Algorithm

#include <iostream>

#include <vector>

#include <algorithm>

#include <queue>

using namespace std;

class Edge {

public:

int src, dest, weight;

};

class Graph {

public:

int V, E;
vector<Edge> edges;

Graph(int V, int E) {

this->V = V;

this->E = E;

void addEdge(int src, int dest, int weight) {

Edge edge = {src, dest, weight};

edges.push_back(edge);

class DisjointSets {

public:

vector<int> parent, rank;

DisjointSets(int n) {

parent.resize(n);

rank.resize(n, 0);

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

parent[i] = i;

int find(int u) {

if (u != parent[u])

parent[u] = find(parent[u]);

return parent[u];

}
void unionSets(int u, int v) {

int rootU = find(u);

int rootV = find(v);

if (rank[rootU] < rank[rootV])

parent[rootU] = rootV;

else if (rank[rootU] > rank[rootV])

parent[rootV] = rootU;

else {

parent[rootV] = rootU;

rank[rootU]++;

};

void kruskalMST() {

priority_queue<Edge, vector<Edge>, function<bool(Edge, Edge)>> Q(

[](Edge a, Edge b) {

return a.weight > b.weight;

});

for (Edge e : edges) {

Q.push(e);

DisjointSets forest(V);

vector<Edge> result;

while (result.size() < V - 1 && !Q.empty()) {


Edge e = Q.top();

Q.pop();

int u = forest.find(e.src);

int v = forest.find(e.dest);

if (u != v) {

result.push_back(e);

forest.unionSets(u, v);

cout << "Edges in the Minimum Spanning Tree:" << endl;

for (auto edge : result) {

cout << edge.src << " -- " << edge.dest << " == " << edge.weight << endl;

};

int main() {

int V = 4; // Number of vertices

int E = 5; // Number of edges

Graph graph(V, E);

graph.addEdge(0, 1, 10);

graph.addEdge(0, 2, 6);

graph.addEdge(0, 3, 5);

graph.addEdge(1, 3, 15);

graph.addEdge(2, 3, 4);
graph.kruskalMST();

return 0;

Que 4: Bellman Ford

#include <iostream>

#include <vector>

#include <climits>

using namespace std;

class Edge {

public:

int src, dest, weight;

};

class Graph {

public:

int V, E;

vector<Edge> edges;

Graph(int V, int E) {

this->V = V;

this->E = E;

}
void addEdge(int src, int dest, int weight) {

Edge edge = {src, dest, weight};

edges.push_back(edge);

void bellmanFord(int src) {

vector<int> dist(V, INT_MAX);

dist[src] = 0;

for (int i = 1; i <= V - 1; ++i) {

for (const Edge& edge : edges) {

int u = edge.src;

int v = edge.dest;

int weight = edge.weight;

if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) {

dist[v] = dist[u] + weight;

for (const Edge& edge : edges) {

int u = edge.src;

int v = edge.dest;

int weight = edge.weight;

if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) {

cout << "Graph contains negative weight cycle" << endl;

return;

}
}

printSolution(dist);

void printSolution(const vector<int>& dist) {

cout << "Vertex\tDistance from Source" << endl;

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

cout << i << "\t\t" << dist[i] << endl;

};

int main() {

int V = 5; // Number of vertices

int E = 8; // Number of edges

Graph graph(V, E);

graph.addEdge(0, 1, -1);

graph.addEdge(0, 2, 4);

graph.addEdge(1, 2, 3);

graph.addEdge(1, 3, 2);

graph.addEdge(1, 4, 2);

graph.addEdge(3, 2, 5);

graph.addEdge(3, 1, 1);

graph.addEdge(4, 3, -3);

int source = 0;

graph.bellmanFord(source);
return 0;

Que 5: B-Tree

#include <iostream>

using namespace std;

class BTreeNode {

int *keys;

int t;

BTreeNode **C;

int n;

bool leaf;

public:

BTreeNode(int _t, bool _leaf);

void traverse();

BTreeNode *search(int k);

void insertNonFull(int k);

void splitChild(int i, BTreeNode *y);

friend class BTree;

};

class BTree {
BTreeNode *root;

int t;

public:

BTree(int _t) {

root = nullptr;

t = _t;

void traverse() {

if (root != nullptr) root->traverse();

BTreeNode *search(int k) {

return (root == nullptr) ? nullptr : root->search(k);

void insert(int k);

};

BTreeNode::BTreeNode(int _t, bool _leaf) {

t = _t;

leaf = _leaf;

keys = new int[2 * t - 1];

C = new BTreeNode *[2 * t];

n = 0;

}
void BTreeNode::traverse() {

int i;

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

if (leaf == false) {

C[i]->traverse();

cout << " " << keys[i];

if (leaf == false) {

C[i]->traverse();

BTreeNode *BTreeNode::search(int k) {

int i = 0;

while (i < n && k > keys[i]) {

i++;

if (keys[i] == k) {

return this;

if (leaf == true) {

return nullptr;

}
return C[i]->search(k);

void BTree::insert(int k) {

if (root == nullptr) {

root = new BTreeNode(t, true);

root->keys[0] = k;

root->n = 1;

} else {

if (root->n == 2 * t - 1) {

BTreeNode *s = new BTreeNode(t, false);

s->C[0] = root;

s->splitChild(0, root);

int i = 0;

if (s->keys[0] < k) {

i++;

s->C[i]->insertNonFull(k);

root = s;

} else {

root->insertNonFull(k);

}
void BTreeNode::insertNonFull(int k) {

int i = n - 1;

if (leaf == true) {

while (i >= 0 && keys[i] > k) {

keys[i + 1] = keys[i];

i--;

keys[i + 1] = k;

n = n + 1;

} else {

while (i >= 0 && keys[i] > k) {

i--;

if (C[i + 1]->n == 2 * t - 1) {

splitChild(i + 1, C[i + 1]);

if (keys[i + 1] < k) {

i++;

C[i + 1]->insertNonFull(k);

void BTreeNode::splitChild(int i, BTreeNode *y) {

BTreeNode *z = new BTreeNode(y->t, y->leaf);


z->n = t - 1;

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

z->keys[j] = y->keys[j + t];

if (y->leaf == false) {

for (int j = 0; j < t; j++) {

z->C[j] = y->C[j + t];

y->n = t - 1;

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

C[j + 1] = C[j];

C[i + 1] = z;

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

keys[j + 1] = keys[j];

keys[i] = y->keys[t - 1];

n = n + 1;

}
int main() {

BTree t(3);

t.insert(10);

t.insert(20);

t.insert(5);

t.insert(6);

t.insert(12);

t.insert(30);

t.insert(7);

t.insert(17);

cout << "Traversal of the constructed tree is ";

t.traverse();

return 0;

Que 6: Binary Search Tree

#include <iostream>

using namespace std;

class Node {

public:

int key;

Node *left, *right;

Node(int item) {
key = item;

left = right = nullptr;

};

class BinaryTree {

public:

Node *root;

BinaryTree() {

root = nullptr;

void insert(int key) {

root = insertRec(root, key);

Node* search(int key) {

return searchRec(root, key);

void inorder() {

inorderRec(root);

private:

Node* insertRec(Node* root, int key) {

if (root == nullptr) {

root = new Node(key);


return root;

if (key < root->key) {

root->left = insertRec(root->left, key);

} else if (key > root->key) {

root->right = insertRec(root->right, key);

return root;

Node* searchRec(Node* root, int key) {

if (root == nullptr || root->key == key) {

return root;

if (key < root->key) {

return searchRec(root->left, key);

return searchRec(root->right, key);

void inorderRec(Node* root) {

if (root != nullptr) {

inorderRec(root->left);

cout << root->key << " ";

inorderRec(root->right);
}

};

int main() {

BinaryTree tree;

tree.insert(50);

tree.insert(30);

tree.insert(20);

tree.insert(40);

tree.insert(70);

tree.insert(60);

tree.insert(80);

cout << "Inorder traversal of the given tree: ";

tree.inorder();

int key = 60;

if (tree.search(key) != nullptr) {

cout << "\nNode " << key << " found in the tree." << endl;

} else {

cout << "\nNode " << key << " not found in the tree." << endl;

key = 25;

if (tree.search(key) != nullptr) {

cout << "Node " << key << " found in the tree." << endl;

} else {

cout << "Node " << key << " not found in the tree." << endl;
}

return 0;

Que 7: KMP Algorithm

#include <iostream>

#include <vector>

#include <string>

using namespace std;

void computeLPSArray(string pattern, int M, vector<int>& lps) {

int length = 0;

lps[0] = 0;

int i = 1;

while (i < M) {

if (pattern[i] == pattern[length]) {

length++;

lps[i] = length;

i++;

} else {

if (length != 0) {

length = lps[length - 1];

} else {

lps[i] = 0;

i++;
}

void KMPSearch(string pattern, string text) {

int M = pattern.size();

int N = text.size();

vector<int> lps(M);

computeLPSArray(pattern, M, lps);

int i = 0;

int j = 0;

while (i < N) {

if (pattern[j] == text[i]) {

i++;

j++;

if (j == M) {

cout << "Found pattern at index " << i - j << endl;

j = lps[j - 1];

} else if (i < N && pattern[j] != text[i]) {

if (j != 0) {

j = lps[j - 1];

} else {

i++;

}
}

int main() {

string text = "ABABDABACDABABCABAB";

string pattern = "ABABCABAB";

KMPSearch(pattern, text);

return 0;

Que 8: Su ix Tree

#include <iostream>

#include <vector>

#include <unordered_map>

#include <string>

using namespace std;

// Node structure for the su ix tree

class Su ixTreeNode {

public:

unordered_map<char, Su ixTreeNode*> children;

int start;

int* end;

int su ixIndex;

Su ixTreeNode(int start, int* end) : start(start), end(end), su ixIndex(-1) {}


};

// Class to build a su ix tree

class Su ixTree {

private:

string text;

Su ixTreeNode* root;

int size;

void buildTree() {

int n = text.size();

int* end = new int(-1);

root = new Su ixTreeNode(-1, end);

Su ixTreeNode* currentNode = root;

int remainingSu ixCount = 0;

int lastNewNode = -1;

int currentEnd = -1;

int i = 0;

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

currentEnd = i;

remainingSu ixCount++;

lastNewNode = -1;

while (remainingSu ixCount > 0) {

if (currentNode->children.find(text[i]) == currentNode->children.end()) {

currentNode->children[text[i]] = new Su ixTreeNode(i, new int(currentEnd));

if (lastNewNode != -1) {

lastNewNode->su ixIndex = i;
lastNewNode = -1;

} else {

Su ixTreeNode* nextNode = currentNode->children[text[i]];

if (nextNode->start < i) {

currentNode = nextNode;

break;

public:

Su ixTree(string inputText) : text(inputText) {

size = text.size();

buildTree();

void printTree(Su ixTreeNode* node) {

if (node == nullptr) return;

if (node->su ixIndex != -1) {

cout << "Leaf at index " << node->su ixIndex << " with substring: ";

for (int i = node->start; i < *node->end; i++) {

cout << text[i];

cout << endl;

for (auto child : node->children) {


printTree(child.second);

void display() {

printTree(root);

};

int main() {

string inputText;

cout << "Enter a string to build the su ix tree: ";

cin >> inputText;

Su ixTree su ixTree(inputText);

cout << "Su ix Tree:

";

su ixTree.display();

return 0;

You might also like