DSA All Programs
DSA All Programs
1
SEARCHING AND SORTING
switch(ch) // Switch case is used for select 1 choice from multiple choice
{
case 1:
bubbleSort(data); //Call bubbleSort()
display(data);
break;
case 2:
insertSort(data); //Call insertSort()
display(data);
break;
case 3:
search (data); //Call search()
break;
case 4:
binarysearch(data); //Call binarysearch()
break;
default:
cout << " Invalid choice ..."; //If invalid (other than 4) so print msg
}
}
void bubbleSort (struct student list[size]) // Arrange list of students according the number
{
int i, j;
struct student temp;
for (i = 0; i< size -1; i++) //For first Roll No.
{
for (j = 0; j< (size-1-i); j++) //For second Roll No.
{
if (list[j].rno > list[j + 1].rno) //If first roll no. > second roll no.
{
temp = list[j]; //Perform swapping/ interchange opertaion.
list [j] = list [j+ 1];
list [j + 1] = temp;
}
}
}
}
cout<<"\n Enter name of student you want to search"; //name you want to search
cin>>search;
while(lower <= upper) //if lower index less then greater index
{
if(strcmp(list[mid].name,search)<0) //Compare search with mid element
lower = mid + 1; //if greater then set
#include <string>
struct Node {
char data;
Node* next;
};
class Stack {
Node* topNode;
public:
Stack() : topNode(nullptr) {}
topNode = newNode;
char pop() {
topNode = topNode->next;
delete temp;
return value;
char top() {
bool isEmpty() {
};
return 0;
Stack s;
string postfix;
if (isalnum(ch)) {
s.push(ch);
} else {
postfix += s.pop();
s.push(ch);
while (!s.isEmpty()) {
return postfix;
Stack operators;
string result;
char ch = infix[i];
if (isalnum(ch)) {
operators.push(ch);
} else {
operators.push(ch);
while (!operators.isEmpty()) {
return result;
int main() {
string infix;
// Postfix Conversion
// Prefix Conversion
return 0;
}
PRACTICAL NO. 3
Circular Queue
case 4:
cout<<"Exit\n"; //Exit operations
break;
default: cout<<"Incorrect!\n"; //Incorrect Choice
}
} while(ch != 4);
return 0;
}
PRACTICAL NO. 4
Expression Tree
#include <iostream>
#include <stack>
#include <string.h>
using namespace std;
struct node
{
char data;
node *leftchild;
node *rightchild;
}*root;
node *store_root_address;
void recursive_inorder(node*root);
void recursive_preorder(node*root);
void recursive_postorder(node*root);
bool isOperator(char c)
{
if (c == '+' || c == '-' || c == '*' || c == '/' || c == '^')
{
return true;
}
return false;
}
node* newNode(char v)
{
node *temp = new node;
temp->leftchild = NULL;
temp->rightchild = NULL;
temp->data = v;
return temp;
};
else
{
root= newNode(postfix[i]);
t1 = s.top();
s.pop();
t2 = s.top();
s.pop();
root->rightchild = t1;
root->leftchild = t2;
s.push(root);
}
}
root= s.top();
s.pop();
return root;
}
else
{
root= newNode(prefix[i]);
t1 = s.top();
s.pop();
t2 = s.top();
s.pop();
root->leftchild = t1;
root->rightchild = t2;
s.push(root);
}
}
root = s.top();
s.pop();
return root;
}
void recursive_inorder(node*root)
{
node*temp;
temp=root;
if(temp!=NULL)
{
recursive_inorder(temp->leftchild);
cout<<" "<<temp->data;
recursive_inorder(temp->rightchild);
}
void recursive_preorder(node*root)
{
node*temp;
temp=root;
if(temp!=NULL)
{
cout<<" "<<temp->data;
recursive_preorder(temp->leftchild);
recursive_preorder(temp->rightchild);
}
}
void recursive_postorder(node*root)
{
node*temp;
temp=root;
if(temp!=NULL)
{
recursive_postorder(temp->leftchild);
recursive_postorder(temp->rightchild);
cout<<" "<<temp->data;
}
stack<node *> s;
{
s.push(current_node);
current_node=current_node->leftchild;
current_node= s.top();
s.pop();
cout<<current_node->data;
current_node=current_node->rightchild;
}
}
while (s.empty()==false)
{
node *temp=s.top();
s.pop();
cout<<" "<<temp->data;
if (temp->rightchild)
{
s.push(temp->rightchild);
}
if (temp->leftchild)
{
s.push(temp->leftchild);
}
}
stack<node *>s1;
stack<node *> s2;
s1.push(root);
node *temp;
while(s1.empty()==false)
{
temp=s1.top();
s1.pop();
s2.push(temp);
if(temp->leftchild)
{
s1.push(temp->leftchild);
}
if(temp->rightchild)
{
s1.push(temp->rightchild);
}
}
while(!s2.empty())
{
temp=s2.top();
s2.pop();
cout<<" "<<temp->data;
int main()
{
int k =0;
int choice, choice_R, choice_NR;
node *root_address;
char reverse[100],prefix[100],postfix[100];
void recursive_inorder(node*root);
void recursive_preorder(node*root);
void recursive_postorder(node*root);
do
{
cout<<"\n";
cout<<"\n From which expression you want to construct binary expression tree?\n";
cout<<"\n 1) Prefix Expression. \n 2) Postfix Expression. \n 3) Exit.";
cout<<"\n Enter Your Choice: ";
cin>>choice;
switch(choice)
{
case 1:
//ACCEPTING PREFIX EXPRESSION
cout<<"\nEnter Prefix Expression: ";
cin>>prefix;
for(int j=strlen(prefix)-1;j>=0;j--)
reverse[k++]=prefix[j];
reverse[k]='\0';
//cout<<reverse;
root_address=construct_prefix_tree(reverse);
cout<<"\nIn which manner you want to traverse the binary expression tree?";
cout<<"1) Recursively. \n2) Non-Recursively. \n3) Exit.";
cout<<"Enter Your Choice: ";
cin>>choice_R;
switch(choice_R)
{
case 1:
//RECURSIVE FUNCTIONS ON PREFIX
cout<<"\nRecursive preorder is: ";
recursive_preorder(root_address);
case 2:
//NON RECURSIVE FUNCTIONS ON PREFIX
case 3:
cout<<"You Have Successfully Exitted.....";
break;
default:
cout<<"INVALID CHOICE.....";
}
break;
case 2:
cout<<"\nEnter Postfix Expression: ";
cin>>postfix;
root_address=construct_postfix_tree(postfix);
cout<<"\nIn which manner you want to traverse the binary
expression tree?";
cout<<"1) Recursively. \n2) Non-Recursively. \n3) Exit.";
cout<<"\nEnter Your Choice: ";
cin>>choice_R;
switch(choice_R)
{
case 1:
//RECURSIVE FUNCTIONS ON PREFIX
cout<<"\nRecursive preorder is: ";
recursive_preorder(root_address);
break;
case 2:
//NON RECURSIVE FUNCTIONS ON PREFIX
case 3:
cout<<"You Have Successfully Exitted.....";
break;
default:
cout<<"INVALID CHOICE.....";
}
}
}
while(choice!=3);
return 0;
}
PRACTICAL NO. 5
Binary Search Tree
#include<iostream>
#include<stdlib.h>
using namespace std;
struct treeNode
{
int data; //Value of Node
treeNode *left; //Left address pointer
treeNode *right; //Right address pointer
};
treeNode* FindMin(treeNode *node) //Function for find min value node
{
if(node==NULL) //if node value is Null
{
return NULL; // There is no element in the tree
}
if(node->left) //Go to the left sub tree to find the min element
return FindMin(node->left);
else
return node;
}
temp = FindMin(node->right);
node -> data = temp->data;
/* As we replaced it with some other node, we have to delete that node */
node -> right = Delet(node->right,temp->data);
}
else
{
/* If there is only one or zero children then we can directly
remove it from the tree and connect its parent to its child */
temp = node;
if(node->left == NULL) //If deleted node has no left child
node = node->right; // Conncet right child to its parent node.
else if(node->right == NULL) //If deleted node has no right child
node = node->left; // Conncet left child to its parent node.
free(temp); //temp is longer required
}
}
return node; //Return remaining tree
}
cout<<"\n1.Insert\n2.Delete\n3.Inorder\n4.Preorder\n5.Postorder\n6.FindMin\n
7.FindMax\n8.Search\n9.Exit\n";
cout<<"Enter ur choice:";
cin>>ch; //Read your choice
switch(ch) //Select one choice from multiple choice
{
case 1:
cout<<"\nEnter element to be insert:"; //Insert Node as root
cin>>val;
root = Insert(root, val); //Call Insert()
cout<<"\nElements in BST are:";
Inorder(root); //Insert inorder way
break;
case 2:
cout<<"\nEnter element to be deleted:"; //Delete Node
cin>>val;
root = Delet(root,val); //Call Delete()
cout<<"\nAfter deletion elements in BST are:";
Inorder(root); //After deletion inorder way element display
break;
case 3:
cout<<"\nInorder Travesals is:";
Inorder(root); //Call inorder()
break;
case 4:
cout<<"\nPreorder Traversals is:";
Preorder(root); //Call preorder()
break;
case 5:
cout<<"\nPostorder Traversals is:";
Postorder(root); //Call postorder()
break;
case 6:
temp = FindMin(root); //FindMin() used in Delete case
cout<<"\nMinimum element is :"<<temp->data;
break;
case 7:
temp = FindMax(root); //FindMax() used in Delete case
cout<<"\nMaximum element is :"<<temp->data;
break;
case 8:
cout<<"\nEnter element to be searched:";
cin>>val;
temp = Find(root,val); //Call search()
if(temp==NULL)
{
cout<<"Element is not foundn"; //Display Message
}
else
{
cout<<"Element "<<temp->data<<" is Found\n";
}
break;
case 9:
exit(0); //Exit Program
break;
default:
cout<<"\nEnter correct choice:"; //Chioce other then 9 invalid
break;
}
}
return 0;
}
PRACTICAL NO. 6
Threaded Binary Tree
#include <iostream>
using namespace std;
Node(int val) {
data = val;
left = right = NULL; // Using NULL for compatibility
lth = rth = false;
}
};
public:
ThreadedBinaryTree() {
root = NULL;
dummy = new Node(-999); // Dummy node to simplify traversal
dummy->left = dummy->right = dummy;
}
// In-order traversal
void inorder() {
if (root == NULL) {
cout << "\nTree is empty!";
return;
}
// Pre-order traversal
void preorder() {
if (root == NULL) {
cout << "\nTree is empty!";
return;
}
// Main function
int main() {
int choice;
char ans = 'N';
ThreadedBinaryTree th;
do {
cout << "\n\n=== Program For Threaded Binary Tree ===\n";
cout << "1) Create\n2) Display\n3) Exit\n";
cout << "Enter Your Choice: ";
cin >> choice;
switch (choice) {
case 1:
do {
th.create();
cout << "\nDo you want to enter more elements? (y/n): ";
cin >> ans;
} while (ans == 'y' || ans == 'Y');
break;
case 2:
th.display();
break;
case 3:
cout << "\nExiting program.";
return 0;
default:
cout << "\nInvalid choice! Please try again.";
}
return 0;
}
PRACTICAL NO: 7
Graph: Minimum Spanning Tree
Prim's Algorithm
#include<iostream>
#define SIZE 20
#define INFINITY 99
using namespace std;
class MST {
private:
int G[SIZE][SIZE], nodes;
public:
MST();
void Prim();
void get_data();
};
MST::MST() {
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
G[i][j] = 0;
}
}
}
void MST::Prim() {
int select[SIZE] = {0}; // To mark selected vertices
int min_dist, v1 = 0, v2 = 0, total = 0;
// Find the minimum distance edge from the selected set to an unselected
vertex
for (int i = 0; i < nodes; i++) {
if (select[i]) {
for (int j = 0; j < nodes; j++) {
if (!select[j] && G[i][j]) { // Vertex j is not selected, and there's an
edge
if (G[i][j] < min_dist) {
min_dist = G[i][j];
v1 = i;
v2 = j;
}
}
}
}
}
cout << "\nTotal path length is " << total << endl;
}
void MST::get_data() {
int v1, v2, length, edges;
cout << "\nEnter the total number of nodes in the graph: ";
cin >> nodes;
cout << "\nEnter the total number of edges in the graph: ";
cin >> edges;
int main() {
MST obj;
cout << "\nPrim's Algorithm\n";
obj.get_data();
obj.Prim();
return 0;
#include<iostream>
#define SIZE 20
#define INFINITY 99
using namespace std;
class MST {
private:
int G[SIZE][SIZE], nodes;
public:
MST();
void Prim();
void get_data();
};
MST::MST() {
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
G[i][j] = 0;
}
}
}
void MST::Prim() {
int select[SIZE] = {0}; // To mark selected vertices
int min_dist, v1 = 0, v2 = 0, total = 0;
// Find the minimum distance edge from the selected set to an unselected
vertex
for (int i = 0; i < nodes; i++) {
if (select[i]) {
for (int j = 0; j < nodes; j++) {
if (!select[j] && G[i][j]) { // Vertex j is not selected, and there's an
edge
if (G[i][j] < min_dist) {
min_dist = G[i][j];
v1 = i;
v2 = j;
}
}
}
}
}
cout << "\nTotal path length is " << total << endl;
}
void MST::get_data() {
int v1, v2, length, edges;
cout << "\nEnter the total number of nodes in the graph: ";
cin >> nodes;
cout << "\nEnter the total number of edges in the graph: ";
cin >> edges;
int main() {
MST obj;
cout << "\nPrim's Algorithm\n";
obj.get_data();
obj.Prim();
return 0;
}
Kruskal's Algorithm:
#include <iostream>
#include <algorithm>
#include <vector>
class Graph {
private:
vector<pair<int, edge>> G; // graph: weight, (u, v)
vector<pair<int, edge>> T; // MST: weight, (u, v)
int *parent;
int V; // Number of vertices
public:
Graph(int V);
void AddWeightedEdge(int u, int v, int w);
int find_set(int i);
void union_set(int u, int v);
void kruskal();
void print();
};
Graph::Graph(int V) {
parent = new int[V]; // Dynamic array to store parent for union-find
this->V = V;
for (int i = 0; i < V; i++) {
parent[i] = i; // Initialize each vertex as its own parent
}
G.clear(); // Clear the graph
T.clear(); // Clear the MST
}
// Kruskal's algorithm
void Graph::kruskal() {
int uRep, vRep;
sort(G.begin(), G.end()); // Sort edges by weight
int main() {
Graph g(6);
g.AddWeightedEdge(0, 1, 4);
g.AddWeightedEdge(0, 2, 4);
g.AddWeightedEdge(1, 2, 2);
g.AddWeightedEdge(1, 0, 4);
g.AddWeightedEdge(2, 3, 3);
g.AddWeightedEdge(2, 1, 2);
g.AddWeightedEdge(3, 4, 3);
g.AddWeightedEdge(5, 2, 2);
g.AddWeightedEdge(5, 4, 3);
g.kruskal();
g.print();
return 0;
}
PRACTICAL NO: 8
Graph: Shortest Path Algorithm
#include <iostream>
#define MAX 20
char v1;
class Graph {
int g[MAX][MAX], n, c[MAX], ch[MAX], min_dist, client_dist, visit_dist;
char v[MAX], str[MAX][MAX], min_path[MAX], client_path[MAX],
visit_path[MAX];
public:
Graph(int m) {
n = m;
visit_dist = 0;
client_dist = 0;
min_dist = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
g[i][j] = 0;
}
}
}
void acceptVertices();
void acceptEdges();
void displayMatrix();
void initializeDijkstra();
void initializeDijkstra(int i);
void dijkstra(char src, char dest, int flag);
void dijkstraToAllDestinations(char src);
};
void Graph::initializeDijkstra(int i) {
for (int j = 0; j < n; j++) {
str[i][j] = '-';
}
}
do {
ch[i] = 1;
min = 999;
for (j = 0; j < n; j++) {
if (g[i][j] != 0 && i != j && c[i] + g[i][j] < c[j]) {
c[j] = c[i] + g[i][j];
initializeDijkstra(j);
for (k = 0; str[i][k] != '-'; k++) {
str[j][k] = str[i][k];
}
str[j][k] = v[j];
}
}
min = 999;
for (int l = 0; l < n; l++) {
if (c[l] < min && ch[l] == 0) {
min = c[l];
i = l;
}
}
} while (v[i] != d);
int main() {
int n, ch;
char src, dest;
cout << "Enter Number of Landmarks: ";
cin >> n;
Graph cityGraph(n);
do {
cout << "\n1. Accept Names of Landmarks\n2. Accept Distances Between
Landmarks\n3. Display Adjacency Matrix\n4. Find Shortest Path\n5. Exit";
cout << "\nEnter Your Choice: ";
cin >> ch;
switch (ch) {
case 1:
cityGraph.acceptVertices();
break;
case 2:
cityGraph.acceptEdges();
break;
case 3:
cityGraph.displayMatrix();
break;
case 4:
cout << "\nEnter Source (Landmark to start from): ";
cin >> src;
cout << "\nEnter Destination (Landmark to reach): ";
cin >> dest;
cityGraph.dijkstra(src, dest, 0);
break;
case 5:
cout << "Exiting...\n";
break;
default:
cout << "Invalid choice. Try again.\n";
}
} while (ch != 5);
return 0;
}
PRACTICAL NO: 9
Heap Sort
#include <iostream> //header files
using namespace std;
if (l < n && arr[l] > arr[largest]) // If left child exist & larger than root
largest = l; //Consider left child as root node
if (r < n && arr[r] > arr[largest]) //If right child exist & largest then root
largest = r; //Consider right child as root node
for (int i = n - 1; i >= 0; i--) { // One by one extract an element from heap
for(int i=n/2 -1;i>=0;i--){ //comparision start from index of the last non-
leaf node to root
heapify(arr,n,i); //Call function maintain heap property
}
return 0;
}
PRACTICAL NO: 10
File Organization
cout<<"\n";
}
void student::display() //Display Students
Data
{
cout<<"\n "<<roll_no<<"\t "<<Name<<" \t\t "<<Division<<"\t
"<<Address;
}
ofstream out("Student.txt");
cout<<"\nHow many records do you want to enter?: ";
cin>>n;
for(i=0;i<n;i++)
{
s.accept();
out.write((char *)&s,sizeof(s));
}
out.close();
}
student s;
while(infile.read((char *)&s,sizeof(s)))
{
if(s.rollno()==n)
{
cout<<"\nRecord Found\n";
cout<<"\nRoll Number Name
Division Address";
s.display();
flag=1;
break;
}
}
if(flag==0)
{
cout<<"\nRecord Not Found.";
}
infile.close();
}
void display() //Display data in file
{
student s;
ifstream infile("Student.txt");
while(infile.read((char *)&s, sizeof(s)))
{
s.display();
}
infile.close();
}
infile.close();
temp.close();
remove("Student.txt");
rename("temp.txt","Student.txt");
}
int main() //Starting function
{
int choice,roll_no,Marks;
char Name[30];
ofstream out("Student.txt");
out.close();
do
{ cout<<"\n";
cout<<"\nMenu:\n1) Create Database.\n2) Display.\n3)
Add record.\n4) Search Record.\n5)Delete Record.\n6) Exit.";
cout<<"\n\nEnter Your Choice: ";
cin>>choice;
switch(choice)
{
case 1:
cout<<"\n";
create();
break;
case 2:
cout<<"\n";
cout<<"\nRoll Number Name
Division Address";
display();
break;
case 3:
cout<<"\n";
add_record();
break;
case 4:
cout<<"\n";
search();
break;
case 5:
cout<<"\n";
delete_record();
break;
case 6:
cout<<"\n";
cout<<"You Have Successfully Exitted...";
break;
}
}
while(choice!=5);
return 0;
}