0% found this document useful (0 votes)
12 views

all dsa program

The document contains multiple C++ programs demonstrating various data structures and algorithms, including sparse matrices, polynomial evaluation, linked lists, and circular linked lists. Each section provides implementations for insertion, deletion, display, and other operations on these data structures. The programs are designed to be interactive, allowing user input to manipulate the data structures in real-time.

Uploaded by

AKNaved Shaikh
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 views

all dsa program

The document contains multiple C++ programs demonstrating various data structures and algorithms, including sparse matrices, polynomial evaluation, linked lists, and circular linked lists. Each section provides implementations for insertion, deletion, display, and other operations on these data structures. The programs are designed to be interactive, allowing user input to manipulate the data structures in real-time.

Uploaded by

AKNaved Shaikh
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/ 35

1a

#include <iostream>
using namespace std;

class sparse_matrix {
const static int max = 100;
int **data;
int row, col;
int len;

public:
sparse_matrix(int r, int c) {
row = r;
col = c;
len = 0;
data = new int *[max];
for (int i = 0; i < max; i++) {
data[i] = new int[3]; // 3 for row, column, and value
}
}

void insert(int r, int c, int val) {


if (r > row || c > col || len >= max) {
cout << "wrong entry" << endl;
} else {
data[len][0] = r;
data[len][1] = c;
data[len][2] = val;
len++;
}
}

sparse_matrix transpose() {
sparse_matrix result(col, row);
result.len = len;

int *count = new int[col + 1]();


for (int i = 0; i < len; i++) {
count[data[i][1]]++;
}

int *index = new int[col + 1];


index[0] = 0;
for (int i = 1; i <= col; i++) {
index[i] = index[i - 1] + count[i - 1];
}

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


int res = index[data[i][1]]++;
result.data[res][0] = data[i][1];
1a
result.data[res][1] = data[i][0];
result.data[res][2] = data[i][2];
}

delete[] count;
delete[] index;
return result;
}

void print() {
cout << "\n Dimension: " << row << " x " << col;
cout << "\n Sparse Matrix:\n Row\tColumn\tValue\n";
for (int i = 0; i < len; i++) {
cout << data[i][0] << "\t" << data[i][1] << "\t" << data[i][2] << endl;
}
}

~sparse_matrix() {
for (int i = 0; i < max; i++) {
delete[] data[i];
}
delete[] data;
}
};

