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

LAB Re

Uploaded by

Harsh Sahu
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

LAB Re

Uploaded by

Harsh Sahu
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 57

Lab Report

DATA STRUCTURES
AND
ANALYSIS OF ALGORITHMS
CSD3009
Submitted by

HARSH KUMAR SAHU


(21BSA10163)

BACHELOR OF TECHNOLOGY

in
Artificial intelligence and machine learning

SCHOOL OF COMPUTING SCIENCE AND ENGINEERING

VIT BHOPAL UNIVERSITY

KOTHRIKALAN, SEHORE
MADHYA PRADESH - 466114
Feb (2023)
INSERTION
Output
TRAVERSAL & CREATION

Output

DELETION
Output
Course Code: CSD3009
Course Name: DATA-STRUCTURES-AND-ANALYSIS-OF-ALGORITHMS
Registration No: 21BSA10163
Name: Harsh Kumar Sahu

Lab 2
Q. Write a program that uses functions to perform the following operations on doubly
linked list i) Creation ii) Insertion iii) Deletion iv) Traversal

Create & Traverse

#include <stdio.h>
#include <stdlib.h>

/*
* Basic structure of Node
*/
struct node {
int data;
struct node * prev;
struct node * next;
}*head, *last;

/*
* Function used in this program
*/
void createList(int n);
void displayListFromFirst();
void displayListFromEnd();

int main()
{
int n, choice;

head = NULL;
last = NULL;

printf("Enter the number of nodes you want to create: ");


scanf("%d", &n);

createList(n); // Create list of n nodes

printf("\nPress 1 to display list from First");


printf("\nPress 2 to display list from End : ");
scanf("%d", &choice);

if(choice==1)
{
displayListFromFirst();
}
else if(choice == 2)
{
displayListFromEnd();
}

return 0;
}

/**
* Create a doubly linked list of n nodes.
* @n Number of nodes to be created
*/
void createList(int n)
{
int i, data;
struct node *newNode;
if(n >= 1)
{
head = (struct node *)malloc(sizeof(struct node));

if(head != NULL)
{
printf("Enter data of 1 node: ");
scanf("%d", &data);

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

last = head;

/*
* Create rest of the n-1 nodes
*/
for(i=2; i<=n; i++)
{
newNode = (struct node *)malloc(sizeof(struct node));

if(newNode != NULL)
{
printf("Enter data of %d node: ", i);
scanf("%d", &data);

newNode->data = data;
newNode->prev = last; // Link new node with the previous
node
newNode->next = NULL;

last->next = newNode; // Link previous node with the new


node
last = newNode; // Make new node as last/previous
node
}
else
{
printf("Unable to allocate memory.");
break;
}
}

printf("\nDOUBLY LINKED LIST CREATED SUCCESSFULLY\n");


}
else
{
printf("Unable to allocate memory");
}
}
}

/**
* Displays the content of the list from beginning to end
*/
void displayListFromFirst()
{
struct node * temp;
int n = 1;

if(head == NULL)
{
printf("List is empty.");
}
else
{
temp = head;
printf("\n\nDATA IN THE LIST:\n");

while(temp != NULL)
{
printf("DATA of %d node = %d\n", n, temp->data);

n++;

/* Move the current pointer to next node */


temp = temp->next;
}
}
}

/**
* Display the content of the list from last to first
*/
void displayListFromEnd()
{
struct node * temp;
int n = 0;

if(last == NULL)
{
printf("List is empty.");
}
else
{
temp = last;
printf("\n\nDATA IN THE LIST:\n");

while(temp != NULL)
{
printf("DATA of last-%d node = %d\n", n, temp->data);

n++;

/* Move the current pointer to previous node */


temp = temp->prev;
}
}
}

Screenshot:-
output
Insertion:
#include <stdio.h>
#include <stdlib.h>

/*
* Basic structure of Node
*/
struct node {
int data;
struct node * prev;
struct node * next;
}*head, *last;

/*
* Function used in this program
*/
void createList(int n);
void displayList();
void insertAtBeginning(int data);
void insertAtEnd(int data);
void insertAtN(int data, int position);

