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

SC Lab File

The document outlines various programming exercises for a Soft Computing Lab course at Amity University Haryana, covering topics such as Armstrong numbers, matrix operations, string manipulations, and sorting algorithms. Each exercise includes a description of the task and sample C++ code implementations. The document serves as a practical guide for students to enhance their programming skills in the context of soft computing.

Uploaded by

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

SC Lab File

The document outlines various programming exercises for a Soft Computing Lab course at Amity University Haryana, covering topics such as Armstrong numbers, matrix operations, string manipulations, and sorting algorithms. Each exercise includes a description of the task and sample C++ code implementations. The document serves as a practical guide for students to enhance their programming skills in the context of soft computing.

Uploaded by

xgaming9050
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Amity University Haryana

(Gurugram)

Academic Year: 2023 -25


Department: AIIT

Submitted by : Shubham Sharma

Submitted to : Prof. Dr. Akshay Mudgal

Enroll. No. : A505145023036

Subject : Soft Computing Lab

Professor Signature
Table of Content

Sr. Questions
No.
1 Write a program to find the Armstrong numbers between two given intervals.
2 Implement a program to convert a decimal number into binary, octal, and hex.
3 Write a program to find the sum of diagonal elements of a square matrix.

4 Develop a program to transpose a matrix without using an additional matrix

5 Implement a program to merge two sorted arrays into a single sorted array.

6 Write a program to check whether two strings are anagrams.

7 Develop a program to implement the Sieve of Eratosthenes for prime numbers.

8 Write a program to find the second largest element in an array without sorting.

9 Create a program to check if a string is a valid palindrome (remove non-alphanumeric characters).

10 Write a program to implement binary search on a sorted array.

11 Write a program to implement a stack using an array (push, pop, peek).

12 Create a program to implement a queue using a linked list.

13 Write a program to perform BFS (breadth-first search) on a graph (adjacencymatrix).

14 Develop a program to reverse a linked list both iteratively and recursively.

15 Write a program to create a binary search tree (BST) and perform in-ordertraversal.
16 Create a program to implement Dijkstra’s algorithm for shortest path in a graph.

17 Write a program to implement bubble sort, selection sort, insertion sort, andcompare their
performance.
18 Develop a program to implement DFS (depth-first search) on a graph.
EXPERIMENT 1
Q Write a program to find the Armstrong numbers between two given intervals.

#include <iostream>

using namespace std;

// Function to calculate power of a number manually


int power(int base, int exp) {
int result = 1;
for (int i = 0; i < exp; i++) {
result *= base;
}
return result;
}

// Function to check if a number is an Armstrong number


bool isArmstrong(int num) {
int original = num;
int sum = 0;
int digits = 0;

// Calculate the number of digits


int temp = num;
while (temp > 0) {
digits++;
temp /= 10;
}

// Calculate the sum of each digit raised to the power of 'digits'


temp = num;
while (temp > 0) {
int digit = temp % 10;
sum += power(digit, digits); // Use custom power function
temp /= 10;
}

// Check if the sum is equal to the original number


return sum == original;
}

int main() {
int lower, upper;

// Input the intervals


cout << "Enter the lower limit: ";
cin >> lower;
cout << "Enter the upper limit: ";
cin >> upper;

cout << "Armstrong numbers between " << lower << " and " << upper << " are:" << endl;

// Find Armstrong numbers in the range


for (int i = lower; i <= upper; i++) {
if (isArmstrong(i)) {
cout << i << " ";
}
}

cout << endl;


return 0;
}

OUTPUT
EXPERIMENT 2
Q Implement a program to convert a decimal number into binary, octal, and hex.

#include <iostream>
#include <sstream>
using namespace std;

string intToString(int num) {


stringstream ss;
ss << num;
return ss.str();
}

// it convert a decimal number to binary


string decimalToBinary(int decimal) {
string binary = "";
while (decimal > 0) {
binary = intToString(decimal % 2) + binary;
decimal /= 2;
}
return binary.empty() ? "0" : binary; // Handle the case for 0
}

// Function to convert a decimal number to octal


string decimalToOctal(int decimal) {
string octal = "";
while (decimal > 0) {
octal = intToString(decimal % 8) + octal;
decimal /= 8;
}
return octal.empty() ? "0" : octal; // Handle the case for 0
}

