Master of Computer Application
1st Semester
Session 2024-2026
Advanced Data Structure
(20MCA2121C5)
Submitted To: Ms. Shikha Thakur Submitted by: Aashish
(Assistant Professor) Student ID: 146070
Certificate
This is to certify that Aashish S /O Anil Kumar has submitted a
practical file for fulfilment of MCA 1st semester lab course for Advanced Data
Structure.
Submitted To: Ms. Shikha Thakur Submitted by: Aashish
(Assistant Professor) Student ID: 146070
INDEX
S.No EXPERIMENTS REMARKS
1. Write a C++ program that use both recursive and non-recursive
functions for implementingthe following searching methods: a) Linear
search b) Binary search.
2. Write a C++ programs for implementing the following sorting
methods: a) Bubble sort b)Insertion sort c) Quick sort d) Merge sort.
3. Write a C++ programs that use recursive functions to traverse the
given
binary tree in a)Preorder b)Inorder c) Postorder.
4. Write a C++ program to perform the operations - Insertion into a B-
tree
5. Write a C++ program to implement breadth firstsearch and depth first
search.
6. Write a C++ program to implement minimumcost spanning tree using
Kruskal’s Algorithm.
EXPERIMET 1
Write a C++ program that use both recursive and non-recursive functions for
implementingthe following searching methods:
a) Linear search
b) Binary search.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// Linear Search (Non-recursive)
int linearSearch(const vector<int>& arr, int target) {for (int i = 0; i < arr.size(); ++i) {
if (arr[i] == target) {
return i; // Return the index if target is found
}
}
return -1; // Return -1 if target is not found
}
// Linear Search (Recursive)
int linearSearchRecursive(const vector<int>& arr, int target, int index = 0) {if (index >=
arr.size()) {
return -1; // Target not found
}
if (arr[index] == target) {
return index; // Return the index if target is found
}
return linearSearchRecursive(arr, target, index + 1); // Recursive call
}
// Binary Search (Non-recursive)
int binarySearch(const vector<int>& arr, int target) {int low = 0;
int high = arr.size() - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == target) { return mid; // Target found
}
else if (arr[mid] < target) {
low = mid + 1; // Target in the right half
}
else {
high = mid - 1; // Target in the left half
}
}
return -1; // Target not found
}
// Binary Search (Recursive)
int binarySearchRecursive(const vector<int>& arr, int target, int low, int high) {if (low > high) {
return -1; // Target not found
}
int mid = low + (high - low) / 2;if (arr[mid] == target) {
return mid; // Target found
}
else if (arr[mid] < target) {
return binarySearchRecursive(arr, target, mid + 1, high); // Search in the right
half
}
else {
return binarySearchRecursive(arr, target, low, mid - 1); // Search in the left
half
}
}
int main() {
vector<int> arr = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19};
int target;
cout << "Enter the target element: ";cin >> target;
// Linear Search (Non-recursive)
int index = linearSearch(arr, target);if (index != -1) {
cout << "Linear Search (Non-recursive): Found target at index " << index << endl;
} else {
cout << "Linear Search (Non-recursive): Target not found" << endl;
}
// Linear Search (Recursive)
index = linearSearchRecursive(arr, target);if (index != -1) {
cout << "Linear Search (Recursive): Found target at index " << index << endl;
} else {
cout << "Linear Search (Recursive): Target not found" << endl;
}
// Binary Search (Non-recursive) index = binarySearch(arr, target);if (index != -1) {
cout << "Binary Search (Non-recursive): Found target at index " << index << endl;
} else {
cout << "Binary Search (Non-recursive): Target not found" << endl;
}
// Binary Search (Recursive)
index = binarySearchRecursive(arr, target, 0, arr.size() - 1);if (index != -1) {
cout << "Binary Search (Recursive): Found target at index " << index << endl;
} else {
cout << "Binary Search (Recursive): Target not found" << endl;
}
return 0;
}
Output:-
EXPERIMETS 2
Write a C++ programs for implementing the following sorting methods:
a) Bubble sort
b) Insertion sort
c) Quick sort
d) Merge sort
#include <iostream>
#include <vector>
#include <algorithm> // Bubble Sort (Non-recursive)
std::swapusing namespace std;
void bubbleSort(vector<int>& arr) {
int n = arr.size();
for (int i = 0; i < n - 1; ++i) {
// Flag to detect if any swapping occurredbool swapped = false;
for (int j = 0; j < n - i - 1; ++j) {if (arr[j] > arr[j + 1]) {
swap(arr[j], arr[j + 1]);swapped = true;
}
}
// If no elements were swapped, the array is already sortedif (!swapped) break;
}
}
// Insertion Sort
void insertionSort(vector<int>& arr) {int n = arr.size();
for (int i = 1; i < n; ++i) {int key = arr[i];
int j = i - 1;
// Shift elements that are greater than the key to the rightwhile (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
--j;
}
// Place the key at its correct positionarr[j + 1] = key;
}
}
// Quick Sort (Recursive)
int partition(vector<int>& arr, int low, int high) {int pivot = arr[high];
int i = low - 1; // Index of smaller elementfor (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(vector<int>& arr, int low, int high) {if (low < high) {
int pi = partition(arr, low, high); quickSort(arr, low, pi - 1); // Left partition quickSort(arr, pi + 1,
high); // Right partition
}
}
// Merge Sort (Recursive)
void merge(vector<int>& arr, int left, int mid, int right) {int n1 = mid - left + 1;
int n2 = right - mid;
// Create temporary arrays for left and right halves
vector<int> L(n1), R(n2);
// Copy data to temp arrays L[] and R[]
for (int i = 0; i < n1; ++i) {
L[i] = arr[left + i];
}
for (int j = 0; j < n2; ++j) {R[j] = arr[mid + 1 + j];
}
// Merge the temp arrays back into arr[left..right]
int i = 0; // Initial index of first subarray
int j = 0; // Initial index of second subarray
int k = left; // Initial index of merged subarray
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k++] = L[i++];
} else {
arr[k++] = R[j++];
}
}
// Copy remaining elements of L[], if any
while (i < n1) {
arr[k++] = L[i++];
}
// Copy remaining elements of R[], if any
while (j < n2) {
arr[k++] = R[j++];
}
}
void mergeSort(vector<int>& arr, int left, int right) {if (left < right) {
int mid = left + (right - left) / 2;
mergeSort(arr, left, mid); // Left half mergeSort(arr, mid + 1, right); // Right half
merge(arr, left, mid, right); // Merge the two halves
}
}
// Function to print an array
void printArray(const vector<int>& arr) {for (int num : arr) {
cout << num << " ";
}
cout << endl;
}
int main() {
vector<int> arr = {64, 25, 12, 22, 11};
cout << "Original array: ";printArray(arr);
// Bubble Sort
vector<int> bubbleArr = arr;bubbleSort(bubbleArr);
cout << "Bubble Sorted array: ";printArray(bubbleArr);
// Insertion Sort
vector<int> insertionArr = arr;insertionSort(insertionArr);
cout << "Insertion Sorted array: ";printArray(insertionArr);
// Quick Sort
vector<int> quickArr = arr; quickSort(quickArr, 0, quickArr.size() - 1);cout << "Quick Sorted
array: "; printArray(quickArr);
// Merge Sort
vector<int> mergeArr = arr; mergeSort(mergeArr, 0, mergeArr.size() - 1);cout << "Merge Sorted
array: "; printArray(mergeArr);
return 0;
}
Output:-
EXPERIMETS 3
Write a C++ programs that use recursive functions to traverse the given binary
treein:
a)Preorder
b) Inorder
c) Postorder
#include <iostream>
using namespace std;
// Definition of a binary tree nodestruct Node {
int data; Node* left; Node* right;
// Constructor to create a new node
Node(int val) : data(val), left(nullptr), right(nullptr) {}};
// Preorder Traversal (Root -> Left -> Right)void preorder(Node* root) {
if (root == nullptr) return;
// Visit the root node firstcout << root->data << " ";
// Traverse the left subtreepreorder(root->left);
// Traverse the right subtreepreorder(root->right);
}
// Inorder Traversal (Left -> Root -> Right)void inorder(Node* root) {
if (root == nullptr) return;
// Traverse the left subtreeinorder(root->left);
// Visit the root node cout << root->data << " ";
// Traverse the right subtreeinorder(root->right);
}
// Postorder Traversal (Left -> Right -> Root)void postorder(Node* root) {
if (root == nullptr) return;
// Traverse the left subtreepostorder(root->left);
// Traverse the right subtree
postorder(root->right);
// Visit the root node cout << root->data << " ";
}
// Helper function to create a simple binary treeNode* createBinaryTree() {
Node* root = new Node(1);root->left = new Node(2);root->right = new Node(3);
root->left->left = new Node(4); root->left->right = new Node(5); root->right->left = new
Node(6); root->right->right = new Node(7);
return root;
}
int main() {
// Create a binary tree
Node* root = createBinaryTree();
cout << "Preorder Traversal: ";
preorder(root); // Preorder: Root -> Left -> Rightcout << endl;
cout << "Inorder Traversal: ";
inorder(root); // Inorder: Left -> Root -> Rightcout << endl;
cout << "Postorder Traversal: ";
postorder(root); // Postorder: Left -> Right -> Rootcout << endl;
return 0;
}
Output:-
EXPERIMETS 4
Write a C++ program to perform the operations - Insertion into a B-tree
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// B-Tree Node definitionstruct BTreeNode {
vector<int> keys; // Array of keys in the node vector<BTreeNode*> children; // Array of
children pointersbool leaf; // Boolean to check if the node is a leaf node
int t; // Minimum degree (defines the range for the number of keys in the node)BTreeNode(int _t,
bool _leaf) : t(_t), leaf(_leaf) {}
// Function to insert a key in a non-full node
void insertNonFull(int key);
// Function to split the child of a node
void splitChild(int i, BTreeNode* y);
// Function to print the tree
void printNode();
};
// B-tree definitionclass BTree { private:
BTreeNode* root;
int t; // Minimum degree
public:
BTree(int _t) : t(_t) {
root = new BTreeNode(t, true);
}
void insert(int key);void printTree() {
root->printNode();
}
};
// Function to insert a key into the B-treevoid BTree::insert(int key) {
// If the root node is full, split it and create a new rootif (root->keys.size() == 2 * t - 1) {
BTreeNode* s = new BTreeNode(t, false);s->children.push_back(root);
s->splitChild(0, root);root = s;
}
root->insertNonFull(key);
}
// Function to insert a key in a non-full node
void BTreeNode::insertNonFull(int key) {int i = keys.size() - 1;
if (leaf) {
// If the node is a leaf, find the position to insert the keywhile (i >= 0 && keys[i] > key) {
i--;
}
keys.insert(keys.begin() + i + 1, key);
} else {
// If the node is not a leaf, find the appropriate child to insert the keywhile (i >= 0 && keys[i] >
key) {
i--;
} i++;
BTreeNode* child = children[i];
// If the child is full, split it
if (child->keys.size() == 2 * t - 1) {splitChild(i, child);
if (keys[i] < key) {i++;
}
}
children[i]->insertNonFull(key);
}
}
// Function to split a child of a node
void BTreeNode::splitChild(int i, BTreeNode* y) {
// Create a new node to store the middle element of yBTreeNode* z = new BTreeNode(y->t, y-
>leaf);
z->keys.resize(t - 1);
// Copy the second half of y's keys to zfor (int j = 0; j < t - 1; j++) {
z->keys[j] = y->keys[j + t];
}
// If y is not a leaf, copy the second half of y's children to zif (!y->leaf) {
z->children.resize(t);
for (int j = 0; j < t; j++) {
z->children[j] = y->children[j + t];
}
}
// Reduce the size of yy->keys.resize(t - 1); y->children.resize(t);
// Move all children of the current node one position aheadchildren.insert(children.begin() + i +
1, z);
// Insert the middle key of y into the current nodekeys.insert(keys.begin() + i, y->keys[t - 1]);
// Clear the middle key from y
y->keys[t - 1] = 0;
}
// Function to print the node and its children (for debugging purposes)void
BTreeNode::printNode() {
// Print all keys in the current node for (int i = 0; i < keys.size(); i++) {
cout << keys[i] << " ";
}
cout << endl;
// If this is not a leaf, recursively print the childrenif (!leaf) {
for (auto child : children) {child->printNode();
}
}
}
int main() {
// Create a B-tree with minimum degree 3 (B-tree of order 6)BTree tree(3);
// Insert keys into the B-treetree.insert(10); tree.insert(20); tree.insert(5); tree.insert(6);
tree.insert(12); tree.insert(30); tree.insert(7); tree.insert(17);
// Print the B-tree after insertion
cout << "B-tree after insertions:" << endl;tree.printTree();
return 0;
}
Output:-
EXPERIMETS 6
Write a C++ program to implement breadth first search and depth first search.
#include <iostream>
#include <vector>
#include <stack>
#include <queue>
#include <set>
using namespace std;
// Graph class to represent the graph using an adjacency list
class Graph {
private:
int V; // Number of vertices
vector<vector<int>> adj; // Adjacency list
public:
Graph(int V); // Constructor to initialize graph
void addEdge(int u, int v); // Function to add an edge to the graph
void BFS(int start); // Function for Breadth First Search
void DFS(int start); // Function for Depth First Search
void DFSUtil(int start, set<int>& visited); // Helper function for DFS
};
// Constructor to initialize the graph with V vertices
Graph::Graph(int V) {
this->V = V; adj.resize(V);
}
// Function to add an edge between vertices u and v
void Graph::addEdge(int u, int v) {
adj[u].push_back(v); // Add v to the list of u's neighbors
adj[v].push_back(u); // Add u to the list of v's neighbors (undirected graph)
}
// Breadth First Search (BFS)
void Graph::BFS(int start) {
vector<bool> visited(V, false); // Array to keep track of visited vertices
queue<int> q; // Queue for BFS
visited[start] = true;q.push(start);
cout << "Breadth First Search starting from vertex " << start << ": ";while (!q.empty()) {
int node = q.front();
cout << node << " ";q.pop();
// Visit all the adjacent vertices of the current node
for (int neighbor : adj[node]) {
if (!visited[neighbor]) { visited[neighbor] = true;
q.push(neighbor);
}
}
}
cout << endl;
}
// Depth First Search (DFS)
void Graph::DFS(int start) {
set<int> visited; // Set to store visited nodes (using set to avoid duplicates)
cout << "Depth First Search starting from vertex " << start << ": "; DFSUtil(start, visited);
cout << endl;
}
// Helper function for recursive DFS
void Graph::DFSUtil(int start, set<int>& visited) {visited.insert(start);
cout << start << " ";
// Visit all the adjacent vertices of the current node
for (int neighbor : adj[start]) {
if (visited.find(neighbor) == visited.end()) { DFSUtil(neighbor, visited); // Recur for unvisited
neighbor
}
}
}
int main() {
// Create a graph with 6 vertices (0 to 5)Graph g(6);
// Add edges to the graphg.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 3);
g.addEdge(1, 4);
g.addEdge(2, 5);
// Perform BFS starting from vertex 0g.BFS(0);
// Perform DFS starting from vertex 0g.DFS(0);
return 0;
}
Output:-