int main()
{
int n, data, choice=1;

head = NULL;
last = NULL;

/*
* Run forever until user chooses 0
*/
while(choice != 0)
{
/*
* Menu creation to use the program
*/
printf("============================================\n");
printf("DOUBLY LINKED LIST PROGRAM\n");
printf("============================================\n");
printf("1. Create List\n");
printf("2. Insert node - at beginning\n");
printf("3. Insert node - at end\n");
printf("4. Insert node - at N\n");
printf("5. Display list\n");
printf("0. Exit\n");
printf("--------------------------------------------\n");
printf("Enter your choice : ");

scanf("%d", &choice);

/*
* Choose from different menu operation
*/
switch(choice)
{
case 1:
printf("Enter the total number of nodes in list: ");
scanf("%d", &n);

createList(n);
break;
case 2:
printf("Enter data of first node : ");
scanf("%d", &data);

insertAtBeginning(data);
break;
case 3:
printf("Enter data of last node : ");
scanf("%d", &data);

insertAtEnd(data);
break;
case 4:
printf("Enter the position where you want to insert new node:
");
scanf("%d", &n);
printf("Enter data of %d node : ", n);
scanf("%d", &data);

insertAtN(data, n);
break;
case 5:
displayList();
break;
case 0:
break;
default:
printf("Error! Invalid choice. Please choose between 0-5");
}

printf("\n\n\n\n\n");
}

return 0;
}

/**
* Creates a doubly linked list of n nodes.
* @n Number of nodes to be created
*/
void createList(int n)
{
int i, data;
struct node *newNode;

if(n >= 1)
{
/*
* Create and link the head node
*/
head = (struct node *)malloc(sizeof(struct node));

printf("Enter data of 1 node: ");


scanf("%d", &data);

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

last = head;

/*
* Create and link rest of the n-1 nodes
*/
for(i=2; i<=n; i++)
{
newNode = (struct node *)malloc(sizeof(struct node));

printf("Enter data of %d node: ", i);


scanf("%d", &data);

newNode->data = data;
newNode->prev = last; // Link new node with the previous node
newNode->next = NULL;

last->next = newNode; // Link previous node with the new node


last = newNode; // Make new node as last/previous node
}

printf("\nDOUBLY LINKED LIST CREATED SUCCESSFULLY\n");


}
}

/**
* Display content of the list from beginning to end
*/
void displayList()
{
struct node * temp;
int n = 1;

if(head == NULL)
{
printf("List is empty.\n");
}
else
{
temp = head;
printf("DATA IN THE LIST:\n");

while(temp != NULL)
{
printf("DATA of %d node = %d\n", n, temp->data);

n++;

/* Move the current pointer to next node */


temp = temp->next;
}
}
}

/**
* Inserts a new node at the beginning of the doubly linked list
* @data Data of the first node i.e. data of the new node
*/
void insertAtBeginning(int data)
{
struct node * newNode;

if(head == NULL)
{
printf("Error, List is Empty!\n");
}
else
{
newNode = (struct node *)malloc(sizeof(struct node));

newNode->data = data;
newNode->next = head; // Point to next node which is currently head
newNode->prev = NULL; // Previous node of first node is NULL

/* Link previous address field of head with newnode */


head->prev = newNode;

/* Make the new node as head node */


head = newNode;

printf("NODE INSERTED SUCCESSFULLY AT THE BEGINNING OF THE LIST\n");


}
}

/**
* Inserts a new node at the end of the doubly linked list
* @data Data of the last node i.e data of the new node
*/
void insertAtEnd(int data)
{
struct node * newNode;

if(last == NULL)
{
printf("Error, List is empty!\n");
}
else
{
newNode = (struct node *)malloc(sizeof(struct node));

newNode->data = data;
newNode->next = NULL;
newNode->prev = last;

last->next = newNode;
last = newNode;

printf("NODE INSERTED SUCCESSFULLY AT THE END OF LIST\n");


}
}

/**
* Inserts a node at any position in the doubly linked list
* @data Data of the new node to be inserted
* @position Position where to insert the new node
*/
void insertAtN(int data, int position)
{
int i;
struct node * newNode, *temp;

if(head == NULL)
{
printf("Error, List is empty!\n");
}
else
{
temp = head;
i=1;

while(i<position-1 && temp!=NULL)


{
temp = temp->next;
i++;
}

if(position == 1)
{
insertAtBeginning(data);
}
else if(temp == last)
{
insertAtEnd(data);
}
else if(temp!=NULL)
{
newNode = (struct node *)malloc(sizeof(struct node));

newNode->data = data;
newNode->next = temp->next; // Connect new node with n+1th node
newNode->prev = temp; // Connect new node with n-1th node

if(temp->next != NULL)
{
/* Connect n+1th node with new node */
temp->next->prev = newNode;
}
/* Connect n-1th node with new node */
temp->next = newNode;

printf("NODE INSERTED SUCCESSFULLY AT %d POSITION\n", position);


}
else
{
printf("Error, Invalid position\n");
}
}
}
Screenshot:
Output
Deletion:-
#include <stdio.h>
#include <stdlib.h>

/*
* Basic structure of Node
*/
struct node {
int data;
struct node * prev;
struct node * next;
}*head, *last;

/*
* Functions used in this program
*/
void createList(int n);
void displayList();
void deleteFromBeginning();
void deleteFromEnd();
void deleteFromN(int position);

int main()
{
int n, data, choice=1;

head = NULL;
last = NULL;

/*
* Run forever until user chooses 0
*/
while(choice != 0)
{
printf("============================================\n");
printf("DOUBLY LINKED LIST PROGRAM\n");
printf("============================================\n");
printf("1. Create List\n");
printf("2. Delete node - from beginning\n");
printf("3. Delete node - from end\n");
printf("4. Delete node - from N\n");
printf("5. Display list\n");
printf("0. Exit\n");
printf("--------------------------------------------\n");
printf("Enter your choice : ");

scanf("%d", &choice);

switch(choice)
{
case 1:
printf("Enter the total number of nodes in list: ");
scanf("%d", &n);
createList(n);
break;
case 2:
deleteFromBeginning();
break;
case 3:
deleteFromEnd();
break;
case 4:
printf("Enter the node position which you want to delete: ");
scanf("%d", &n);
deleteFromN(n);
break;
case 5:
displayList();
break;
case 0:
break;
default:
printf("Error! Invalid choice. Please choose between 0-5");
}

printf("\n\n\n\n\n");
}

return 0;
}

/**
* Creates a doubly linked list of n nodes.
* @n Number of nodes to be created
*/
void createList(int n)
{
int i, data;
struct node *newNode;

if(n >= 1)
{
/*
* Creates and links the head node
*/
head = (struct node *)malloc(sizeof(struct node));

printf("Enter data of 1 node: ");


scanf("%d", &data);

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

last = head;

/*
* Create and link rest of the n-1 nodes
*/
for(i=2; i<=n; i++)
{
newNode = (struct node *)malloc(sizeof(struct node));

printf("Enter data of %d node: ", i);


scanf("%d", &data);

newNode->data = data;
newNode->prev = last; // Link new node with the previous node
newNode->next = NULL;

last->next = newNode; // Link previous node with the new node


last = newNode; // Make new node as last node
}

printf("\nDOUBLY LINKED LIST CREATED SUCCESSFULLY\n");


}
}
/**
* Display the content of the list from beginning to end
*/
void displayList()
{
struct node * temp;
int n = 1;

if(head == NULL)
{
printf("List is empty.\n");
}
else
{
temp = head;
printf("DATA IN THE LIST:\n");

while(temp != NULL)
{
printf("DATA of %d node = %d\n", n, temp->data);

n++;

/* Move the current pointer to next node */


temp = temp->next;
}
}
}

/**
* Delete or remove the first node of the doubly linked list
*/
void deleteFromBeginning()
{
struct node * toDelete;

if(head == NULL)
{
printf("Unable to delete. List is empty.\n");
}
else
{
toDelete = head;
head = head->next; // Move head pointer to 2 node

if (head != NULL)
head->prev = NULL; // Remove the link to previous node

free(toDelete); // Delete the first node from memory


printf("SUCCESSFULLY DELETED NODE FROM BEGINNING OF THE LIST.\n");
}
}

/**
* Delete or remove the last node of the doubly linked list
*/
void deleteFromEnd()
{
struct node * toDelete;

if(last == NULL)
{
printf("Unable to delete. List is empty.\n");
}
else
{
toDelete = last;

last = last->prev; // Move last pointer to 2nd last node

if (last != NULL)
last->next = NULL; // Remove link to of 2nd last node with last node

free(toDelete); // Delete the last node


printf("SUCCESSFULLY DELETED NODE FROM END OF THE LIST.\n");
}
}

/**
* Delete node from any position in the doubly linked list
*/
void deleteFromN(int position)
{
struct node *current;
int i;
current = head;
for(i=1; i<position && current!=NULL; i++)
{
current = current->next;
}

if(position == 1)
{
deleteFromBeginning();
}
else if(current == last)
{
deleteFromEnd();
}
else if(current != NULL)
{
current->prev->next = current->next;
current->next->prev = current->prev;

free(current); // Delete the n node

printf("SUCCESSFULLY DELETED NODE FROM %d POSITION.\n", position);


}
else
{
printf("Invalid position!\n");
}
}
Output:
Q.write a program that uses function to perform the following operations on
circuler linked list
I)creation ii) deletion III) insertion IV) traversal