// Function to convert a decimal number to hexadecimal


string decimalToHexadecimal(int decimal) {
string hex = "";
string hexCharacters = "0123456789ABCDEF";
while (decimal > 0) {
hex = hexCharacters[decimal % 16] + hex;
decimal /= 16;
}
return hex.empty() ? "0" : hex; // Handle the case for 0
}

int main() {
int decimal;

// Input the decimal number


cout << "Enter a decimal number: ";
cin >> decimal;

if (decimal < 0) {
cout << "Please enter a non-negative number." << endl;
return 1;
}
// Convert and display the results
cout << "Binary: " << decimalToBinary(decimal) << endl;
cout << "Octal: " << decimalToOctal(decimal) << endl;
cout << "Hexadecimal: " << decimalToHexadecimal(decimal) << endl;

return 0;
}

OUTPUT
EXPERIMENT 3
Q Write a program to find the sum of diagonal elements of a square matrix.

#include <iostream>
using namespace std;

int main() {
int n;

// Input the size of the square matrix


cout << "Enter the size of the square matrix (n x n): ";
cin >> n;

// Dynamically allocate memory for the matrix


int** matrix = new int*[n];
for (int i = 0; i < n; i++) {
matrix[i] = new int[n];
}

// Input elements of the matrix


cout << "Enter the elements of the matrix:" << endl;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> matrix[i][j];
}
}

int diagonalSum = 0;

// Sum of diagonal elements


for (int i = 0; i < n; i++) {
diagonalSum += matrix[i][i]; // Primary diagonal elements
diagonalSum += matrix[i][n - i - 1]; // Secondary diagonal elements
}

// If the matrix size is odd, we need to subtract the middle element (because it was counted twice)
if (n % 2 != 0) {
diagonalSum -= matrix[n / 2][n / 2];
}

// Output the sum of the diagonal elements


cout << "Sum of diagonal elements: " << diagonalSum << endl;

// Deallocate the memory


for (int i = 0; i < n; i++) {
delete[] matrix[i];
}
delete[] matrix;

return 0;
}
OUTPUT
EXPERIMENT 4
Q Develop a program to transpose a matrix without using an additional matrix

#include <iostream>
using namespace std;

int main() {
int n;

// Input the size of the square matrix


cout << "Enter the size of the matrix (n x n): ";
cin >> n;

int matrix[n][n]; // Declare the matrix

// Input elements of the matrix


cout << "Enter the elements of the matrix:" << endl;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> matrix[i][j];
}
}

// Transpose the matrix in place by swapping elements


for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) { // Start from j = i + 1 to avoid redundant swaps
// Swap element (i, j) with element (j, i)
swap(matrix[i][j], matrix[j][i]);
}
}

// Output the transposed matrix


cout << "Transposed matrix:" << endl;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}

return 0;
}
EXPERIMENT 5
Q Implement a program to merge two sorted arrays into a single sorted array.

#include <iostream>
using namespace std;

void mergeArrays(int arr1[], int arr2[], int n1, int n2) {


int i = 0, j = 0, k = 0;
int mergedArray[n1 + n2]; // Array to store the merged result

// Merge the two arrays


while (i < n1 && j < n2) {
if (arr1[i] < arr2[j]) {
mergedArray[k++] = arr1[i++];
} else {
mergedArray[k++] = arr2[j++];
}
}

// If any elements are left in arr1, add them


while (i < n1) {
mergedArray[k++] = arr1[i++];
}

// If any elements are left in arr2, add them


while (j < n2) {
mergedArray[k++] = arr2[j++];
}

// Output the merged array


cout << "Merged sorted array: ";
for (int i = 0; i < (n1 + n2); i++) {
cout << mergedArray[i] << " ";
}
cout << endl;
}

