PRACTICAL NO.
1
SEARCHING AND SORTING
using namespace std; //Header Files
#include<iostream>
#include <string.h>
int const size = 3; // Enter 3 students data fixed size
struct student //structure for storing different information
{
int rno;
char name [20];
float SGPA;
};
void accept(struct student list [size]); //accept() accept students data
void display(struct student list [80]); // display() display students data
void bubbleSort(struct student list [size]); // Arrange list of students according the number
void insertSort(struct student list [size]); // Arrange list of students alphabetically
void search(struct student list [size]); //Serach students according the SGPA
void binarysearch (struct student list [size]); // Search students according the Name
main() //Starting Function
{
int ch, i;
struct student data[20]; //data array stored students data
accept(data); //call accept method for accept written data
//Opetions for Which operations are performed?
cout << "\n 1: Bubble Sort"; //Choice 1
cout << "\n 2: Insertion Sort"; //Choice 2
cout << "\n 3: Search"; //Choice 3
cout << "\n 4: Binary Search"; //Choice 4
cout << "\n Select your choice:";
cin>>ch; //Selected Choice stored into ch variable.
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 accept(struct student list[size]) //Accept() Logic
{
int i;
for (i = 0; i< size; i++) //Enter data one by one. size=3
{
cout << " Enter rollno, name and SGPA:"; //Print 1st msg
cin >> list[i].rno >> list[i] .name >> list[i].SGPA; //Read Rno, Name and SGPA
}
}
void display (struct student list[80]) //Display given data
{
int i;
cout <<"\n Rollno \t Name \t SGPA \n"; //Display data in table format
for (i = 0; i< size; i++) //Display complete data in Array
{
cout <<"\n" << list[i].rno << "\t" << list[i].name << "\t" << list[i].SGPA;
}
}
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;
}
}
}
}
void insertSort(struct student list[size]) // Arrange list of students alphabetically
{
int k,j;
struct student temp;
for(k=1;k<size;k++) // Complete students names in list
{
temp=list[k]; //stored first names (one by one) in list in temp variable.
j=k-1; //for backword comparision i.e k=1 then j=0
while(strcmp(list[j].name,[Link]) > 0 && j>=0)
// Compare first name in list with name in temp list
{
list[j+1] = list[j]; //stored backword in list all name alphabetically
--j; //insertion sort compare in in backword way
}
list[j+1]=temp; //finaly all name stored in temp shift into list array
}
}
void search(struct student list[size]) //Serach students according the SGPA
{
float SGPA;
int i;
cout<<"\n Enter SGPA:";
//Msg
cin>>SGPA; //Read SGPA
cout<<"\n Rollno\t Name\t SGPA\n";
for (i = 0; i < size;i++) //Search complete SGPA in array
{
if(SGPA==list[i].SGPA) //If given SGPA is matched with List array of SGPA
cout<<"\n"<<list[i].rno<<"\t" <<list[i].name <<"\t" << list[i].SGPA;
//Print complete details of that SGPA of students
}
}
void binarysearch (struct student list[size]) //binarysearch
{
int k, lower, upper, mid; //variable declaration
char search[80];
cout<<"\n Enter name of student you want to search"; //name you want to search
cin>>search;
lower= 0; //Binary search formula
upper = size -1;
mid=(lower + upper)/2;
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
else if (strcmp(list[mid].name, search)==0) //Mid element exactly equal to search
{
cout<<"\n"<<list[mid].rno<< "\t" <<list[mid].name<< "\t" << list[mid].SGPA; //Display msg
break;
}
else
upper = mid- 1; //if smaller then set
mid = (lower + upper)/2; //formula
}
if (lower > upper) //not found in list
cout <<search<< "Not found in the list";
}
PRACTICAL NO. 2
STACK
#include <iostream> //Header Files
#include <cctype>
#include <string>
using namespace std;
// Sreucture Node definition for singly linked list
struct Node {
char data;
Node* next;
};
// Stack ADT using singly linked list
class Stack {
Node* topNode;
public:
Stack() : topNode(nullptr) {}
void push(char value) {
Node* newNode = new Node{value, topNode};
topNode = newNode;
char pop() {
if (isEmpty()) return '\0';
Node* temp = topNode;
char value = temp->data;
topNode = topNode->next;
delete temp;
return value;
char top() {
return (topNode) ? topNode->data : '\0';
bool isEmpty() {
return topNode == nullptr;
};
// Function to check precedence of operators
int precedence(char op) {
if (op == '+' || op == '-') return 1;
if (op == '*' || op == '/') return 2;
return 0;
// Infix to Postfix conversion
string infixToPostfix(const string& infix) {
Stack s;
string postfix;
for (char ch : infix) {
if (isalnum(ch)) {
postfix += ch; // Append operand to result
} else if (ch == '(') {
[Link](ch);
} else if (ch == ')') {
while ([Link]() != '(') postfix += [Link]();
[Link](); // Remove '('
} else {
while (![Link]() && precedence([Link]()) >= precedence(ch))
postfix += [Link]();
[Link](ch);
while (![Link]()) {
postfix += [Link](); // Pop remaining operators
return postfix;
// Infix to Prefix conversion
string infixToPrefix(const string& infix) {
Stack operators;
string result;
// Reverse traversal for prefix conversion
for (int i = [Link]() - 1; i >= 0; --i) {
char ch = infix[i];
if (isalnum(ch)) {
result = ch + result; // Operand goes to result
} else if (ch == ')') {
[Link](ch);
} else if (ch == '(') {
while ([Link]() != ')')
result = [Link]() + result;
[Link](); // Remove ')'
} else {
while (![Link]() && precedence([Link]()) > precedence(ch))
result = [Link]() + result;
[Link](ch);
while (![Link]()) {
result = [Link]() + result; // Pop remaining operators
return result;
int main() {
string infix;
cout << "Enter an infix expression: ";
cin >> infix;
// Postfix Conversion
string postfix = infixToPostfix(infix);
cout << "Postfix Expression: " << postfix << endl;
// Prefix Conversion
string prefix = infixToPrefix(infix);
cout << "Prefix Expression: " << prefix << endl;
return 0;
}
PRACTICAL NO. 3
Circular Queue
#Include <iostream> //header file declaration
using namespace std;
int cqueue[5]; //queue array fixed 5 elements
int front = -1, rear = -1, n=5; //initialization
//Insert Circular Queue Operation
void insertCQ(int val) {
if ((front == 0 && rear == n-1) || (front == rear+1)) { //Queue is full
cout<<"Queue Overflow \n";
return;
}
if (front == -1) { //Queue is empty
front = 0; //Pointer initialization
rear = 0;
} else {
if (rear == n - 1) //If rear points to max condition cant insert element
rear = 0;
else
rear = rear + 1; //Otherwise insert element, rear pointer increamented
}
cqueue[rear] = val ; //New inserted value insert into array
}
//Delete element from Circular Queue
void deleteCQ() {
if (front == -1) { //Queue is empty, Display message
cout<<"Queue Underflow\n";
return ;
}
cout<<"Element deleted from queue is : "<<cqueue[front]<<endl;
if (front == rear) { //Queue is empty
front = -1;
rear = -1;
} else {
if (front == n - 1) //After deleting last element queue is empty
front = 0;
else
front = front + 1; //After deletion front ++
}
}
//Display elements from Circular Queue
void displayCQ() {
int f = front, r = rear; //Pointer Initialization
if (front == -1) { //Queue is empty, Display message
cout<<"Queue is empty"<<endl;
return;
}
cout<<"Queue elements are :\n";
if (f <= r) {
while (f <= r){ //Dispay elements from front pointer to rear pointer
cout<<cqueue[f]<<" "; //All display elements stored in array
f++; //Display one by one
}
} else {
while (f <= n - 1) { //Display all elemets in queue
cout<<cqueue[f]<<" "; //All display elements stored in array
f++; //Display one by one
}
}
cout<<endl;
}
int main() { //Starting of the program
int ch, val; //Variable Declaration
cout<<"1)Insert Element in Queue \n"; //Display Message
cout<<"2)Delete Eelement in Queue \n";
cout<<"3)Display All Elements in Queue \n";
cout<<"4)Exit\n";
do {
cout<<"Enter choice : "<<endl; //Read choice number as per operations
cin>>ch;
switch(ch) {
case 1: //Choice for Insertion
cout<<"Input for insertion: "<<endl;
cin>>val;
insertCQ(val); //Call Insert Function
break;
case 2: //Choice for Deletion
deleteCQ(); //Call Delete Function
break;
case 3: //Choice for Display elements in queue
displayCQ(); //Call Display Function
break;
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;
node *construct_prefix_tree(char prefix[]);
node *construct_postfix_tree(char posfix[]);
void recursive_nonrecursive_choice();
void expression_choice();
void recursive_inorder(node*root);
void recursive_preorder(node*root);
void recursive_postorder(node*root);
void nonrecursive_inorder(node *root);
void nonrecursive_preorder(node *root);
void nonrecursive_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;
};
node* construct_postfix_tree(char postfix[])
{
stack<node *> s;
node *root, *t1, *t2;
for (int i=0; i<strlen(postfix); i++)
{
if (!isOperator(postfix[i]))
{
root=newNode(postfix[i]);
[Link](root);
}
else
{
root= newNode(postfix[i]);
t1 = [Link]();
[Link]();
t2 = [Link]();
[Link]();
root->rightchild = t1;
root->leftchild = t2;
[Link](root);
}
}
root= [Link]();
[Link]();
return root;
}
node* construct_prefix_tree(char prefix[])
{
stack<node *> s;
node *root, *t1, *t2;
for (int i=0; i<strlen(prefix); i++)
{
if (!isOperator(prefix[i]))
{
root= newNode(prefix[i]);
[Link](root);
}
else
{
root= newNode(prefix[i]);
t1 = [Link]();
[Link]();
t2 = [Link]();
[Link]();
root->leftchild = t1;
root->rightchild = t2;
[Link](root);
}
}
root = [Link]();
[Link]();
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;
}
void nonrecursive_inorder(node *root)
{
stack<node *> s;
node *current_node = root;
while (current_node != NULL || [Link]() == false)
while (current_node!= NULL)
{
[Link](current_node);
current_node=current_node->leftchild;
current_node= [Link]();
[Link]();
cout<<current_node->data;
current_node=current_node->rightchild;
}
}
void nonrecursive_preorder(node *root)
{
stack<node *>s;
[Link](root);
if (root == NULL)
{
return;
}
while ([Link]()==false)
{
node *temp=[Link]();
[Link]();
cout<<" "<<temp->data;
if (temp->rightchild)
{
[Link](temp->rightchild);
}
if (temp->leftchild)
{
[Link](temp->leftchild);
}
}
void nonrecursive_postorder(node *root)
{
if(root==NULL)
{
return;
}
stack<node *>s1;
stack<node *> s2;
[Link](root);
node *temp;
while([Link]()==false)
{
temp=[Link]();
[Link]();
[Link](temp);
if(temp->leftchild)
{
[Link](temp->leftchild);
}
if(temp->rightchild)
{
[Link](temp->rightchild);
}
}
while(![Link]())
{
temp=[Link]();
[Link]();
cout<<" "<<temp->data;
int main()
{
int k =0;
int choice, choice_R, choice_NR;
node *root_address;
char reverse[100],prefix[100],postfix[100];
node *construct_prefix_tree(char prefix[]);
node *construct_postfix_tree(char posfix[]);
void recursive_non_recursive_choice();
void expression_choice();
void recursive_inorder(node*root);
void recursive_preorder(node*root);
void recursive_postorder(node*root);
void nonrecursive_inorder(node *root);
void nonrecursive_preorder(node *root);
void nonrecursive_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);
cout<<"\nRecursive inorder is: ";
recursive_inorder(root_address);
cout<<"\nRecursive postorder is: ";
recursive_postorder(root_address);
break;
case 2:
//NON RECURSIVE FUNCTIONS ON PREFIX
cout<<"\n\nNon-Recursive preorder is: ";
nonrecursive_preorder(root_address);
cout<<"\nNon-Recursive inorder is: ";
nonrecursive_inorder(root_address);
cout<<"\nNon-Recursive postorder is: ";
nonrecursive_postorder(root_address);
break;
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);
cout<<"\nRecursive inorder is: ";
recursive_inorder(root_address);
cout<<"\nRecursive postorder is: ";
recursive_postorder(root_address);
break;
case 2:
//NON RECURSIVE FUNCTIONS ON PREFIX
cout<<"\n\nNon-Recursive preorder is: ";
nonrecursive_preorder(root_address);
cout<<"\nNon-Recursive inorder is: ";
nonrecursive_inorder(root_address);
cout<<"\nNon-Recursive postorder is: ";
nonrecursive_postorder(root_address);
break;
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;
}
treeNode* FindMax(treeNode *node) //Function for find max value node
{
if(node==NULL) //if node value is Null
{
return NULL; //There is no element in the tree
}
if(node->right) //Go to the Right sub tree to find the min element
return(FindMax(node->right));
else
return node;
}
treeNode *Insert(treeNode *node,int data) //Insert Node in Binary Tree
{
if(node==NULL) // If node is NULL then create new node
{
treeNode *temp; //Newnode1 is called as temp node
temp=new treeNode; //Allocate memory run time
temp -> data = data; // Stored value in data part.
temp -> left = temp -> right = NULL; //Stored Null value in Left &
Right Part bcz only 1 node create
return temp; //Return single node.
}
if(data >(node->data)) //If new data greater then root data
{
node->right = Insert(node->right,data); // add new node in Right subtree.
}
else if(data < (node->data)) //If new data less then root data
{
node->left = Insert(node->left,data); //add new node in Left subtree.
}
return node; //Return complete tree nodes.
}
treeNode * Delet(treeNode *node, int data) //Delete node in tree
{
treeNode *temp;
if(node==NULL) //If no node is present i.e. Null
{
cout<<"Element Not Found"; //Display msg
}
else if(data < node->data) //If value less then root node
{
node->left = Delet(node->left, data); //Delete node in Left Sub Tree
}
else if(data > node->data) //If value greater then root node
{
node->right = Delet(node->right, data); //Delete node in Right Sub Tree
}
else
{
/* Now We can delete this node and replace with either minimum element
in the right sub tree or maximum element in the left subtree */
if(node->right && node->left) //Deleted Node
{
/* Here we will replace with minimum element in the right sub tree */
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
}
treeNode * Find(treeNode *node, int data) //Search Node in Binary Tree
{
if(node==NULL) //If node value is null
{
return NULL; //Element is not found
}
if(data > node->data) //If search value grater then root node
{
return Find(node->right,data); //Search in the right sub tree.
}
else if(data < node->data) //If search value less then root node
{
return Find(node->left,data); // Search in the left sub tree.
}
else
{
return node; //Element not Found
}
}
void Inorder(treeNode *node) //Find Inorder traversal of node
{
if(node==NULL) //If node not present
{
return;
}
Inorder(node->left); //Apply Inorder Principle "left-root-right"
cout<<node->data<<" ";
Inorder(node->right);
}
void Preorder(treeNode *node) //Find Preorder traversal of node
{
if(node==NULL) //If node not present
{
return;
}
cout<<node->data<<" "; //Apply Preorder Principle "root-left-right"
Preorder(node->left);
Preorder(node->right);
}
void Postorder(treeNode *node) //Find Postorder traversal of node
{
if(node==NULL) //If node not present
{
return;
}
Postorder(node->left); //Apply Postorder Principle "left-right-root"
Postorder(node->right);
cout<<node->data<<" ";
}
int main() //main function
{
treeNode *root = NULL,*temp; //Initially Tree is Null
int ch, val;
//clrscr();
while(1) //If condition set true, Display Message
{
cout<<"\[Link]\[Link]\[Link]\[Link]\[Link]\[Link]\n
[Link]\[Link]\[Link]\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 structure for Threaded Binary Tree
class Node {
public:
int data;
bool lth; // Left Thread Flag
bool rth; // Right Thread Flag
Node* left;
Node* right;
Node(int val) {
data = val;
left = right = NULL; // Using NULL for compatibility
lth = rth = false;
}
};
// Threaded Binary Tree class
class ThreadedBinaryTree {
private:
Node* root;
Node* dummy;
public:
ThreadedBinaryTree() {
root = NULL;
dummy = new Node(-999); // Dummy node to simplify traversal
dummy->left = dummy->right = dummy;
}
// Function to create and insert a new node
void create() {
int value;
cout << "\nEnter The Element: ";
cin >> value;
Node* newNode = new Node(value);
if (root == NULL) { // If tree is empty, new node becomes root
root = newNode;
root->left = dummy;
root->right = dummy;
dummy->left = root;
} else {
insert(root, newNode);
}
}
// Function to insert a node into the threaded binary tree
void insert(Node* current, Node* newNode) {
Node* parent = NULL;
Node* temp = current;
while (temp != dummy) {
parent = temp;
if (newNode->data < temp->data) {
if (temp->lth) {
temp = temp->left;
} else {
break;
}
} else if (newNode->data > temp->data) {
if (temp->rth) {
temp = temp->right;
} else {
break;
}
} else {
cout << "\nDuplicate value! Insertion skipped.";
return;
}
}
if (newNode->data < parent->data) {
newNode->left = parent->left;
newNode->right = parent;
parent->lth = true;
parent->left = newNode;
} else {
newNode->right = parent->right;
newNode->left = parent;
parent->rth = true;
parent->right = newNode;
}
}
// In-order traversal
void inorder() {
if (root == NULL) {
cout << "\nTree is empty!";
return;
}
Node* temp = root;
while (temp->lth && temp->left != dummy) {
temp = temp->left;
}
while (temp != dummy) {
cout << temp->data << " ";
if (!temp->rth) {
temp = temp->right;
} else {
temp = temp->right;
while (temp->lth && temp->left != dummy) {
temp = temp->left;
}
}
}
}
// Pre-order traversal
void preorder() {
if (root == NULL) {
cout << "\nTree is empty!";
return;
}
Node* temp = root;
while (temp != dummy) {
cout << temp->data << " ";
if (temp->lth) {
temp = temp->left;
} else if (temp->rth) {
temp = temp->right;
} else {
while (temp != dummy && !temp->rth) {
temp = temp->right;
}
if (temp != dummy) {
temp = temp->right;
}
}
}
}
// Function to display both In-order and Pre-order traversals
void display() {
if (root == NULL) {
cout << "\nTree is not created.";
return;
}
cout << "\nIn-order Traversal: ";
inorder();
cout << "\nPre-order Traversal: ";
preorder();
}
};
// 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 {
[Link]();
cout << "\nDo you want to enter more elements? (y/n): ";
cin >> ans;
} while (ans == 'y' || ans == 'Y');
break;
case 2:
[Link]();
break;
case 3:
cout << "\nExiting program.";
return 0;
default:
cout << "\nInvalid choice! Please try again.";
}
} while (ans == 'y' || ans == 'Y' || choice != 3);
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;
cout << "\nThe minimum spanning tree:\n";
select[0] = 1; // Starting vertex (0) is selected
for (int k = 0; k < nodes - 1; k++) {
min_dist = INFINITY;
// 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;
}
}
}
}
}
// Mark the selected vertex
select[v2] = 1;
cout << "Edge (" << v1 << ", " << v2 << ") and Weight = " << min_dist
<< endl;
total += min_dist;
}
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;
cout << "\nEnter the edge and weight of the graph:\n";
for (int i = 0; i < edges; i++) {
cout << "\nEnter the edge in the form of v1 v2 (e.g., 0 1): ";
cin >> v1 >> v2;
cout << "\nEnter corresponding weight: ";
cin >> length;
G[v1][v2] = G[v2][v1] = length; // Since the graph is undirected
}
}
int main() {
MST obj;
cout << "\nPrim's Algorithm\n";
obj.get_data();
[Link]();
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;
cout << "\nThe minimum spanning tree:\n";
select[0] = 1; // Starting vertex (0) is selected
for (int k = 0; k < nodes - 1; k++) {
min_dist = INFINITY;
// 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;
}
}
}
}
}
// Mark the selected vertex
select[v2] = 1;
cout << "Edge (" << v1 << ", " << v2 << ") and Weight = " << min_dist
<< endl;
total += min_dist;
}
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;
cout << "\nEnter the edge and weight of the graph:\n";
for (int i = 0; i < edges; i++) {
cout << "\nEnter the edge in the form of v1 v2 (e.g., 0 1): ";
cin >> v1 >> v2;
cout << "\nEnter corresponding weight: ";
cin >> length;
G[v1][v2] = G[v2][v1] = length; // Since the graph is undirected
}
}
int main() {
MST obj;
cout << "\nPrim's Algorithm\n";
obj.get_data();
[Link]();
return 0;
}
Kruskal's Algorithm:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
#define edge pair<int, int>
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
}
[Link](); // Clear the graph
[Link](); // Clear the MST
}
void Graph::AddWeightedEdge(int u, int v, int w) {
G.push_back(make_pair(w, edge(u, v))); // Add edge to the graph
}
// Find set using path compression
int Graph::find_set(int i) {
if (i == parent[i])
return i;
else
return parent[i] = find_set(parent[i]); // Path compression
}
// Union of two sets
void Graph::union_set(int u, int v) {
parent[u] = v; // Union by setting parent of one root to the other
}
// Kruskal's algorithm
void Graph::kruskal() {
int uRep, vRep;
sort([Link](), [Link]()); // Sort edges by weight
for (int i = 0; i < [Link](); i++) {
uRep = find_set(G[i].[Link]);
vRep = find_set(G[i].[Link]);
// If u and v belong to different sets, add this edge to the MST
if (uRep != vRep) {
T.push_back(G[i]); // Add edge to the tree
union_set(uRep, vRep); // Union the sets
}
}
}
// Print the Minimum Spanning Tree
void Graph::print() {
cout << "Edge : Weight\n";
for (int i = 0; i < [Link](); i++) {
cout << T[i].[Link] << " - " << T[i].[Link] << " : " <<
T[i].first << endl;
}
}
int main() {
Graph g(6);
[Link](0, 1, 4);
[Link](0, 2, 4);
[Link](1, 2, 2);
[Link](1, 0, 4);
[Link](2, 3, 3);
[Link](2, 1, 2);
[Link](3, 4, 3);
[Link](5, 2, 2);
[Link](5, 4, 3);
[Link]();
[Link]();
return 0;
}
PRACTICAL NO: 8
Graph: Shortest Path Algorithm
#include <iostream>
#define MAX 20
using namespace std;
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);
};
// Accept names of landmarks
void Graph::acceptVertices() {
int i = 0;
cout << "\nEnter Names of Landmarks:";
while (i < n) {
cout << "\nLandmark [" << i + 1 << "] : ";
cin >> v[i];
i++;
}
cout << "\n";
}
// Accept distances between landmarks
void Graph::acceptEdges() {
char v1, v2;
int cst;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
if (i == j) {
g[i][j] = 0;
continue;
}
cout << "\nDistance Between Landmark [" << v[i] << "][" << v[j] << "]
: ";
cin >> cst;
g[i][j] = g[j][i] = cst;
}
}
cout << "\n";
}
// Display adjacency matrix
void Graph::displayMatrix() {
cout << "\nAdjacency Matrix:\n";
for (int i = 0; i < n; i++) {
cout << "\t" << v[i];
}
cout << "\n";
for (int i = 0; i < n; i++) {
cout << v[i];
for (int j = 0; j < n; j++) {
cout << "\t" << g[i][j];
}
cout << "\n";
}
cout << "\n";
}
// Initialize Dijkstra's algorithm
void Graph::initializeDijkstra() {
for (int i = 0; i < n; i++) {
c[i] = 9999;
ch[i] = 0;
for (int j = 0; j < n; j++) {
str[i][j] = '-';
}
}
cout << "\n";
}
void Graph::initializeDijkstra(int i) {
for (int j = 0; j < n; j++) {
str[i][j] = '-';
}
}
// Dijkstra's algorithm for shortest path
void Graph::dijkstra(char s, char d, int f) {
initializeDijkstra();
int i = 0, j, k, min, cst;
while (v[i] != s) i++;
c[i] = 0;
k = 0;
str[i][k] = v[i];
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);
// Print minimum distance and path
cout << "\nShortest Distance from " << s << " to " << d << ": " << c[i] <<
"\nPath: ";
for (int m = 0; str[i][m] != '-'; m++) {
cout << str[i][m] << " ";
}
cout << "\n";
}
// Dijkstra's algorithm to find shortest distances from source to all destinations
void Graph::dijkstraToAllDestinations(char src) {
dijkstra(src, '-', 0);
cout << "\nShortest Distances from " << src << " to all Landmarks:\n";
for (int i = 0; i < n; i++) {
cout << "\nFrom " << src << " to " << v[i] << ": " << c[i] << "\nPath: ";
for (int j = 0; str[i][j] != '-'; j++) {
cout << str[i][j] << " ";
}
cout << "\n";
}
}
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:
[Link]();
break;
case 2:
[Link]();
break;
case 3:
[Link]();
break;
case 4:
cout << "\nEnter Source (Landmark to start from): ";
cin >> src;
cout << "\nEnter Destination (Landmark to reach): ";
cin >> dest;
[Link](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;
//Heapify function to maintain heap property.
//n is size of heap, i is every elements in array
void heapify(int arr[], int n, int i)
{
int largest = i; // Initialize largest as root Since we using 0 based indexing
int l = 2 * i + 1; // Find out left child = 2*i + 1
int r = 2 * i + 2; // Find out right child = 2*i + 2
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
if (largest != i) { //If largest is not root
swap(arr[i], arr[largest]); //Swap elements
heapify(arr, n, largest); // Recursively heapify affected sub-tree
}
}
//Function to sort an array using Heap Sort.
void heapSort(int arr[], int n)
{
for (int i = n / 2 - 1; i >= 0; i--)
// index of the last non-leaf node to 0. leaf node always consider as heap.
Because they dont have child node for comparision.
heapify(arr, n, i); //Call function maintain heap property
for (int i = n - 1; i >= 0; i--) { // One by one extract an element from heap
swap(arr[0], arr[i]); // Move current root to end
heapify(arr, i, 0); // call max heapify on the reduced heap
}
}
//Function to print array of size n
void printArray(int arr[], int n)
{
for (int i = 0; i < n; ++i) //Print all the elements in array in sorted form
cout << arr[i] << " ";
cout << "\n";
}
//Starting of the program
int main()
{
int arr[] = { 60 ,20 ,40 ,70, 30, 10}; //Unsorted elements in array
int n = sizeof(arr) / sizeof(arr[0]); //Calculate size of array
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
}
cout << "Before heapifying array is \n";
printArray(arr, n); //Unsorted array
heapSort(arr, n); //Call heapsort function for sorting
cout << "After heapifying array is \n";
printArray(arr, n); //Sorted array
return 0;
}
PRACTICAL NO: 10
File Organization
#include <iostream> //Header Files
#include <fstream>
using namespace std;
class student //Create Class
{
int roll_no; //Members of Class
char Name[30];
char Division[5];
char Address[50];
public: //Functions of Class
void accept();
void display();
int rollno()
{
return roll_no;
}
};
void student::accept() //Accept Students Data
{
cout<<"\nEnter Roll Number: ";
cin>>roll_no;
cout<<"\nEnter Name: ";
[Link]();
[Link](Name,30);
cout<<"\nEnter Division: ";
cin>>Division;
cout<<"\nEnter Address: ";
cin>>Address;
cout<<"\n";
}
void student::display() //Display Students
Data
{
cout<<"\n "<<roll_no<<"\t "<<Name<<" \t\t "<<Division<<"\t
"<<Address;
}
void create() //Create File
{
student s;
int n, i;
ofstream out("[Link]");
cout<<"\nHow many records do you want to enter?: ";
cin>>n;
for(i=0;i<n;i++)
{
[Link]();
[Link]((char *)&s,sizeof(s));
}
[Link]();
}
void search() //Search data in file
{
int n, flag=0;
cout<<"\nEnter Roll Number To Be Searched: ";
cin>>n;
ifstream infile("[Link]");
student s;
while([Link]((char *)&s,sizeof(s)))
{
if([Link]()==n)
{
cout<<"\nRecord Found\n";
cout<<"\nRoll Number Name
Division Address";
[Link]();
flag=1;
break;
}
}
if(flag==0)
{
cout<<"\nRecord Not Found.";
}
[Link]();
}
void display() //Display data in file
{
student s;
ifstream infile("[Link]");
while([Link]((char *)&s, sizeof(s)))
{
[Link]();
}
[Link]();
}
void add_record() //Add records in file
{
student s;
ofstream outfile("[Link]",ios::app);
[Link]();
[Link]((char *)&s,sizeof(s));
[Link]();
cout<<"Record Successfully Added.";
}
void delete_record() //Delete records from file
{
int n, flag=0;
cout<<"\nEnter Roll Number Whose Record To Be Deleted:";
cin>>n;
ifstream infile("[Link]"); // to read from source file
ofstream temp("[Link]"); // to write in destination
file(temporary file)
student s;
while([Link]((char *)&s, sizeof(s)))
{
if([Link]()!=n)
{
[Link]((char *)&s, sizeof(s));
}
else
{
flag=1;
cout<<"\nRecord Successfully Deleted.";
}
}
if(flag==0)
{
cout<<"\nRecord Not Found.";
}
[Link]();
[Link]();
remove("[Link]");
rename("[Link]","[Link]");
}
int main() //Starting function
{
int choice,roll_no,Marks;
char Name[30];
ofstream out("[Link]");
[Link]();
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;
}