#include <stdio.h>
#include <stdlib.h>

// Create a node
struct Node {
int data;
struct Node* next;
};

// Insert at the beginning


void insertAtBeginning(struct Node** head_ref, int new_data) {
// Allocate memory to a node
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));

// insert the data


new_node->data = new_data;

new_node->next = (*head_ref);
// Move head to new node
(*head_ref) = new_node;
}

// Insert a node after a node


void insertAfter(struct Node* prev_node, int new_data) {
if (prev_node == NULL) {
printf("the given previous node cannot be NULL");
return;
}

struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));


new_node->data = new_data;
new_node->next = prev_node->next;
prev_node->next = new_node;
}

// Insert the the end


void insertAtEnd(struct Node** head_ref, int new_data) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
struct Node* last = *head_ref; /* used in step 5*/

new_node->data = new_data;
new_node->next = NULL;

if (*head_ref == NULL) {
*head_ref = new_node;
return;
}

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

last->next = new_node;
return;
}

// Delete a node
void deleteNode(struct Node** head_ref, int key) {
struct Node *temp = *head_ref, *prev;

if (temp != NULL && temp->data == key) {


*head_ref = temp->next;
free(temp);
return;
}
// Find the key to be deleted
while (temp != NULL && temp->data != key) {
prev = temp;
temp = temp->next;
}

// If the key is not present


if (temp == NULL) return;

// Remove the node


prev->next = temp->next;

free(temp);
}