int main() {
int n1, n2;

// Input size and elements of the first array


cout << "Enter the size of the first array: ";
cin >> n1;
int arr1[n1];
cout << "Enter elements of the first array in sorted order: ";
for (int i = 0; i < n1; i++) {
cin >> arr1[i];
}

// Input size and elements of the second array


cout << "Enter the size of the second array: ";
cin >> n2;
int arr2[n2];
cout << "Enter elements of the second array in sorted order: ";
for (int i = 0; i < n2; i++) {
cin >> arr2[i];
}

// Merge the two arrays


mergeArrays(arr1, arr2, n1, n2);

return 0;
}
EXPERIMENT 6
Q Write a program to check whether two strings are anagrams.

#include <iostream>
#include <algorithm> // For sorting the strings
using namespace std;

bool areAnagrams(string str1, string str2) {


// If the lengths are not the same, they cannot be anagrams
if (str1.length() != str2.length()) {
return false;
}

// Sort both strings


sort(str1.begin(), str1.end());
sort(str2.begin(), str2.end());

// Compare sorted strings


return str1 == str2;
}

int main() {
string str1, str2;

// Input two strings


cout << "Enter first string: ";
cin >> str1;
cout << "Enter second string: ";
cin >> str2;

// Check and output whether the strings are anagrams


if (areAnagrams(str1, str2)) {
cout << "The strings are anagrams." << endl;
} else {
cout << "The strings are not anagrams." << endl;
}

return 0;
}
EXPERIMENT 7
Q Develop a program to implement the Sieve of Eratosthenes for prime numbers.

#include <iostream>
#include <vector>
using namespace std;

void sieveOfEratosthenes(int n) {
// Create a boolean array "prime[0..n]" and initialize all entries as true.
vector<bool> prime(n + 1, true);

// 0 and 1 are not primes


prime[0] = prime[1] = false;

// Implement the Sieve of Eratosthenes


for (int i = 2; i * i <= n; i++) {
if (prime[i]) {
// Marking all multiples of i as false (not prime)
for (int j = i * i; j <= n; j += i) {
prime[j] = false;
}}}
// Printing all prime numbers
cout << "Prime numbers up to " << n << " are: ";
for (int i = 2; i <= n; i++) {
if (prime[i]) {
cout << i << " ";
}
}
cout << endl;
}

int main() {
int n;
// Input: Limit up to which we need to find primes
cout << "Enter the limit for finding prime numbers: ";
cin >> n;

// Call the sieve function


sieveOfEratosthenes(n);

return 0;
}

OUTPUT
EXPERIMENT 8
Q Write a program to find the second largest element in an array without sorting.

#include <iostream>
#include <climits> // For INT_MIN
using namespace std;

int findSecondLargest(int arr[], int n) {


if (n < 2) {
cout << "Array is too small to find second largest element." << endl;
return -1; // Return -1 if there are fewer than 2 elements
}

int first = INT_MIN; // Initialize first to the smallest possible value


int second = INT_MIN; // Initialize second to the smallest possible value

// Traverse the array


for (int i = 0; i < n; i++) {
if (arr[i] > first) {
second = first; // Update second to the previous largest
first = arr[i]; // Update first to the current largest
} else if (arr[i] > second && arr[i] != first) {
second = arr[i]; // Update second if the current element is not equal to first
}
}

return second; // Return the second largest element


}

int main() {
int n;

// Input size of array


cout << "Enter the size of the array: ";
cin >> n;

int arr[n];

// Input elements of the array


cout << "Enter the elements of the array: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}

// Find and print the second largest element


int secondLargest = findSecondLargest(arr, n);

if (secondLargest != -1) {
cout << "The second largest element is: " << secondLargest << endl;
}

return 0;
}
OUTPUT
EXPERIMENT 9
Q Create a program to check if a string is a valid palindrome (remove non-
alphanumeric characters).

#include <iostream>
#include <cctype> // For isalnum and tolower functions
using namespace std;

bool isPalindrome(string str) {


// Remove non-alphanumeric characters and convert to lowercase
string cleanedStr = "";
for (char ch : str) {
if (isalnum(ch)) {
cleanedStr += tolower(ch); // Append lowercase alphanumeric characters
}
}

// Check if the cleaned string is equal to its reverse


int left = 0;
int right = cleanedStr.length() - 1;
while (left < right) {
if (cleanedStr[left] != cleanedStr[right]) {
return false; // If mismatch, it's not a palindrome
}
left++;
right--;
}

return true; // If no mismatch, it is a palindrome


}

