0% found this document useful (0 votes)
12 views46 pages

Name

name

Uploaded by

Suraj Mhaske
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)
12 views46 pages

Name

name

Uploaded by

Suraj Mhaske
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/ 46

Name :- Mhaske Suraj Machhindra

Roll-No :- 207B073

Asingnment No :- 1

#include <iostream>

using namespace std;

struct Student {

int roll_no;

string name;

float sgpa;

};

Student students[] = {

{101, "Alice", 8.5}, {105, "Bob", 7.2}, {103, "Charlie", 9.1},

{104, "David", 8.7}, {102, "Eve", 6.8}, {110, "Frank", 9.2},

{109, "Grace", 7.5}, {108, "Heidi", 8.3}, {107, "Ivan", 8.9},

{106, "Judy", 6.9}, {111, "Mallory", 8.0}, {113, "Niaj", 7.9},

{115, "Oscar", 7.0}, {112, "Peggy", 9.1}, {114, "Sybil", 6.7}

};

int n = 15; // Number of students

void printStudents(Student students[], int n) {

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

cout << "Roll No: " << students[i].roll_no << ", Name: "

<< students[i].name << ", SGPA: " << students[i].sgpa << endl;

}}

// a) Sort by Roll Number using Bubble Sort

void bubbleSortByRollNo(Student students[], int n) {

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

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

if (students[j].roll_no > students[j + 1].roll_no) {

swap(students[j], students[j + 1]); } }}}

// b) Sort Alphabetically by Name using Insertion Sort

void insertionSortByName(Student students[], int n) {


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

Student key = students[i];

int j = i - 1;

while (j >= 0 && students[j].name > key.name) {

students[j + 1] = students[j];

j = j - 1; }

students[j + 1] = key; }}

// c) Find Top 10 Students by SGPA using Quick Sort

int partition(Student students[], int low, int high) {

float pivot = students[high].sgpa;

int i = low - 1;

for (int j = low; j < high; j++) {

if (students[j].sgpa > pivot) { // Descending order

i++;

swap(students[i], students[j]); } }

swap(students[i + 1], students[high]);

return i + 1;}

void quickSortBySGPA(Student students[], int low, int high) {

if (low < high) {

int pi = partition(students, low, high);

quickSortBySGPA(students, low, pi - 1);

quickSortBySGPA(students, pi + 1, high); }}

void printTop10Students(Student students[], int n) {

quickSortBySGPA(students, 0, n - 1);

cout << "Top 10 students by SGPA:\n";

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

cout << "Roll No: " << students[i].roll_no << ", Name: "

<< students[i].name << ", SGPA: " << students[i].sgpa << endl; }}

// d) Search students by SGPA

void searchBySGPA(Student students[], int n, float sgpa) {

bool found = false;


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

if (students[i].sgpa == sgpa) {

cout << "Roll No: " << students[i].roll_no << ", Name: "

<< students[i].name << ", SGPA: " << students[i].sgpa << endl;

found = true; }}

if (!found) cout << "No students found with SGPA " << sgpa << endl;}

// e) Search a particular student by Name using Binary Search