// Search a node
int searchNode(struct Node** head_ref, int key) {
struct Node* current = *head_ref;

while (current != NULL) {


if (current->data == key) return 1;
current = current->next;
}
return 0;
}

// Sort the linked list


void sortLinkedList(struct Node** head_ref) {
struct Node *current = *head_ref, *index = NULL;
int temp;

if (head_ref == NULL) {
return;
} else {
while (current != NULL) {
// index points to the node next to current
index = current->next;

while (index != NULL) {


if (current->data > index->data) {
temp = current->data;
current->data = index->data;
index->data = temp;
}
index = index->next;
}
current = current->next;
}
}
}

// Print the linked list


void printList(struct Node* node) {
while (node != NULL) {
printf(" %d ", node->data);
node = node->next;
}
}

// Driver program
int main() {
struct Node* head = NULL;

insertAtEnd(&head, 1);
insertAtBeginning(&head, 2);
insertAtBeginning(&head, 3);
insertAtEnd(&head, 4);
insertAfter(head->next, 5);

printf("Linked list: ");


printList(head);

printf("\nAfter deleting an element: ");


deleteNode(&head, 3);
printList(head);

int item_to_find = 3;
if (searchNode(&head, item_to_find)) {
printf("\n%d is found", item_to_find);
} else {
printf("\n%d is not found", item_to_find);
}

sortLinkedList(&head);
printf("\nSorted List: ");
printList(head);
}
Output:-
LAB-4
Q.Write a program to perform the following operation: a) Insert an element into
a binary search tree. B) delete àn element form a binary search tree. C) search
for a key element in a binary search tree