int main() {
string input;

// Input the string to check


cout << "Enter a string: ";
getline(cin, input);

// Check if the string is a palindrome


if (isPalindrome(input)) {
cout << "The string is a valid palindrome." << endl;
} else {
cout << "The string is not a valid palindrome." << endl;
}

return 0;
}

OUTPUT
EXPERIMENT 10
Q Write a program to implement binary search on a sorted array.

#include <iostream>
using namespace std;

int binarySearch(int arr[], int n, int key) {


int low = 0;
int high = n - 1;

// Perform binary search


while (low <= high) {
int mid = low + (high - low) / 2;

// Check if key is present at mid


if (arr[mid] == key) {
return mid; // Element found at index mid
}

// If key is smaller than mid, search the left half


if (arr[mid] > key) {
high = mid - 1;
}
// If key is larger than mid, search the right half
else {
low = mid + 1;
}
}

// If the element is not found


return -1;
}

int main() {
int n, key;

// Input size of the array


cout << "Enter the size of the array: ";
cin >> n;

int arr[n];

// Input elements of the sorted array


cout << "Enter " << n << " sorted elements: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}

// Input the key to search for


cout << "Enter the element to search for: ";
cin >> key;

// Perform binary search and print the result


int result = binarySearch(arr, n, key);

if (result != -1) {
cout << "Element found at index " << result << endl;
} else {
cout << "Element not found in the array." << endl;
}

return 0;
}

OUTPUT
EXPERIMENT 11
QWrite a program to implement a stack using an array (push, pop, peek).

#include<iostream>
using namespace std;
class stack{
//stack implementation through array
public:
int *arr;
int top;
int size;
stack(int size){
this->size=size;
arr=new int [size];
top=-1;
}

void push(int data){


if(top<size-1){
top++;
arr[top]=data;
}
else{
cout<<" stack overflow "<<endl;
exit(0);
}
}

void pop(){
if(top>=0){
top--;
}
else
cout<<" empty stack "<<endl;
}

bool empty(){
return top==-1;
}

int Top(){
if(!empty()){
return arr[top];
}
else{
cout<<" empty stack "<<endl;
}
return -1;
}

int findmiddle(){
int n =top/2;
cout<<"mid is at nth position and is "<<arr[n];
return n;
}

};

int main(){
stack s(3);
s.push(1);
s.push(2);
s.push(3);
// s.push(4);
// s.push(5);
// s.push(6);
// s.push(7);
// s.push(8);

cout<<"Peek function "<<s.Top()<<endl;


s.pop();
cout<<"Peek function "<<s.Top()<<endl;
cout<<"if zero than empty else not "<<s.empty()<<endl;
int mid = s.findmiddle();
return 0;
}
OUTPUT
EXPERIMENT 12
Q Create a program to implement a queue using a linked list.

#include <iostream>
using namespace std;

// Node structure to represent each element in the queue


struct Node {
int data;
Node* next;

// Constructor to initialize node with data


Node(int value) {
data = value;
next = nullptr;
}
};

// Queue class using a linked list