void binarySearchByName(Student students[], int n, string name) {

insertionSortByName(students, n); // Ensure students are sorted by name first

int left = 0, right = n - 1;

bool found = false;

while (left <= right) {

int mid = left + (right - left) / 2;

if (students[mid].name == name) {

cout << "Roll No: " << students[mid].roll_no << ", Name: "

<< students[mid].name << ", SGPA: " << students[mid].sgpa << endl;

found = true;

break;

} else if (students[mid].name < name) {

left = mid + 1;

} else {

right = mid - 1; } }

if (!found) cout << "Student with name " << name << " not found." << endl;

int main() {

// a) Sort by Roll Number

cout << "Sorted by Roll Number:\n";

bubbleSortByRollNo(students, n);

printStudents(students, n);

// b) Sort by Name

cout << "\nSorted by Name:\n";


insertionSortByName(students, n);

printStudents(students, n);

// c) Top 10 Students by SGPA

cout << "\nTop 10 Students by SGPA:\n";

printTop10Students(students, n);

// d) Search by SGPA

float sgpaToSearch;

cout << "\nEnter SGPA to search for: ";

cin >> sgpaToSearch;

searchBySGPA(students, n,
sgpaToSearch);

// e) Search by Name using


Binary Search

string nameToSearch;

cout << "\nEnter name to


search for: ";

cin >> nameToSearch;

binarySearchByName(students,
n, nameToSearch);

return 0;

}
Name :- Mhaske Suraj Machhindra

Roll-No :- 207B073

Asingnment No :- 2

#include <iostream>

using namespace std;

struct Node {

char data;

Node* next;

};

class Stack {

private:

Node* top;

public:

Stack() { top = nullptr; }

void push(char value) {

Node* newNode = new Node();

newNode->data = value;

newNode->next = top;

top = newNode; }

char pop() {

if (top == nullptr) {

cout << "Stack Underflow" << endl;

return -1; }

char value = top->data;

Node* temp = top;

top = top->next;

delete temp;

return value; }

char peek() {

if (top != nullptr)

return top->data;
else

return -1; }

bool isEmpty() {

return top == nullptr; }};

// Function to check if a character is an operator

bool isOperator(char c) {

return (c == '+' || c == '-' || c == '*' || c == '/' || c == '^');

// Function to determine precedence of operators

int precedence(char op) {

if (op == '^') return 3;

if (op == '*' || op == '/') return 2;

if (op == '+' || op == '-') return 1;

return 0;}

// Infix to Postfix conversion

string infixToPostfix(string infix) {

Stack stack;

string postfix = "";

for (char ch : infix) {

if (isalnum(ch)) {

postfix += ch;

} else if (ch == '(') {

stack.push(ch);

} else if (ch == ')') {

while (!stack.isEmpty() && stack.peek() != '(') {

postfix += stack.pop();}

stack.pop(); // Remove '('

} else if (isOperator(ch)) {

while (!stack.isEmpty() && precedence(stack.peek()) >= precedence(ch)) {

postfix += stack.pop();

}
stack.push(ch); } }

while (!stack.isEmpty()) {

postfix += stack.pop();}

return postfix;}

// Infix to Prefix conversion

string infixToPrefix(string infix) {

reverse(infix.begin(), infix.end());

for (char &ch : infix) {

if (ch == '(') ch = ')';

else if (ch == ')') ch = '('; }

string postfix = infixToPostfix(infix);

reverse(postfix.begin(), postfix.end());

return postfix;}

int evaluatePostfix(string postfix) {

stack<int> stack;

for (char ch : postfix) {

if (isdigit(ch)) {

stack.push(ch - '0');

} else if (isOperator(ch)) {

int operand2 = stack.top(); stack.pop();

int operand1 = stack.top(); stack.pop();

switch (ch) {

case '+': stack.push(operand1 + operand2); break;

case '-': stack.push(operand1 - operand2); break;

case '*': stack.push(operand1 * operand2); break;

case '/': stack.push(operand1 / operand2); break;

case '^': stack.push(pow(operand1, operand2)); break; }}}

return stack.top();}

int evaluatePrefix(string prefix) {

stack<int> stack;

reverse(prefix.begin(), prefix.end());
for (char ch : prefix) {

if (isdigit(ch)) {

stack.push(ch - '0');

} else if (isOperator(ch)) {

int operand1 = stack.top(); stack.pop();

int operand2 = stack.top(); stack.pop();

switch (ch) {

case '+': stack.push(operand1 + operand2); break;

case '-': stack.push(operand1 - operand2); break;

case '*': stack.push(operand1 * operand2); break;

case '/': stack.push(operand1 / operand2); break;

case '^': stack.push(pow(operand1, operand2)); break; }}}

return stack.top();}

int main() {

string infix;

cout << "Enter infix expression: ";

cin >> infix;

string postfix = infixToPostfix(infix);

cout << "Postfix Expression: " << postfix << endl;

cout << "Evaluated Postfix Result: " <<


evaluatePostfix(postfix) << endl;

string prefix = infixToPrefix(infix);

cout << "Prefix Expression: " << prefix


<< endl;

cout << "Evaluated Prefix Result: " <<


evaluatePrefix(prefix) << endl;

return 0;

}
Name :- Mhaske Suraj Machhindra

Roll-No :- 207B073

Asingnment No :- 3

#include <iostream>

using namespace std;

int cqueue[5]; // Circular queue array

int front = -1, rear = -1, n = 5; // Queue size = 5

void insertCQ(int val) {

if ((front == 0 && rear == n - 1) || (front == rear + 1)) {

cout << "Queue Overflow\n";

return;

if (front == -1) { // Initial insertion

front = 0;

rear = 0;

} else {

if (rear == n - 1)

rear = 0; // Wrap around

else

rear = rear + 1;

cqueue[rear] = val;

void deleteCQ() {

if (front == -1) {

cout << "Queue Underflow\n";

return;

}
cout << "Element deleted from queue is : " << cqueue[front] << endl;

if (front == rear) { // Only one element was in the queue

front = -1;

rear = -1;

} else {

if (front == n - 1)

front = 0; // Wrap around

else

front = front + 1;

void displayCQ_forward() {

if (front == -1) {

cout << "Queue is empty\n";

return;

cout << "Queue elements are :\n";

if (front <= rear) {

for (int i = front; i <= rear; i++) {

cout << cqueue[i] << " ";

} else {

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

cout << cqueue[i] << " ";

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

cout << cqueue[i] << " ";

}}

cout << endl;

void displayCQ_reverse() {
if (front == -1) {

cout << "Queue is empty\n";

return;

cout << "Queue elements in reverse are:\n";

if (front <= rear) {

for (int i = rear; i >= front; i--) {

cout << cqueue[i] << " ";

} else {

for (int i = rear; i >= 0; i--) {

cout << cqueue[i] << " ";

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

cout << cqueue[i] << " ";

}}

cout << endl;

int main() {

int ch, val;

cout << "1) Insert\n";

cout << "2) Delete\n";

cout << "3) Display forward\n";

cout << "4) Display reverse\n";

cout << "5) Exit\n";

do {

cout << "Enter choice: ";

cin >> ch;

switch (ch) {

case 1:
cout << "Input for insertion: ";

cin >> val;

insertCQ(val);

break;

case 2:

deleteCQ();

break;

case 3:

displayCQ_forward();

break;

case 4:

displayCQ_reverse();

break;

case 5:

cout << "Exit\n";

break;

default:

cout << "Incorrect!\n";

} while (ch != 5);

return 0;

}
Name :- Mhaske Suraj Machhindra

Roll-No :- 207B073

Asingnment No :- 4

#include<iostream>

using namespace std;

typedef struct node

char data;

struct node *left;

struct node *right;

}node;

typedef struct stacknode

node* data;

struct stacknode *next;

}stacknode;

class stack

stacknode *top;

public:

stack()

top=NULL;}

node* topp()

return (top->data);}

int isempty()

if(top==NULL)

return 1;

return 0;
}

void push(node* a){

stacknode *p;

p=new stacknode();

p->data=a;

p->next=top;

top=p;}

node* pop(){ stacknode *p;

node* x;

x=top->data;

p=top;

top=top->next;

return x;}};

node* create_pre(char prefix[10]);

node* create_post(char postfix[10]);

void inorder_non_recursive(node *t);

void inorder(node *p);

void preorder(node *p);

void postorder(node *p);

void preorder_non_recursive(node *t);

void postorder_non_recursion(node *t);

node* create_post(char postfix[10])

{node *p;

stack s;

for(int i=0;postfix[i]!='\0';i++)

char token=postfix[i];

if(isalnum(token))

p=new node();

p->data=token;
p->left=NULL;

p->right=NULL;

s.push(p); }

else{

p=new node();

p->data=token;

p->right=s.pop();

p->left=s.pop();

s.push(p); }}

return s.pop();}

node* create_pre(char prefix[10])

{node *p;

stack s;

int i;

for(i=0;prefix[i]!='\0';i++)

{}

i=i-1;

for(;i>=0;i--){

char token=prefix[i];

if(isalnum(token)){

p=new node();

p->data=token;

p->left=NULL;

p->right=NULL;

s.push(p);

} else{

p=new node();

p->data=token;

p->left=s.pop();

p->right=s.pop();

s.push(p); }}
return s.pop();}

int main(){

node *r=NULL,*r1;

char postfix[10],prefix[10];

int x;

int ch,choice;

do

cout<<"\n\t****TREE OPERATIONS****\n1.Construct tree from postfix expression/ prefix


expression\n2.Inorder traversal\n3.Preorder traversal\n4.Postorder traversal\n5.Exit\nEnter your
choice=";

cin>>ch;

switch(ch)

case 1:cout<<"ENTER CHOICE:\n1.Postfix expression\n2.Prefix expression\nchoice=";

cin>>choice;

if(choice==1){

cout<<"\nEnter postfix expression=";

cin>>postfix;

r=create_post(postfix);}

else{

cout<<"\nEnter prefix expression=";

cin>>prefix;

r=create_pre(prefix);}

cout<<"\n\nTree created successfully";

break;

case 2:cout<<"\nInorder Traversal of tree:\n";

inorder(r);

cout<<"\n Without recursion:\t";

inorder_non_recursive(r);

break;

case 3:cout<<"\nPreorder Traversal of tree:\n";


preorder(r);

cout<<"\npreorder traversal without recursion:\t";

preorder_non_recursive(r);

break;

case 4:cout<<"\nPostorder Traversal of tree:\n";

postorder(r);

cout<<"\npostorder traversal without recursion";

postorder_non_recursion(r);

break;}

}while(ch!=5);

return 0;}

void inorder(node *p){

if(p!=NULL){

inorder(p->left);

cout<<p->data;

inorder(p->right); }}

void preorder(node *p){

if(p!=NULL){

cout<<p->data;

preorder(p->left);

preorder(p->right); }}

void postorder(node *p){

if(p!=NULL){

postorder(p->left);

postorder(p->right);

cout<<p->data; }}

void inorder_non_recursive(node *t){

stack s;

while(t!=NULL){

s.push(t);
t=t->left;}

while(s.isempty()!=1){

t=s.pop();

cout<<t->data;

t=t->right;

while(t!=NULL){

s.push(t);

t=t->left;}}}

void preorder_non_recursive(node *t){

stack s;

while(t!=NULL){

cout<<t->data;

s.push(t);

t=t->left;}

while(s.isempty()!=1){

t=s.pop();

t=t->right;

while(t!=NULL){

cout<<t->data;

s.push(t);

t=t->left;}}}

void postorder_non_recursion(node *t)

{stack s,s1;

node *t1;

while(t!=NULL){

s.push(t);

s1.push(NULL);

t=t->left; }

while(s.isempty()!=1){

t=s.pop();

t1=s1.pop();
if(t1==NULL){

s.push(t);

s1.push((node *)1);

t=t->right;

while(t!=NULL){

s.push(t);

s1.push(NULL);

t=t->left; }}

else{

cout<<t->data; }}
Name :- Mhaske Suraj Machhindra

Roll-No :- 207B073

Asingnment No :- 5

#include<iostream>

using namespace std;

typedef struct tnode {

int data;

struct tnode*left;

struct tnode*right;

}tnode;

typedef struct node {

struct tnode*x;

struct node *next;

}node;

class queue {

node *front,*rear;

public:

queue() {

front=NULL;

rear=NULL; }

int isempty() {

if(front==NULL)

return 1;

return 0; }

void enque(tnode *i) {

node *p;

p=new node();

p->x=i;

p->next=NULL;

if(front==NULL) {

front=p;
rear=p; }

else {

rear->next=p;

rear=rear->next; } }

tnode *deque() {

node *p;

tnode *temp;

p=front;

temp=front->x;

if(front==rear) {

front=NULL;

rear=NULL; }

else {

front=front->next; }

delete p;

return temp;

} };

class tree{

tnode *t;

public:

tree(){

t=NULL; }

tnode *insert(int x) {

tnode *p,*q,*r;

p=new tnode();

p->data=x;

p->left=NULL;

p->right=NULL;

if(t==NULL)

return p;
q=t;

r=t;

while(r!=NULL) {

q=r;

if(x<r->data)

r=r->left;

else

r=r->right; }

if(x<q->data)

q->left=p;

else

q->right=p;

return t; }

tnode *create() {

int n,i,key;

cout<<" \n Enter the number of nodes - ";

cin>>n;

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

cout<<" \n Enter the data -";

cin>>key;

t=insert(key); }

return t; }

void inorder(tnode *t) {

if(t!=NULL) {

inorder(t->left);

cout<<"\t"<<t->data;

inorder(t->right); } }

tnode* search(int key) {

tnode *s=t;

while(s!=NULL) {

if(s->data==key)
return t;

else if(s->data<key)

s=s->right;

else

s=s->left; }

return NULL; }

tnode *find_min(tnode *r) {

while(r->left!=NULL) {

r=r->left; }

return r; }

tnode *del(tnode *t,int key) {

tnode *temp;

if(t==NULL) {

return NULL; }

if(key<t->data) {

t->left=del(t->left,key);

return t; }

if(key>t->data) {

t->right=del(t->right,key);

return t; }

//element found

//no child

if(t->left==NULL&t->right==NULL) {

temp=t;

delete temp;

return NULL; }

//one child

if(t->left!=NULL&&t->right==NULL) {

temp=t;

t=t->left;

delete temp;
return t; }

if(t->left==NULL&&t->right!=NULL) {

temp=t;

t=t->right;

delete temp;

return t; }

//both child present

temp=find_min(t->right);

t->data=temp->data;

t->right=del(t->right,temp->data);

return t; }

tnode *mirror(tnode *t) {

tnode *temp;

if(t==NULL) {

return NULL; }

temp=t->left;

t->left=mirror(t->right);

t->right=mirror(temp);

return t; }

tnode* copy(tnode *T) {

tnode *P;

P=NULL;

if(T!=NULL) {

P=new tnode();

P->data=T->data;

P->left=copy(T->left);

P->right=copy(T->right); }

return P; }

int height(tnode *T) {

int hl,hr;

if(T==NULL)
return 0;

if(T->left==NULL && T->right==NULL)

return 0;

hl=height(T->left);

hr=height(T->right);

if(hl>hr)

return 1+hl;

else

return 1+hr; }

void leaf(tnode *T) {

if(T==NULL)

return ;

if(T->left==NULL && T->right==NULL)

{ cout<<"\t"<<T->data;

leaf(T->left);

leaf(T->right); }

void parent(tnode *T) {

if(T==NULL)

return ;

if(T->left!=NULL && T->right==NULL) {

cout<<"\t"<<T->data;

cout<<"\t"<<T->left->data;

cout<<"\n"; }

if(T->left==NULL && T->right!=NULL) {

cout<<"\t"<<T->data;

cout<<"\t"<<T->right->data;

cout<<"\n"; }

if(T->left!=NULL && T->right!=NULL) {

cout<<"\t"<<T->data;

cout<<"\t"<<T->left->data<<"\t"<<T->right->data;
cout<<"\n"; }

parent(T->left);

parent(T->right); }

void level_wise() {

tnode *t1;

queue q1;

if(t==NULL)

return;

q1.enque(t);

cout<<"\n"<<t->data;

while(q1.isempty()!=1) {

cout<<"\n";

queue q2;

while(q1.isempty()!=1) {

t1=q1.deque();

if(t1->left!=NULL) {

q2.enque(t1->left);

cout<<" "<<t1->left->data; }

if(t1->right!=NULL) {

q2.enque(t1->right);

cout<<" "<<t1->right->data; } }

q1=q2; }}};

int main(){

int choice,key, cnt;

tnode *root,*result, *rt;

tree t;

do {

cout<<" \n Main menu "

"\n 1.Create "

"\n 2.Insert "

"\n 3.Display "


"\n 4.Search "

"\n 5.Delete "

"\n 6.Mirror image "

"\n 7.create copy "

"\n 8.Find Depth "

"\n 9.Minimum "

"\n 10.Display Tree Level-wise "

"\n 11.Display Leaf nodes "

"\n 12.Display parent node with child nodes "

"\n 13.Exit \n Enter your choice - ";

cin>>choice;

switch(choice) {

case 1:root=t.create(); break;

case 2:cout<<"\n Enter the number to insert - ";

cin>>key;

root=t.insert(key); break;

case 3:cout<<"Binary tree :-";

t.inorder(root); break;

case 4:cout<<" \n Enter the node to search -";

cin>>key;

result=t.search(key);

if(result==NULL) {

cout<<"\n Element "<<key<<" not present"<<endl; }

else{

cout<<"\n Element "<<key<<" is present"<<endl; }

break;

case 5:cout<<"\n Enter the node to delete -";

cin>>key;

result=t.del(root,key);

root=result;

cout<<"\n Element deleted successfully!!"<<endl;


break;

case 6:root=t.mirror(root);

cout<<"\n Mirror image of the binary tree is :-"<<endl;

t.inorder(root);

break;

break;

case 7: cout<<"\n Copied tree - ";

rt=t.copy(root);

t.inorder(rt); break;

case 8:cnt=t.height(root);

cout<<"\n Height of tree -"<<cnt;

break;

case 9:result=t.find_min(root);

cout<<"\n Minimum is "<<result-


>data<<endl;

break;

case 10:cout <<"\n Level wise display :-


"<<endl;

t.level_wise();

break;

case 11:cout <<"\n Leaf nodes are :-


"<<endl;

t.leaf(root);

break;

case 12:cout <<"\n Parent node with child


nodes are :-"<<endl;

t.parent(root);

break;

case 13:return 0;

default:cout<<"\n Invalid choice !! Please enter your choice again."<<endl;

}while(choice!=13); }
Name :- Mhaske Suraj Machhindra

Roll-No :- 207B073

Asingnment No :- 6

#include <iostream>

using namespace std;

// Node structure for Threaded Binary Tree

struct Node {

int data;

Node* left;

Node* right;

bool isThreaded; // True if right points to the in-order successor

};

// Function to create a new node

Node* createNode(int data) {

Node* node = new Node();

node->data = data;

node->left = node->right = nullptr;

node->isThreaded = false;

return node; }

// Function to insert a node in the Threaded Binary Tree

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

Node* node = createNode(key);

if (!root) return node;

Node* parent = nullptr;

Node* current = root;

// Find the appropriate position for the new node

while (current) {

parent = current;

if (key < current->data) {

if (current->left)

current = current->left;
else

break;

} else {

if (!current->isThreaded)

current = current->right;

else

break; } }

// Insert the new node as the left or right child of parent

if (key < parent->data) {

parent->left = node;

node->right = parent;

node->isThreaded = true;

} else {

node->right = parent->right;

node->isThreaded = true;

parent->right = node;

parent->isThreaded = false;

return root; }

// In-order traversal of Threaded Binary Tree

void inorder(Node* root) {

Node* current = root;

// Move to the leftmost node

while (current && current->left) {

current = current->left; }

// Traverse the tree using threads

while (current) {

cout << current->data << " ";

if (current->isThreaded) {

current = current->right;

} else {
current = current->right;

while (current && current->left) {

current = current->left; } } }}

// Pre-order traversal of Threaded Binary Tree

void preorder(Node* root) {

Node* current = root;

while (current) {

cout << current->data << " ";

// Go to the left child if exists

if (current->left) {

current = current->left;

} else {

// Otherwise, follow threads to find the next node

while (current && current->isThreaded) {

current = current->right;

if (current) {

current = current->right; } } }}

// Main function to test the implementation

int main() {

Node* root = nullptr;

// Insert nodes into the Threaded Binary Tree

root = insert(root, 20);

root = insert(root, 10);

root = insert(root, 30);

root = insert(root, 5);

root = insert(root, 15);

root = insert(root, 25);

root = insert(root, 35);

cout << "In-order Traversal: ";

inorder(root);
cout << endl;

cout << "Pre-order Traversal: ";

preorder(root);

cout << endl;

return 0;

}
Name :- Mhaske Suraj Machhindra

Roll-No :- 207B073

Asingnment No :- 7

#include <iostream>

using namespace std;

// Structure to represent an edge in the graph

struct Edge {

int src, dest, weight;

bool operator<(const Edge& other) const {

return weight < other.weight; }};

// Graph class to represent a weighted undirected graph

class Graph {

int V; // Number of vertices

vector<vector<pair<int, int>>> adjList; // Adjacency list for Prim's Algorithm

vector<Edge> edges; // List of all edges for Kruskal's Algorithm

public:

Graph(int V) : V(V) {

adjList.resize(V);

// Function to add an edge to the graph

void addEdge(int u, int v, int weight) {

adjList[u].push_back({v, weight});

adjList[v].push_back({u, weight});

edges.push_back({u, v, weight});

// Function to perform Kruskal's Algorithm for MST

void kruskalMST() {

vector<Edge> mst; // Stores edges of MST

sort(edges.begin(), edges.end()); // Sort edges by weight

// Disjoint Set to manage cycle detection

vector<int> parent(V);
for (int i = 0; i < V; ++i) parent[i] = i;

// Function to find the root of a set

function<int(int)> find = [&](int v) {

if (v == parent[v]) return v;

return parent[v] = find(parent[v]);

// Function to union two sets

auto unionSets = [&](int u, int v) {

int rootU = find(u);

int rootV = find(v);

if (rootU != rootV) parent[rootU] = rootV;

};

for (const Edge& edge : edges) {

int rootU = find(edge.src);

int rootV = find(edge.dest);

// If they belong to different sets, include this edge in MST

if (rootU != rootV) {

mst.push_back(edge);

unionSets(edge.src, edge.dest);

// Print MST edges and total weight

cout << "Kruskal's MST:" << endl;

int totalWeight = 0;

for (const Edge& e : mst) {

cout << e.src << " - " << e.dest << " : " << e.weight << endl;

totalWeight += e.weight;

cout << "Total Weight of MST: " << totalWeight << endl;

}
// Function to perform Prim's Algorithm for MST

void primMST() {

vector<int> key(V, INT_MAX); // Key values used to pick minimum weight edge

vector<int> parent(V, -1); // Stores the parent of each vertex in MST

vector<bool> inMST(V, false); // Track vertices included in MST

key[0] = 0; // Start from the 0th vertex

priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> pq; // Min-heap

pq.push({0, 0}); // {key, vertex}

while (!pq.empty()) {

int u = pq.top().second; // Extract vertex with minimum key value

pq.pop();

inMST[u] = true; // Mark this vertex as part of MST

// Update key value and parent index of adjacent vertices

for (auto &[v, weight] : adjList[u]) {

if (!inMST[v] && weight < key[v]) {

key[v] = weight;

pq.push({key[v], v});

parent[v] = u; }} }

// Print MST edges and total weight

cout << "Prim's MST:" << endl;

int totalWeight = 0;

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

if (parent[i] != -1) {

cout << parent[i] << " - " << i << " : " << key[i] << endl;

totalWeight += key[i]; } }

cout << "Total Weight of MST: " << totalWeight << endl; }};

int main() {

int V = 6; // Assuming there are 6 departments/buildings in the campus

Graph g(V);

// Adding edges (distances between departments/buildings)

g.addEdge(0, 1, 10);
g.addEdge(0, 2, 15);

g.addEdge(1, 2, 5);

g.addEdge(1, 3, 20);

g.addEdge(2, 4, 25);

g.addEdge(3, 4, 30);

g.addEdge(3, 5, 35);

g.addEdge(4, 5, 10);

cout << "Minimum Spanning Tree using Kruskal's Algorithm:" << endl;

g.kruskalMST();

cout << endl;

cout << "Minimum Spanning Tree using Prim's Algorithm:" << endl;

g.primMST();

return 0;

/* ************Output**************************

Minimum Spanning Tree using Kruskal's Algorithm:

1-2:5

0 - 1 : 10

4 - 5 : 10

2 - 4 : 25

3 - 4 : 30

Total Weight of MST: 80

Minimum Spanning Tree using Prim's Algorithm:

0 - 1 : 10

1-2:5

2 - 4 : 25

4 - 5 : 10

3 - 4 : 30

Total Weight of MST: 80

******************************************** */
Name :- Mhaske Suraj Machhindra

Roll-No :- 207B073

Asingnment No :- 8

#include <iostream>

using namespace std;

// Graph class to represent a weighted undirected graph

class Graph {

int V; // Number of vertices

vector<vector<pair<int, int>>> adjList; // Adjacency list where each pair contains (destination,
weight)

public:

Graph(int V) : V(V) {

adjList.resize(V);

// Function to add an edge to the graph

void addEdge(int u, int v, int weight) {

adjList[u].push_back({v, weight});

adjList[v].push_back({u, weight}); // Comment this line if the graph is directed

// Function to perform Dijkstra's Algorithm from a single source

void dijkstra(int src) {

vector<int> dist(V, INT_MAX); // Distance from source to each vertex

dist[src] = 0;

// Min-heap priority queue to store vertices and their distances from the source

priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> pq;

pq.push({0, src}); // {distance, vertex}

while (!pq.empty()) {

int u = pq.top().second;

int uDist = pq.top().first;

pq.pop();
// If the popped vertex distance is greater than the current known distance, continue

if (uDist > dist[u]) continue;

// Traverse through all adjacent vertices of u

for (auto &[v, weight] : adjList[u]) {

if (dist[u] + weight < dist[v]) {

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

pq.push({dist[v], v});

} }}

// Display shortest distances from the source to each vertex

cout << "Shortest distances from source " << src << " to all other landmarks:" << endl;

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

cout << "Landmark " << src << " to Landmark " << i << " : ";

if (dist[i] == INT_MAX) {

cout << "Unreachable" << endl;

} else {

cout << dist[i] << endl;

}} }};

int main() {

int V = 5; // Assume 5 landmarks in the city

Graph g(V);

// Adding edges (distances between landmarks)

g.addEdge(0, 1, 10);

g.addEdge(0, 4, 3);

g.addEdge(1, 2, 2);

g.addEdge(1, 4, 4);

g.addEdge(2, 3, 9);

g.addEdge(3, 4, 7);

g.addEdge(4, 2, 1);

int source = 0; // Starting point (e.g., landmark 0)

g.dijkstra(source);

return 0;
}

/* ********************************Output***********************

Shortest distances from source 0 to all other landmarks:

Landmark 0 to Landmark 0 : 0

Landmark 0 to Landmark 1 : 7

Landmark 0 to Landmark 2 : 6

Landmark 0 to Landmark 3 : 15

Landmark 0 to Landmark 4 : 3

*************************************************** */
Name :- Mhaske Suraj Machhindra

Roll-No :- 207B073

Asingnment No :- 9

#include <iostream>

using namespace std;

// Function to heapify a subtree with the root at index `i`

void heapify(vector<int>& arr, int n, int i) {

int largest = i; // Initialize the largest as root

int left = 2 * i + 1; // Left child

int right = 2 * i + 2; // Right child

// If left child is larger than root

if (left < n && arr[left] > arr[largest])

largest = left;

// If right child is larger than largest so far

if (right < n && arr[right] > arr[largest])

largest = right;

// If largest is not root

if (largest != i) {

swap(arr[i], arr[largest]); // Swap root with the largest element

heapify(arr, n, largest); // Recursively heapify the affected subtree

// Function to perform heap sort

void heapSort(vector<int>& arr) {

int n = arr.size();

// Build a max heap

for (int i = n / 2 - 1; i >= 0; i--)

heapify(arr, n, i);

// One by one extract elements from heap

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

swap(arr[0], arr[i]); // Move the current root to the end


heapify(arr, i, 0); // Call heapify on the reduced heap

}}

// Function to print an array

void printArray(const vector<int>& arr) {

for (int i : arr)

cout << i << " ";

cout << endl;

int main() {

vector<int> arr = {12, 11, 13, 5, 6, 7};

cout << "Original array: ";

printArray(arr);

heapSort(arr);

cout << "Sorted array: ";

printArray(arr);

return 0;

}
Name :- Mhaske Suraj Machhindra

Roll-No :- 207B073

Asingnment No :- 10

#include <iostream>

using namespace std;

// Structure to represent a student record

struct Student {

int rollNumber;

string name;

string division;

string address;

};

// Function to add a student record to the file

void addStudent() {

Student student;

cout << "Enter Roll Number: ";

cin >> student.rollNumber;

cout << "Enter Name: ";

cin.ignore(); // To clear the newline character from the input buffer

getline(cin, student.name);

cout << "Enter Division: ";

getline(cin, student.division);

cout << "Enter Address: ";

getline(cin, student.address);

ofstream file("students.txt", ios::app); // Append mode

if (file.is_open()) {

file << student.rollNumber << " " << student.name << " " << student.division << " " <<
student.address << endl;

cout << "Student record added successfully.\n";

file.close();

} else {
cout << "Unable to open file to add student record.\n"; } }

// Function to display a specific student's record

void displayStudent() {

int rollNumber;

cout << "Enter Roll Number to search: ";

cin >> rollNumber;

ifstream file("students.txt");

if (file.is_open()) {

Student student;

bool found = false;

while (file >> student.rollNumber) {

file.ignore(); // Ignore the space before the name

getline(file, student.name, ' ');

getline(file, student.division, ' ');

getline(file, student.address);

if (student.rollNumber == rollNumber) {

cout << "\nStudent Found:\n";

cout << "Roll Number: " << student.rollNumber << "\n";

cout << "Name: " << student.name << "\n";

cout << "Division: " << student.division << "\n";

cout << "Address: " << student.address << "\n";

found = true;

break; }}

file.close();

if (!found) {

cout << "Student with Roll Number " << rollNumber << " not found.\n"; }

} else {

cout << "Unable to open file to search for student record.\n"; }}

// Function to delete a student record from the file

void deleteStudent() {

int rollNumber;
cout << "Enter Roll Number to delete: ";

cin >> rollNumber;

ifstream file("students.txt");

ofstream tempFile("temp.txt");

bool found = false;

if (file.is_open() && tempFile.is_open()) {

Student student;

while (file >> student.rollNumber) {

file.ignore();

getline(file, student.name, ' ');

getline(file, student.division, ' ');

getline(file, student.address);

// Copy all records except the one to be deleted

if (student.rollNumber == rollNumber) {

found = true;

cout << "Student with Roll Number " << rollNumber << " deleted.\n";

} else {

tempFile << student.rollNumber << " " << student.name << " " << student.division << " "
<< student.address << endl; } }

file.close();

tempFile.close();

// Delete original file and rename temp file

remove("students.txt");

rename("temp.txt", "students.txt");

if (!found) {

cout << "Student with Roll Number " << rollNumber << " not found.\n"; }

} else {

cout << "Unable to open file to delete student record.\n"; }}

// Function to display all student records

void displayAllStudents() {

ifstream file("students.txt");
if (file.is_open()) {

Student student;

cout << "\nAll Student Records:\n";

while (file >> student.rollNumber) {

file.ignore();

getline(file, student.name, ' ');

getline(file, student.division, ' ');

getline(file, student.address);

cout << "Roll Number: " << student.rollNumber << "\n";

cout << "Name: " << student.name << "\n";

cout << "Division: " << student.division << "\n";

cout << "Address: " << student.address << "\n";

cout << "----------------------\n"; }

file.close();

} else {

cout << "Unable to open file to display student records.\n"; }}

int main() {

int choice;

do {

cout << "\n--- Student Database Menu ---\n";

cout << "1. Add Student\n";

cout << "2. Display Student\n";

cout << "3. Delete Student\n";

cout << "4. Display All Students\n";

cout << "5. Exit\n";

cout << "Enter your choice: ";

cin >> choice;

switch (choice) {

case 1:

addStudent();

break;
case 2:

displayStudent();

break;

case 3:

deleteStudent();

break;

case 4:

displayAllStudents();

break;

case 5:

cout << "Exiting program.\n";

break;

default:

cout << "Invalid choice.


Please try again.\n";

} while (choice != 5);

return 0;

You might also like