#include <iostream>
using namespace std;
class node
{
public:
int data;
node *left;
node *right;
};

//Function to search an element in a BST


bool search(node *root, int x)
{
//base case
if (root == NULL)
return false;
//if node found
if (x == root->data)
return true;
//if current value is less than value to be found
//search in left subtree
if (x < root->data)
return search(root->left, x);
//search in right subtree otherwise
return search(root->right, x);
}
//Function to insert an element in a BST
node *insert(node *root, int x)
{ //if we found the place where the node is to be inserted
if (root == NULL)
{
//create new node and return it
root = new node();
root->data = x;
root->left = root->right = NULL;
return root;
}
//if the current node is greater the node to be inserted
if (x < root->data)
{
//if left child of the current node is NULL
if (root->left == NULL)
{
//the new node is the left child
root->left = insert(root->left, x);
}
else
{
//recursively insert the element into left subtree
insert(root->left, x);
}
return root;
}
//if the current node is less the node to be inserted
//if right child of the current node is NULL
if (root->right == NULL)
{
//the new node is the right child
root->right = insert(root->right, x);
}
else
//recursively insert the element in the right subtree
insert(root->right, x);
return root;
}

//Function to find the predecessor of a given node


node *inorderPredecessor(node *t)
{
if (t == NULL)
{
return NULL;
}
while (t != NULL and t->right != NULL)
{
t = t->right;
}
return t;
}

//Function to delete a node


node *deleteNode(node *t, int k)
{
//if the root is NULL
if (t == NULL)
{
return NULL;
}
//if the found node is a leaf node
if (t->left == NULL and t->right == NULL)
{
return NULL;
}
node *q;
//if current node is less than k
if (k > t->data)
{
//recursively delete from right subtree
t->right = deleteNode(t->right, k);
}
//if current node is greater than k
else if (k < t->data)
{
//recursively delete from left subtree
t->left = deleteNode(t->left, k);
}
else
{
//if the element to be deleted is found, swap it with its predecessor
//and then delete it from the left subtree
q = inorderPredecessor(t->left);
t->data = q->data;
t->left = deleteNode(t->left, q->data);
}
return t;
}
int main()
{
int ch;
node *root = NULL;
while (1)
{
cout << "1. Insert Node\n";
cout << "2. Search Node\n";
cout << "3. Delete Node\n";
cout << "4. Exit\n";
cout << "Enter your choice: ";
scanf("%d", &ch);
switch (ch)
{
case 1:
{
int x;
cout << "Enter the value to be inserted: ";
cin >> x;
root = insert(root, x);
break;
}
case 2:
{
int x;
cout << "Enter the value to be searched: ";
cin >> x;
bool res = search(root, x);
if (res == true)
cout << "Node found\n";
else
cout << "Node not found\n";
break;
}
case 3:
{
int x;
cout << "Enter the value to be deleted: ";
cin >> x;
root = deleteNode(root, x);
break;
}
case 4:
{
return 0;
break;
}
default:
break;
}
}
}

Output:
LAB-5
Q.Write algorithms for Breadth First Search (BFS) and Depth First Search (DFS)
in a graph. Also, implement them using a programming language

BFS and DFS for the Graph

First, we will look at the algorithm for BFS.

1. Take the empty queue and bool type array (visit) initialise with FALSE.
2. Push the starting node in the queue and set the value TRUE for this node in
visited array.
3. Pop out the front node of the queue and print the node.
4. Push the adjacent node of pop node in queue which are not visited. Set the
value TRUE in visited array of adding node.
5. Repeat step 3 and 4 until the queue becomes empty.

Now we will look on the algorithm for DFS.

1. Take the empty stack and bool type array (visit) initialise with FALSE.
2. Push the starting node in the stack and set the value TRUE for this node in
visited array.
3. Pop the top node from the stack and print that node.
4. Push the adjacent node of pop node in the stack which is not visited. Set the
value TRUE in visited array of adding node.
5. Repeat step 3 and 4until the stack becomes empty.

So, here we also look that the BFS and DFS algorithm is mostly similar in above
iterative approaches, only one difference is that in BFS that we will use the queue
and in DFS we will use the stack because need goes to depth for DFS.