class Queue {
private:
Node* front; // Pointer to the front of the queue
Node* rear; // Pointer to the rear of the queue

public:
// Constructor to initialize the queue
Queue() {
front = nullptr;
rear = nullptr;
}

// Destructor to free dynamically allocated memory


~Queue() {
while (!isEmpty()) {
dequeue(); // Remove all elements
}
}

// Check if the queue is empty


bool isEmpty() {
return front == nullptr;
}

// Enqueue operation (insert at rear)


void enqueue(int value) {
Node* newNode = new Node(value);
if (isEmpty()) {
front = rear = newNode; // If queue is empty, front and rear are the same
} else {
rear->next = newNode; // Add new node at the rear
rear = newNode; // Update rear to the new node
}
cout << value << " enqueued to the queue" << endl;
}

// Dequeue operation (remove from front)


void dequeue() {
if (isEmpty()) {
cout << "Queue is empty. Cannot dequeue." << endl;
return;
}
Node* temp = front; // Temporarily hold the front node
front = front->next; // Move front to the next node
if (front == nullptr) {
rear = nullptr; // If the queue becomes empty, set rear to nullptr
}
delete temp; // Free the memory of the dequeued node
cout << "Dequeued from the queue" << endl;
}

// Get the front element of the queue


int peek() {
if (isEmpty()) {
cout << "Queue is empty." << endl;
return -1; // Return -1 if queue is empty
}
return front->data; // Return the data of the front node
}

// Display all elements in the queue


void display() {
if (isEmpty()) {
cout << "Queue is empty." << endl;
return;
}
Node* temp = front;
cout << "Queue elements: ";
while (temp != nullptr) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
};

// Main function to demonstrate the queue operations


int main() {
Queue q;

// Enqueue some elements


q.enqueue(10);
q.enqueue(20);
q.enqueue(30);
q.enqueue(40);

// Display the queue


q.display();

// Dequeue some elements


q.dequeue();
q.dequeue();
// Display the queue again
q.display();

// Peek the front element


cout << "Front element: " << q.peek() << endl;

// Dequeue remaining elements


q.dequeue();
q.dequeue();

// Try to dequeue from an empty queue


q.dequeue();

return 0;
}
OUTPUT
EXPERIMENT 13
Q Write a program to perform BFS (breadth-first search) on a graph (adjacency
matrix).

#include <iostream>
#include <queue> // for using queue
#include <vector> // for using vector
using namespace std;

// Function to perform BFS on a graph represented by an adjacency matrix


void BFS(int graph[][5], int startNode, int numNodes) {
vector<bool> visited(numNodes, false); // visited array to keep track of visited nodes
queue<int> q; // queue for BFS

// Start with the given node and mark it as visited


visited[startNode] = true;
q.push(startNode);

cout << "BFS traversal starting from node " << startNode << ": ";

while (!q.empty()) {
// Dequeue a node from the front
int currentNode = q.front();
q.pop();

// Print the current node


cout << currentNode << " ";

// Visit all the unvisited neighbors of the current node


for (int i = 0; i < numNodes; ++i) {
if (graph[currentNode][i] == 1 && !visited[i]) { // If there's an edge and the node is unvisited
q.push(i);
visited[i] = true;
}
}
}
cout << endl;
}
int main() {
// Define a graph using an adjacency matrix
int graph[5][5] = {
{0, 1, 1, 0, 0}, // Node 0 is connected to 1 and 2
{1, 0, 1, 1, 0}, // Node 1 is connected to 0, 2, and 3
{1, 1, 0, 1, 1}, // Node 2 is connected to 0, 1, 3, and 4
{0, 1, 1, 0, 1}, // Node 3 is connected to 1, 2, and 4
{0, 0, 1, 1, 0} // Node 4 is connected to 2 and 3
};
int startNode = 0; // Starting node for BFS (Node 0)

int numNodes = 5; // Number of nodes in the graph


BFS(graph, startNode, numNodes); // Call BFS starting from node 0

return 0;
}
EXPERIMENT 14
Q Develop a program to reverse a linked list both iteratively and recursively.

#include <iostream>
using namespace std;

// Node structure representing each element in the linked list


struct Node {
int data;
Node* next;

// Constructor to create a new node


Node(int value) {
data = value;
next = nullptr;
}
};

// Linked List class


class LinkedList {
private:
Node* head; // Pointer to the first node (head) of the linked list

public:
// Constructor initializes the list as empty
LinkedList() {
head = nullptr;
}

// Function to insert a new node at the end of the linked list


void insert(int value) {
Node* newNode = new Node(value);
if (head == nullptr) {
head = newNode; // If list is empty, make this new node the head
} else {
Node* temp = head;
while (temp->next != nullptr) { // Traverse to the end of the list
temp = temp->next;
}
temp->next = newNode; // Insert the new node at the end
}
}

// Function to print the linked list


void print() {
Node* temp = head;
while (temp != nullptr) {
cout << temp->data << " "; // Print each node's data
temp = temp->next;
}
cout << endl;
}

// Iterative method to reverse the linked list


void reverseIterative() {
Node* prev = nullptr;
Node* current = head;
Node* next = nullptr;

while (current != nullptr) {


next = current->next; // Save the next node
current->next = prev; // Reverse the current node's pointer
prev = current; // Move prev and current one step forward
current = next;
}
head = prev; // Update the head to the new first node
}

// Recursive method to reverse the linked list


Node* reverseRecursive(Node* node) {
if (node == nullptr || node->next == nullptr) {
return node; // Base case: if the node is null or it's the last node
}

Node* rest = reverseRecursive(node->next); // Reverse the rest of the list


node->next->next = node; // Link the current node to the reversed part
node->next = nullptr; // Set the current node's next to null
return rest; // Return the new head
}

// Wrapper function for recursive reversal


void reverseRecursive() {
head = reverseRecursive(head);
}
};

// Main function
int main() {
LinkedList list;

// Insert nodes into the list


list.insert(1);
list.insert(2);
list.insert(3);
list.insert(4);
list.insert(5);

cout << "Original List: ";


list.print(); // Print the original list

// Reverse the list iteratively


list.reverseIterative();
cout << "Reversed List (Iterative): ";
list.print(); // Print the list after iterative reversal

// Reverse the list recursively


list.reverseRecursive();
cout << "Reversed List (Recursive): ";
list.print(); // Print the list after recursive reversal

return 0;
}
EXPERIMENT 15
Q Write a program to create a binary search tree (BST) and perform in-order
traversal.

#include <iostream>
using namespace std;

// Node structure for BST


struct Node {
int data; // Data stored in the node
Node* left; // Pointer to the left child
Node* right; // Pointer to the right child

// Constructor to initialize a node


Node(int value) {
data = value;
left = nullptr;
right = nullptr;
}
};

// Function to insert a node into the BST


Node* insert(Node* root, int value) {
// If the tree is empty, create a new node as the root
if (root == nullptr) {
return new Node(value);
}

// Recursively insert into the left or right subtree


if (value < root->data) {
root->left = insert(root->left, value);
} else if (value > root->data) {
root->right = insert(root->right, value);
}

return root; // Return the unchanged root pointer


}

// Function for in-order traversal of the BST


void inOrderTraversal(Node* root) {
if (root == nullptr) {
return; // Base case: if the node is null, return
}

// Visit the left subtree


inOrderTraversal(root->left);

// Print the current node's data


cout << root->data << " ";

// Visit the right subtree


inOrderTraversal(root->right);
}

// Main function
int main() {
Node* root = nullptr; // Initialize the root of the BST as null
// Insert nodes into the BST
root = insert(root, 50);
insert(root, 30);
insert(root, 70);
insert(root, 20);
insert(root, 40);
insert(root, 60);
insert(root, 80);

// Perform in-order traversal


cout << "In-order traversal of the BST: ";
inOrderTraversal(root);
cout << endl;

return 0;
}
OUTPUT
EXPERIMENT 16
Q Create a program to implement Dijkstra’s algorithm for shortest path in a graph.

#include <iostream>
#include <vector>
#include <queue>
#include <climits> // For INT_MAX
using namespace std;

// Function to perform Dijkstra's algorithm


void dijkstra(int start, vector<vector<pair<int, int>>>& graph, int vertices) {
// Distance vector to store the shortest distance to each vertex
vector<int> dist(vertices, INT_MAX);
dist[start] = 0;

// Priority queue to select the vertex with the smallest distance


// The pair is in the form (distance, vertex)
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> pq;
pq.push({0, start});

while (!pq.empty()) {
int current_dist = pq.top().first; // Distance of current vertex
int current_vertex = pq.top().second;
pq.pop();

// If the distance is already larger, skip this vertex


if (current_dist > dist[current_vertex]) {
continue;
}

// Traverse all neighbors of the current vertex


for (auto& neighbor : graph[current_vertex]) {
int next_vertex = neighbor.first;
int weight = neighbor.second;
if (dist[current_vertex] + weight < dist[next_vertex]) {
dist[next_vertex] = dist[current_vertex] + weight;
pq.push({dist[next_vertex], next_vertex});
}
}
}

// Print the shortest distances from the start vertex


cout << "Vertex\tDistance from Source" << endl;
for (int i = 0; i < vertices; i++) {
cout << i << "\t" << dist[i] << endl;
}
}
// Main function
int main() {
int vertices, edges;
cout << "Enter the number of vertices and edges: ";
cin >> vertices >> edges;

// Adjacency list representation of the graph


vector<vector<pair<int, int>>> graph(vertices);

cout << "Enter the edges (u, v, weight):" << endl;


for (int i = 0; i < edges; i++) {
int u, v, weight;
cin >> u >> v >> weight;
graph[u].push_back({v, weight});
graph[v].push_back({u, weight}); // Comment this line if the graph is directed
}
int start;
cout << "Enter the starting vertex: ";
cin >> start;

// Perform Dijkstra's algorithm


dijkstra(start, graph, vertices);

return 0;
}
OUTPUT
EXPERIMENT 17
Q Write a program to implement bubble sort, selection sort, insertion sort, and
compare their performance.

#include <iostream>
#include <vector>
#include <chrono> // For measuring execution time
using namespace std;
// Bubble Sort
void bubbleSort(vector<int>& arr) {
int n = arr.size();
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
swap(arr[j], arr[j + 1]);
}}}}