int main() {
sparse_matrix a(4, 4);
sparse_matrix b(4, 4);
a.insert(1, 2, 10);
a.insert(1, 4, 12);
a.insert(3, 3, 5);
a.insert(4, 1, 15);
a.insert(4, 2, 12);
b.insert(1, 3, 8);
b.insert(2, 4, 23);
b.insert(3, 3, 9);
b.insert(4, 1, 20);
b.insert(4, 2, 25);

cout << "\nMatrix A:";


a.print();
cout << "\nMatrix B:";
b.print();
cout << "\nTranspose of Matrix A:";
sparse_matrix transpose = a.transpose();
transpose.print();

return 0;
}
1b
#include<iostream>
using namespace std;
double evaluate_polynomial(double x,int degree,double coeffs[]){
double result=0;
for(int i=degree;i>=0;i--)

{
result=result *x+coeffs[i];
}
return result;
}
int main()
{
int degree;
double x,coeffs[50],result;
cout<<"Enter the degree of the polynomial :";
cin>>degree;
cout<<"Enter the value of X :";
cin>>x;
cout<<"Enter the cofficient of the polynomial in ascending order :";
for(int i=0;i<=degree;i++){
cin>>coeffs[i];
}
result=evaluate_polynomial(x,degree,coeffs);
cout<<"Result :"<<result;
return 0;

#include<iostream>
2a
using namespace std;
struct Node
{
int data;
Node* next;
};
Node *head=NULL;
void insert(int x)
{
Node* temp=new Node();
temp->data=x;
temp->next=head;
head=temp;
}
void Delete(int n)
{
Node* temp1=head;
if(n==1)
{
head=temp1->next;
2a
delete temp1;
return;
}
for(int i=0;i<n-2;i++){

temp1=temp1->next;
Node* temp2=temp1->next;
temp1->next=temp2->next;
delete temp2;
}
}
void display()
{
Node* temp=head;
while(temp!=NULL)
{
cout<<temp->data<<" ";
temp=temp->next;
}
cout<<endl;
}
int main()
{
int choice,x,n;
while(1){
cout<<"1.Insert \n";
cout<<"2.Delete\n";
cout<<"3.Display\n";
cout<<"4.Exit\n";
cout<<"Enter your choice :";
cin>>choice;
switch(choice){
case 1: cout<<"Enter the element :";
cin>>x;
insert(x);
break;
case 2: cout<<"Enter the element you want to delete :";
cin>>n;
Delete(n);
break;
case 3: display();
break;
case 4: exit(0);
default:cout<<"Invalid input";
}
}
return 0;

}
2b
#include<iostream>
#include<limits>
using namespace std;

struct Node {
int data;
Node* next;
};

class LinkedList {
private:
Node* head;
int count;

public:
LinkedList() {
head = NULL;
count = 0;
}

~LinkedList() {
Node* current = head;
Node* nextNode;
while (current != NULL) {
nextNode = current->next;
delete current;
current = nextNode;
}
}

void Create() {
int data;
cout << "Enter the data for the node: ";
while (!(cin >> data)) {
cout << "Invalid input! Please enter an integer: ";
cin.clear(); // Clear error flag
cin.ignore(numeric_limits<streamsize>::max(), '\n'); // Ignore invalid input
}
Node* newNode = new Node();
newNode->data = data;
newNode->next = head;
head = newNode;
count++;
}

void reverse() {
Node* prev = NULL;
Node* current = head;
Node* next = NULL;
2b
while (current != NULL) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
head = prev;
}

int search(int key) {


Node* current = head;
int index = 0;
while (current != NULL) {
if (current->data == key) {
return index;
}
current = current->next;
index++;
}
return -1;
}

int countNodes() {
return count;
}

void display() {
Node* current = head;
if (current == NULL) {
cout << "The list is empty." << endl;
return;
}
while (current != NULL) {
cout << current->data << " ";
current = current->next;
}
cout << endl;
}
};

int main() {
int choice;
LinkedList list;

while (true) {
cout << "1. Create Node" << endl;
cout << "2. Reverse list" << endl;
cout << "3. Search Element" << endl;
cout << "4. Count Nodes" << endl;
2b
cout << "5. Display" << endl;
cout << "6. Exit" << endl;
cout << "Enter your choice: ";
cin >> choice;

switch (choice) {
case 1:
list.Create();
break;
case 2:
list.reverse();
break;
case 3:
int key;
cout << "Enter the element to be searched: ";
cin >> key;
int index = list.search(key);
if (index == -1) {
cout << "Element not found." << endl;
} else {
cout << "Element found at index: " << index << endl;
}
break;
case 4:
cout << "Number of nodes: " << list.countNodes() << endl;
break;
case 5:
list.display();
break;
case 6:
cout << "Exiting program..." << endl;
return 0;
default:
cout << "Invalid Choice. Please enter a valid choice." << endl;
}
}

return 0;
}
3a
#include<iostream>
using namespace std;

struct node {
int data;
node* next;
node* prev;
};

node* head1 = NULL;


node* head2 = NULL;

void insert(int data, node*& head) {


node* temp = new node();
temp->data = data;
temp->next = NULL;
temp->prev = NULL;

if (!head) {
head = temp;
} else {
node* ptr = head;
while (ptr->next) {
ptr = ptr->next;
}
ptr->next = temp;
temp->prev = ptr;
}
}

void sortlist(node* head) {


if (head == NULL) return;

node* ptr = head;


while (ptr) {
node* temp = ptr->next;
while (temp) {
if (ptr->data > temp->data) {
swap(ptr->data, temp->data);
}
temp = temp->next;
}
ptr = ptr->next;
}
}

void mergelists() {
if (!head1 || !head2) return;
3a
node* ptr1 = head1;
while (ptr1->next) {
ptr1 = ptr1->next;
}

ptr1->next = head2;
if (head2) {
head2->prev = ptr1;
}
}

void printlist(node* head) {


node* ptr = head;
if (!ptr) {
cout << "List is empty!" << endl;
return;
}

while (ptr) {
cout << ptr->data << " ";
ptr = ptr->next;
}
cout << endl;
}

int main() {
// Insert elements into the first list
insert(5, head1);
insert(2, head1);
insert(4, head1);
insert(7, head1);
sortlist(head1); // Sort the first list
printlist(head1);

insert(3, head2);
insert(1, head2);
insert(6, head2);
insert(9, head2);
sortlist(head2);
printlist(head2);

mergelists();
printlist(head1);

return 0;
}
3b
#include<iostream>
using namespace std;

struct node {
int data;
node* next;
node* prev;
};

node* head = NULL;

void push(int data) {


node* newnode = new node();
newnode->data = data;
newnode->prev = NULL;
newnode->next = head;
if (head != NULL)
head->prev = newnode;
head = newnode;
}

void insert(int data) {


node* newnode = new node();
newnode->data = data;
newnode->next = NULL;

if (head == NULL) {
newnode->prev = NULL;
head = newnode;
return;
}

node* last = head;


while (last->next != NULL)
last = last->next;

last->next = newnode;
newnode->prev = last;
}

void deletenode(int position) {


if (head == NULL)
return;

node* temp = head;

if (position == 0) {
head = temp->next;
3b

if (head != NULL)
head->prev = NULL;
delete temp;
return;
}

for (int i = 0; temp != NULL && i < position - 1; i++) {


temp = temp->next;
}

if (temp == NULL || temp->next == NULL)


return;

node* next = temp->next->next;

delete temp->next;
temp->next = next;

if (next != NULL) {
next->prev = temp;
}
}

void printlist() {
node* temp = head;
while (temp != NULL) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}

int main() {
int choice, data, position;
while (true) {
cout << "1. Insert at front" << endl;
cout << "2. Insert at end" << endl;
cout << "3. Delete a node" << endl;
cout << "4. Print the list" << endl;
cout << "5. Exit" << endl;
cout << "Enter your choice : " << endl;

cin >> choice;

switch (choice) {
case 1:
cout << "Enter data: ";
cin >> data;
push(data);
3b
break;

case 2:
cout << "Enter data: ";
cin >> data;
insert(data);
break;

case 3:
cout << "Enter position: ";
cin >> position;
deletenode(position);
break;

case 4:
printlist();
break;

case 5:
return 0;

default:
cout << "Invalid choice" << endl;
}
}
return 0;
}

#include<iostream>
4a
using namespace std;

struct node {
int data;
node* next;
node* prev;
};

class circularlinkedlist{
private:
node* head;

public:
circularlinkedlist()
{
head = NULL;
}

void insertAtEnd(int data)


{
4a

node* newnode = new node();


newnode->data = data;
newnode->next = head;
newnode->prev = NULL;

if(head != NULL)
{
node* temp = head;
while(temp->next != head)
{
temp = temp->next;
}
temp->next = newnode;
newnode->prev = temp;
}
else
{
head = newnode;
newnode->next = newnode;
newnode->prev = newnode;
}
}

void insertatbeginning(int data)


{
node* newnode = new node();
newnode->data = data;

if(head != NULL)
{
node* temp = head;
while(temp->next != head)
{
temp = temp->next;
}
temp->next = newnode;
newnode->prev = temp;
newnode->next = head;
head->prev = newnode;
}
else
{
head = newnode;
newnode->next = newnode;
newnode->prev = newnode;
}
}

void deleteatend()
4a
{
if(head == NULL)
{
return;
}

node* temp = head;


if(temp->next == head)
{
head = NULL;
delete temp;
return;
}

while(temp->next != head)
{
temp = temp->next;
}

node* todelete = temp;


temp->prev->next = head;
head->prev = temp->prev;
delete todelete;
}

void deleteatbeginning()
{
if(head == NULL)
{
return;
}

node* temp = head;


if(temp->next == head)
{
head = NULL;
delete temp;
return;
}

node* todelete = head;


head = head->next;
head->prev = temp->prev;
temp->prev->next = head;
delete todelete;
}

void Display()
{
4a

node* temp = head;


if(head != NULL)
{
do
{
cout << temp->data << " ";
temp = temp->next;
}
while(temp != head);
}
cout << endl;
}
};

int main()
{
circularlinkedlist cll;
cll.insertAtEnd(1);
cll.insertAtEnd(2);
cll.insertAtEnd(3);
cll.insertatbeginning(0);
cll.deleteatend();
cll.deleteatbeginning();
cll.Display();

return 0;
}

#include<iostream> 4b
#include<math.h>

using namespace std;

struct node {
int coeff, powx, powy;
struct node* next;
};

// Function to create a new node and add it to the circular linked list
void create_node(int c, int p1, int p2, struct node** temp) {
struct node* r;
struct node* z = *temp;
r = new node(); // Use 'new' instead of 'malloc' in C++
r->coeff = c;
r->powx = p1;
r->powy = p2;

if (z == NULL) {
4b

(*temp) = r;
(*temp)->next = (*temp);
} else {
r->next = z->next;
z->next = r;
(*temp) = r;
}
}

// Function to display the polynomial stored in the circular linked list


void display_polynomial(struct node* temp) {
if (temp == NULL) {
cout << "Polynomial is empty!" << endl;
return;
}

struct node* t = temp;


do {
cout << t->coeff << "x^" << t->powx << "y^" << t->powy;
t = t->next;
if (t != temp) {
cout << " + ";
}
} while (t != temp);
cout << endl;
}

// Function to add two polynomials


void add_polynomials(struct node* poly1, struct node* poly2, struct node** result) {
struct node *p1 = poly1, *p2 = poly2;

while (p1 != poly1 || p2 != poly2) {


if (p1->powx == p2->powx && p1->powy == p2->powy) {
int coeff = p1->coeff + p2->coeff;
create_node(coeff, p1->powx, p1->powy, result);
p1 = p1->next;
p2 = p2->next;
} else if (p1->powx > p2->powx || (p1->powx == p2->powx && p1->powy > p2->powy)) {
create_node(p1->coeff, p1->powx, p1->powy, result);
p1 = p1->next;
} else {
create_node(p2->coeff, p2->powx, p2->powy, result);
p2 = p2->next;
}
}

// If there are remaining terms in either of the polynomials


while (p1 != poly1) {
create_node(p1->coeff, p1->powx, p1->powy, result);
4b
p1 = p1->next;
}

while (p2 != poly2) {


create_node(p2->coeff, p2->powx, p2->powy, result);
p2 = p2->next;
}
}

// Function to evaluate a polynomial at a given x and y


int evaluate_polynomial(struct node* poly, int x, int y) {
int result = 0;
struct node* temp = poly;

do {
result += temp->coeff * pow(x, temp->powx) * pow(y, temp->powy);
temp = temp->next;
} while (temp != poly);

return result;
}

int main() {
struct node* poly1 = NULL, *poly2 = NULL, *result = NULL;
int choice, c, p1, p2, x, y;

while (true) {
cout << "\nMenu:\n";
cout << "1. Create first polynomial\n";
cout << "2. Create second polynomial\n";
cout << "3. Display first polynomial\n";
cout << "4. Display second polynomial\n";
cout << "5. Add polynomials\n";
cout << "6. Evaluate polynomial\n";
cout << "7. Exit\n";
cout << "Enter your choice: ";
cin >> choice;

switch (choice) {
case 1:
cout << "Enter coefficient, power of x, and power of y for the term: ";
cin >> c >> p1 >> p2;
create_node(c, p1, p2, &poly1);
break;
case 2:
cout << "Enter coefficient, power of x, and power of y for the term: ";
cin >> c >> p1 >> p2;
create_node(c, p1, p2, &poly2);
break;
4b

case 3:
cout << "First polynomial: ";
display_polynomial(poly1);
break;
case 4:
cout << "Second polynomial: ";
display_polynomial(poly2);
break;
case 5:
add_polynomials(poly1, poly2, &result);
cout << "Result of addition: ";
display_polynomial(result);
break;
case 6:
cout << "Enter value of x and y: ";
cin >> x >> y;
cout << "Evaluation result: " << evaluate_polynomial(poly1, x, y) << endl;
break;
case 7:
return 0;
default:
cout << "Invalid choice! Please try again." << endl;
}
}

return 0;
};

#include<iostream> 5a
#include<stack>
using namespace std;

int priority(char alpha) {


if (alpha == '+' || alpha == '-')
return 1;
if (alpha == '*' || alpha == '/')
return 2;
if (alpha == '^')
return 3;
return 0;
}

string convert(string infix) {


int i = 0;
string postfix = "";
stack<char> s;
5a

while (infix[i] != '\0') {


if ((infix[i] >= 'a' && infix[i] <= 'z') || (infix[i] >= 'A' && infix[i] <= 'Z')) {
postfix += infix[i];
i++;
}
else if (infix[i] == '(') {
s.push(infix[i]);
i++;
}
else if (infix[i] == ')') {

while (!s.empty() && s.top() != '(') {


postfix += s.top();
s.pop();
}
s.pop();
i++;
}
else {

while (!s.empty() && priority(infix[i]) <= priority(s.top())) {


postfix += s.top();
s.pop();
}
s.push(infix[i]);
i++;
}
}

while (!s.empty()) {
postfix += s.top();
s.pop();
}

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


return postfix;
}

int main() {
string infix = "((a+(b*c)-d))";
string postfix;
postfix = convert(infix);
return 0;
}
5b
#include<iostream>
#include<stack>
using namespace std;
string infixtopostfix(string infix)
{
stack<char> s;
string prefix=" ";
for(int i=0;i<infix.length();i++)
if(isalnum(infix[i]))
{

prefix+=infix[i];
}

else{
while(!s.empty() && s.top()!='(' && s.top()!=')')
{
prefix +=s.top();
s.pop();
}
s.push(infix[i]);
}
while(!s.empty())
{
prefix+=s.top();
s.pop();
}
return prefix;
}
int main()
{
string infix="A*B+C*D";
cout<<"Infix :"<<infix<<endl;
cout<<"postfix :"<<infixtopostfix(infix);
return 0;

#include<iostream> 6a
using namespace std;
class circularqueue{
int * queue,size,front,rear;
public:
circularqueue(int s){
size=s;
queue=new int[size];
front = rear = -1;
}
6a
void enqueue(int x);
int dequeue();
void display();

};
void circularqueue::enqueue(int x)
{
if(front==0 && rear==size-1)
{
cout<<"Queue is full\n";
return ;
}
else if(front== -1)
{
front=rear=0;
}
else if(rear==size-1 && front!=0){
rear=0;
}
else{
rear++;
}
queue[rear]=x;
}
int circularqueue::dequeue(){
if(front==-1){
cout<<"Queue is empty \n";
return -1;
}
int x=queue[front];
if(front==rear)
{
front=rear=-1;
}
else if(front==size-1){
front =0;}
else{
front ++;
}
return x;
}
void circularqueue::display()
{
if(front== -1)
{
cout<<"Queue is empty\n";
return;

}
6a
if(rear>=front)
{
for(int i=front;i<rear;i++)
cout<<queue[i]<<" ";
}
else
{for(int i=front;i<size;i++)
cout<<queue[i]<<" ";
for(int i=0;i<=rear;i++)
cout<<queue[i]<<" ";
}
}
int main(){
circularqueue q(5);
q.enqueue(1);
q.enqueue(2);
q.enqueue(3);
q.enqueue(4);
q.enqueue(5);
q.enqueue(6);
q.display();
q.dequeue();
q.dequeue();
q.display();

return 0;
}

#include <iostream> 6b
using namespace std;

struct node {
int data;
node* next;

// Constructor for node


node(int d) {
data = d;
next = NULL;
}
};

struct Queue {
node* front, *rear;

// Constructor for Queue


Queue() {
front = rear = NULL;
6b

// Enqueue function to add elements to the queue


void enqueue(int x) {
node* temp = new node(x);
if (rear == NULL) {
front = rear = temp;
return;
}
rear->next = temp;
rear = temp;
}

// Dequeue function to remove elements from the queue


void dequeue() {
if (front == NULL)
return;
node* temp = front;
front = front->next;
if (front == NULL)
rear = NULL;
delete temp;
}
};

int main() {
Queue q;
q.enqueue(10);
q.enqueue(20);
q.dequeue(); // Removes 10 from the queue
q.dequeue(); // Removes 20 from the queue
q.enqueue(40); // Adds 40 to the queue

// Check the state of the queue after operations


if (q.front != NULL) {
cout << "Queue front: " << q.front->data << endl;
} else {
cout << "Queue is empty" << endl;
}

if (q.rear != NULL) {
cout << "Queue rear: " << q.rear->data << endl;
} else {
cout << "Queue is empty" << endl;
}

return 0;
}
7a
#include <iostream>
#include <vector>
#include <bits/stdc++.h>
using namespace std;

vector<vector<int> > adj;

// Function to add edges to the graph


void addedge(int x, int y)
{
adj[x][y] = 1;
adj[y][x] = 1;
}

// DFS function to traverse the graph starting from a node


void dfs(int start)
{
vector<bool> visited(adj.size(), false); // Track visited nodes
stack<int> s; // Stack to simulate the DFS traversal
s.push(start);

while (!s.empty())
{
int node = s.top();
s.pop();

// If the node hasn't been visited, visit it


if (!visited[node])
{
visited[node] = true;
cout << node << " "; // Output the visited node
}

// Check all adjacent nodes


for (int i = 0; i < adj[node].size(); i++)
{
if (adj[node][i] == 1 && !visited[i]) // If there's an edge and node hasn't been visited
{
s.push(i);
}
}
}
}

int main()
{
int v = 5; // Number of vertices
int e = 4; // Number of edges
7a
adj = vector<vector<int> >(v, vector<int>(v, 0)); // Initialize adjacency matrix

// Adding edges to the graph


addedge(0, 1);
addedge(0, 2);
addedge(0, 3);
addedge(0, 4);

// Perform DFS starting from vertex 0


cout << "DFS traversal starting from vertex 0: ";
dfs(0);
cout << endl;

return 0;
}

#include <bits/stdc++.h> 7b
using namespace std;

vector<vector<int> > adj;

// Function to add an edge


void addedge(int x, int y) {
adj[x][y] = 1;
adj[y][x] = 1;
}

// BFS Traversal
void bfs(int start, vector<bool>& visited) {
vector<int> q;
q.push_back(start);
visited[start] = true;

while (!q.empty()) {
int vis = q[0];
cout << vis << " ";
q.erase(q.begin()); // Dequeue

for (int i = 0; i < adj[vis].size(); i++) {


if (adj[vis][i] == 1 && !visited[i]) {
q.push_back(i);
visited[i] = true;
}
}
}
}

// DFS Traversal
7b

void dfs(int start, vector<bool>& visited) {


visited[start] = true;
cout << start << " ";

// Recur for all the vertices adjacent to this vertex


for (int i = 0; i < adj[start].size(); i++) {
if (adj[start][i] == 1 && !visited[i]) {
dfs(i, visited);
}
}
}

int main() {
int v = 5; // Number of vertices
int e = 4; // Number of edges

adj = vector<vector<int> >(v, vector<int>(v, 0)); // Create an adjacency matrix

// Adding edges
addedge(0, 1);
addedge(0, 2);
addedge(0, 3);
addedge(0, 4);

vector<bool> visited(v, false);

// DFS Traversal
cout << "DFS traversal starting from vertex 0: ";
dfs(0, visited);
cout << endl;

// Reset visited array for BFS


fill(visited.begin(), visited.end(), false);

// BFS Traversal
cout << "BFS traversal starting from vertex 0: ";
bfs(0, visited);
cout << endl;

return 0;
}
8a
#include<iostream>
#include<vector>
#include<utility>
#include<algorithm>
using namespace std;

const int MAX = 1000;


int id[MAX], nodes, edges;
pair<long long, pair<int, int> > p[MAX];

void init() {
for (int i = 0; i < MAX; i++)
id[i] = i;
}

int root(int x) {
while (id[x] != x) {
id[x] = id[id[x]];
x = id[x];
}
return x;
}

void union1(int x, int y) {


int p = root(x);
int q = root(y);
id[p] = id[q];
}

long long kruskal(pair<long long, pair<int, int> > p[]) {


int x, y;
long long cost, minimumcost = 0;
for (int i = 0; i < edges; ++i) {
x = p[i].second.first;
y = p[i].second.second;
cost = p[i].first;

if (root(x) != root(y)) {
minimumcost += cost;
cout << x << " - " << y << " : " << p[i].first << endl;
union1(x, y);
}
}
return minimumcost;
}

int main() {
8a
int x, y;
long long weight, minimumcost;
init();

cout << "Enter number of nodes and edges: ";


cin >> nodes >> edges;

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


cout << "Enter x, y & weight of edge " << i + 1 << ": ";
cin >> x >> y >> weight;
p[i] = make_pair(weight, make_pair(x, y));
}

sort(p, p + edges);

minimumcost = kruskal(p);

cout << "Minimum cost of the spanning tree: " << minimumcost << endl;

return 0;
}

#include<stdio.h> 8b
#include<limits.h>
#include<stdbool.h>

#define V 9
int mindistance(int dist[], bool sprser[])
{
int min = INT_MAX, min_index;

for (int v = 0; v < V; v++)


{
if (sprser[v] == false && dist[v] <= min)
{
min = dist[v];
min_index = v;
}
}
return min_index;
}

void printsolution(int dist[])


{
printf("Vertex \t Distance from Source\n");
for (int i = 0; i < V; i++)
printf("%d \t\t %d\n", i, dist[i]);
8b

void dijikstra(int graph[V][V], int src)


{
int dist[V];
bool sprser[V];
for (int i = 0; i < V; i++)
{
dist[i] = INT_MAX;
sprser[i] = false;
}

dist[src] = 0;

for (int count = 0; count < V - 1; count++)


{
int u = mindistance(dist, sprser);

sprser[u] = true;

for (int v = 0; v < V; v++)


{
if (!sprser[v] && graph[u][v] && dist[u] != INT_MAX && dist[u] + graph[u][v] < dist[v])
{
dist[v] = dist[u] + graph[u][v];
}
}
}

printsolution(dist);
}
int main()
{
int graph[V][V] = {
{0, 4, 0, 0, 0, 0, 0, 8, 0},
{4, 0, 8, 0, 0, 0, 0, 11, 0},
{0, 8, 0, 7, 0, 4, 0, 0, 2},
{0, 0, 7, 0, 9, 14, 0, 0, 0},
{0, 4, 0, 0, 0, 2, 0, 1, 6},
{0, 0, 4, 14, 2, 0, 1, 0, 7},
{0, 0, 0, 0, 0, 1, 0, 2, 3},
{8, 11, 0, 0, 1, 0, 2, 0, 0},
{0, 0, 2, 0, 6, 7, 3, 0, 0}
};

dijikstra(graph, 0);
return 0;
}
9a
#include <iostream>
using namespace std;

void merge(int arr[], int l, int m, int r) {


int n1 = m - l + 1;
int n2 = r - m;

int L[n1], R[n2];

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


L[i] = arr[l + i];
for (int j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];

int i = 0, j = 0, k = l;

while (i < n1 && j < n2) {


if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}

while (i < n1) {


arr[k] = L[i];
i++;
k++;
}

while (j < n2) {


arr[k] = R[j];
j++;
k++;
}
}

void mergesort(int arr[], int l, int r) {


if (l < r) {

int m = l + (r - l) / 2;

mergesort(arr, l, m);
mergesort(arr, m + 1, r);

merge(arr, l, m, r);
9a

}
}

int main() {

int arr[] = {12, 11, 13, 5, 6, 7};

int n = sizeof(arr) / sizeof(arr[0]);

mergesort(arr, 0, n - 1);

cout << "Sorted array: \n";


for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;

return 0;
}

#include<iostream> 9b
using namespace std;

void heapify(int arr[], int n, int i) {


int largest = i;
int l = 2 * i + 1;
int r = 2 * i + 2;

if (l < n && arr[l] > arr[largest]) {


largest = l;
}

if (r < n && arr[r] > arr[largest]) {


largest = r;
}

if (largest != i) {
swap(arr[i], arr[largest]);
heapify(arr, n, largest);
}
}

void heapsort(int arr[], int n) {


for (int i = n / 2 - 1; i >= 0; i--) {
heapify(arr, n, i);
}
9b
for (int i = n - 1; i >= 0; i--) {
swap(arr[0], arr[i]);
heapify(arr, i, 0);
}
}
int main() {
int arr[] = {12, 11, 13, 5, 6, 7};
int n = sizeof(arr) / sizeof(arr[0]);

heapsort(arr, n);

cout << "Sorted array: ";


for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;

return 0;
}

#include<iostream> 10a
using namespace std;
int sequentialsearch(int array[],int size,int key)
{
for(int i=0;i<size;i++)
{
if(array[i]==key)
{
return i;
}
}
return -1;
}
int main()
{
int array[]={1,2,3,4,5};
int size=sizeof(array)/sizeof(array[0]);
int key=3;
int index=sequentialsearch(array,size,key);
if(index!=-1)
{
cout<<"key found at index :"<<index;
}
else{
cout<<"key not found:";
}
return 0;
}
11a

#include<iostream>
using namespace std;

struct node {
int data;
node* left;
node* right;
};

node* getnewnode(int data) {


node* newnode = new node();
newnode->data = data;
newnode->left = newnode->right = NULL;
return newnode;
}

// Preorder traversal: Root -> Left -> Right


void preorder(node* root) {
if (root == NULL) return;
cout << root->data << " ";
preorder(root->left);
preorder(root->right);
}

void inorder(node* root) {


if (root == NULL) return;
inorder(root->left);
cout << root->data << " ";
inorder(root->right);
}

void postorder(node* root) {


if (root == NULL) return;
postorder(root->left);
postorder(root->right);
cout << root->data << " ";
}

int main() {
node* root = getnewnode(1);
root->left = getnewnode(2);
root->right = getnewnode(3);
root->left->left = getnewnode(4);
root->left->right = getnewnode(5);

cout << "Preorder traversal: ";


preorder(root);
11a

cout << endl;

cout << "Inorder traversal: ";


inorder(root);
cout << endl;

cout << "Postorder traversal: ";


postorder(root);
cout << endl;

return 0;
}

11b

#include<iostream>
#include<queue>
#include<algorithm>
using namespace std;

struct node {
int data;
node* left, * right;
};

node* newnode(int data) {


node* newNode = new node();
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}

int height(node* root) {


if (root == NULL)
return 0;
return 1 + max(height(root->left), height(root->right));
}

void printleafnodes(node* root) {


if (root == NULL)
return;
if (root->left == NULL && root->right == NULL)
cout << root->data << " ";
printleafnodes(root->left);
printleafnodes(root->right);
}
11b

node* mirror(node* root) {


if (root == NULL)
return NULL;
node* left = mirror(root->left);
node* right = mirror(root->right);
root->left = right;
root->right = left;
return root;
}

void printlevelwise(node* root) {


if (root == NULL)
return;

queue<node*> q;
q.push(root);
while (!q.empty()) {
node* current = q.front();
q.pop();
cout << current->data << " ";
if (current->left != NULL)
q.push(current->left);
if (current->right != NULL)
q.push(current->right);
}
}

int main() {
node* root = newnode(1);
root->left = newnode(2);
root->right = newnode(3);
root->left->left = newnode(4);
root->left->right = newnode(5);
cout << "Height of tree: " << height(root) << endl;
cout << "Leaf nodes of original tree: ";
printleafnodes(root);
cout << endl;
node* mirrorroot = mirror(root);
cout << "Original tree (level-wise): ";
printlevelwise(root);
cout << endl;
cout << "Mirror image (level-wise): ";
printlevelwise(mirrorroot);
cout << endl;

return 0;
}

You might also like