Implementation of the graph is by the method of an adjacency list. Therefore


Implementation of adjacency list is by the using of the vector of an array

C++ code implementation for BFS and DFS :-

#include<iostream>
#include<vector>
#include<queue>
#include<stack>
using namespace std;
//add the edge in graph
void edge(vector<int>adj[],int u,int v){
adj[u].push_back(v);
}
//function for bfs traversal
void bfs(int s,vector<int>adj[],bool visit[]){
queue<int>q;//queue in STL
q.push(s);
visit[s]=true;
while(!q.empty()){
int u=q.front();
cout<<u<<" ";
q.pop();
//loop for traverse
for(int i=0;i<adj[u].size();i++){
if(!visit[adj[u][i]]){
q.push(adj[u][i]);
visit[adj[u][i]]=true;
}
}
}
}
//function for dfs traversal
void dfs(int s,vector<int>adj[],bool visit[]){
stack<int>stk;//stack in STL
stk.push(s);
visit[s]=true;
while(!stk.empty()){
int u=stk.top();
cout<<u<<" ";
stk.pop();
//loop for traverse
for(int i=0;i<adj[u].size();i++){
if(!visit[adj[u][i]]){
stk.push(adj[u][i]);
visit[adj[u][i]]=true;
}
}
}
}
//main function
int main(){
vector<int>adj[5];//vector of array to store the graph
bool visit[5];//array to check visit or not of a node
//initially all node are unvisited
for(int i=0;i<5;i++){
visit[i]=false;
}
//input for edges
edge(adj,0,2);
edge(adj,0,1);
edge(adj,1,3);
edge(adj,2,0);
edge(adj,2,3);
edge(adj,2,4);
cout<<"BFS traversal is"<<" ";
//call bfs funtion
bfs(0,adj,visit);//1 is a starting point
cout<<endl;
//again initialise all node unvisited for dfs
for(int i=0;i<5;i++){
visit[i]=false;
}
cout<<"DFS traversal is"<<" ";
//call dfs function
dfs(0,adj,visit);//1 is a starting point
}

OUTPUT:-
1.Bubble sort

#include<iostream>

using namespace std;

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

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

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

if (arr[j] > arr[j+1]) {

int temp = arr[j];

arr[j] = arr[j+1];

arr[j+1] = temp;

int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};

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

bubbleSort(arr, n);

cout << "Sorted array is: \n";

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

cout << arr[i] << " ";

return 0;

2.Insertion sort

#include<iostream>

using namespace std;

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

int key, j;

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

key = arr[i];

j = i-1;