// Selection Sort
void selectionSort(vector<int>& arr) {
int n = arr.size();
for (int i = 0; i < n - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
swap(arr[i], arr[minIndex]);
}
}

// Insertion Sort
void insertionSort(vector<int>& arr) {
int n = arr.size();
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}

// Function to display an array


void displayArray(const vector<int>& arr) {
for (int num : arr) {
cout << num << " ";
}
cout << endl;}// Main Function
int main() {
vector<int> arr = {64, 34, 25, 12, 22, 11, 90};
// Bubble Sort
vector<int> bubbleArr = arr;
auto startBubble = chrono::high_resolution_clock::now();
bubbleSort(bubbleArr);
auto endBubble = chrono::high_resolution_clock::now();
auto durationBubble = chrono::duration_cast<chrono::microseconds>(endBubble -
startBubble).count();
cout << "Bubble Sort:\nSorted Array: ";
displayArray(bubbleArr);
cout << "Execution Time: " << durationBubble << " microseconds\n\n";

// Selection Sort
vector<int> selectionArr = arr;
auto startSelection = chrono::high_resolution_clock::now();
selectionSort(selectionArr);
auto endSelection = chrono::high_resolution_clock::now();
auto durationSelection = chrono::duration_cast<chrono::microseconds>(endSelection -
startSelection).count();
cout << "Selection Sort:\nSorted Array: ";
displayArray(selectionArr);
cout << "Execution Time: " << durationSelection << " microseconds\n\n";

// Insertion Sort
vector<int> insertionArr = arr;
auto startInsertion = chrono::high_resolution_clock::now();
insertionSort(insertionArr);
auto endInsertion = chrono::high_resolution_clock::now();
auto durationInsertion = chrono::duration_cast<chrono::microseconds>(endInsertion -
startInsertion).count();
cout << "Insertion Sort:\nSorted Array: ";
displayArray(insertionArr);
cout << "Execution Time: " << durationInsertion << " microseconds\n";
return 0;}

OUTPUT
EXPERIMENT 18
Q Develop a program to implement DFS (depth-first search) on a graph.

#include <iostream>
#include <vector>
using namespace std;

// Function to perform DFS


void dfs(int node, vector<vector<int>>& graph, vector<bool>& visited) {
// Mark the current node as visited
visited[node] = true;
cout << node << " ";

// Recursively visit all unvisited neighbors


for (int neighbor : graph[node]) {
if (!visited[neighbor]) {
dfs(neighbor, graph, visited);
}
}
}

int main() {
int vertices, edges;
cout << "Enter the number of vertices and edges: ";
cin >> vertices >> edges;

// Create adjacency list for the graph


vector<vector<int>> graph(vertices);

cout << "Enter the edges (u, v): " << endl;
for (int i = 0; i < edges; i++) {
int u, v;
cin >> u >> v;
graph[u].push_back(v);
graph[v].push_back(u); // Comment this line if the graph is directed
}

// Array to track visited nodes


vector<bool> visited(vertices, false);

int startNode;
cout << "Enter the starting node for DFS: ";
cin >> startNode;

cout << "DFS Traversal starting from node " << startNode << ": ";
dfs(startNode, graph, visited);
cout << endl;

return 0;
}

You might also like