while (j >= 0 && arr[j] > key) {

arr[j + 1] = arr[j];

j = j - 1;

arr[j + 1] = key;

int main() {

int arr[] = {64, 34, 25, 12, 22, 11, 90};

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

insertionSort(arr, n);
cout << "Sorted array is: \n";

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

cout << arr[i] << " ";

return 0;

3.Selection sort

#include<iostream>

using namespace std;

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

int i, j, min_idx;

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

min_idx = i;

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

if (arr[j] < arr[min_idx])

min_idx = j;

int temp = arr[min_idx];

arr[min_idx] = arr[i];

arr[i] = temp;

int main() {

int arr[] = {64, 34, 25, 12, 22, 11, 90};

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

selectionSort(arr, n);

cout << "Sorted array is: \n";

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


cout << arr[i] << " ";

return 0;

4.Merge sort

#include<iostream>

using namespace std;

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

int i, j, k;

int n1 = m - l + 1;

int n2 = r - m;

int L[n1], R[n2];

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

L[i] = arr[l + i];

for (j = 0; j < n2; j++)

R[j] = arr[m + 1+ j];

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);

int main() {

int arr[] = {64, 34, 25, 12, 22, 11, 90};

int n = sizeof(arr)/sizeof(arr[0]);
mergeSort(arr, 0, n-1);

cout << "Sorted array is: \n";

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

cout << arr[i] << " ";

return 0;

5.Quick sort

#include<iostream>

using namespace std;

int partition (int arr[], int low, int high) {

int pivot = arr[high];

int i = (low - 1);

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

if (arr[j] < pivot) {

i++;

int temp = arr[i];

arr[i] = arr[j];

arr[j] = temp;

int temp = arr[i + 1];

arr[i + 1] = arr[high];

arr[high] = temp;

return (i + 1);

void quickSort(int arr[], int low, int high) {

if (low < high) {


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

quickSort(arr, low, pi - 1);

quickSort(arr, pi + 1, high);

int main() {

int arr[] = {64, 34, 25, 12, 22, 11, 90};

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

quickSort(arr, 0, n-1);

cout << "Sorted array is: \n";

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

cout << arr[i] << " ";

return 0;

}
LAB-7
C implementation of the Prim's algorithm for finding the minimum spanning tree of
a connected, undirected graph:

This implementation uses the Prim's algorithm to find the minimum spanning tree of
a connected, undirected graph. It starts from a given vertex and iteratively adds the
vertex that is not yet in the tree, but has the smallest edge with a vertex that is
already in the tree. It uses a 2D array called "graph" to store the edges, and a 1D
array called "visited" to keep track of which vertices are already in the tree. It prints
the edges and the total weight of the minimum spanning tree.

It uses the adjacency matrix representation of the graph. If the graph is sparse, you
can use adjacency list representation, which will be more memory efficient.

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define MAX_VERTICES 1000


#define INF 0x3f3f3f3f

int n, m;
int graph[MAX_VERTICES][MAX_VERTICES];
bool visited[MAX_VERTICES];

void prim(int start) {


int i, j;
int min_cost = 0;
for (i = 0; i < n; i++) {
visited[i] = false;
}
visited[start] = true;
for (i = 0; i < n - 1; i++) {
int min_edge = INF;
int x = 0, y = 0;
for (j = 0; j < n; j++) {
if (visited[j]) {
for (int k = 0; k < n; k++) {
if (!visited[k] && graph[j][k]) {
if (graph[j][k] < min_edge) {
min_edge = graph[j][k];
x = j;
y = k;
}
}
}
}
}
if (min_edge != INF) {
visited[y] = true;
min_cost += min_edge;
printf("%d - %d : %d\n", x, y, min_edge);
}
}
printf("Minimum cost : %d\n", min_cost);
}

int main() {
int i, j;
scanf("%d %d", &n, &m);
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
graph[i][j] = 0;
}
}
for (i = 0; i < m; i++) {
int x, y, w;
scanf("%d %d %d", &x, &y, &w);
graph[x][y] = w;
graph[y][x] = w;
}
prim(0);
return 0;
}

C implementation of the Kruskal's algorithm for finding the minimum spanning tree
of a connected, undirected graph:

This implementation uses the union-find data structure to keep track of the
connected components in the graph. It sorts the edges by weight, and then iterates
through them in increasing order of weight, adding each edge to the minimum
spanning tree if its endpoints belong to different connected components. The edges
are stored in an array called edges and the vertices are stored in an array called
vertices.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_EDGES 1000000


#define MAX_VERTICES 1000

typedef struct {
int x, y, w;
} Edge;

Edge edges[MAX_EDGES];
int parent[MAX_VERTICES];

int cmp(const void* a, const void* b) {


Edge* e1 = (Edge*)a;
Edge* e2 = (Edge*)b;
return e1->w - e2->w;
}

int find(int x) {
if (parent[x] != x)
parent[x] = find(parent[x]);
return parent[x];
}

void union_set(int x, int y) {


int px = find(x);
int py = find(y);
parent[px] = py;
}

void kruskal(int n, int m) {


int i, count = 0;
for (i = 0; i < n; i++)
parent[i] = i;
qsort(edges, m, sizeof(Edge), cmp);
for (i = 0; i < m; i++) {
int x = edges[i].x;
int y = edges[i].y;
int w = edges[i].w;
int px = find(x);
int py = find(y);
if (px != py) {
union_set(px, py);
printf("%d %d %d\n", x, y, w);
count++;
}
if (count == n - 1)
break;
}
}

int main() {
int n, m, i;
scanf("%d %d", &n, &m);
for (i = 0; i < m; i++)
scanf("%d %d %d", &edges[i].x, &edges[i].y, &edges[i].w);
kruskal(n, m);
return 0;
}

You might also like