0% found this document useful (0 votes)
7 views25 pages

DAA

The document contains multiple C and C++ programs that implement various sorting algorithms (Bubble Sort, Insertion Sort, Selection Sort, Merge Sort), a binary search algorithm, Strassen's algorithm for matrix multiplication, Prim's and Kruskal's algorithms for finding Minimum Spanning Trees, and Dijkstra's algorithm for finding the shortest path in a graph. Each program includes a main function that demonstrates the algorithm's functionality with sample data. The code snippets are well-structured and provide clear examples of algorithm implementations.

Uploaded by

hussainmohd90888
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)
7 views25 pages

DAA

The document contains multiple C and C++ programs that implement various sorting algorithms (Bubble Sort, Insertion Sort, Selection Sort, Merge Sort), a binary search algorithm, Strassen's algorithm for matrix multiplication, Prim's and Kruskal's algorithms for finding Minimum Spanning Trees, and Dijkstra's algorithm for finding the shortest path in a graph. Each program includes a main function that demonstrates the algorithm's functionality with sample data. The code snippets are well-structured and provide clear examples of algorithm implementations.

Uploaded by

hussainmohd90888
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/ 25

1.

// C program for implementation of Bubble sort

#include <stdio.h>

void swap(int* arr, int i, int j) {

int temp = arr[i];

arr[i] = arr[j];

arr[j] = temp;

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

int i, j;

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

// Last i elements are already in place, so the loop

// will only num n - i - 1 times

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

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

swap(arr, j, j + 1);

int main() {

int arr[] = { 6, 0, 3, 5 };

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

printf("Unsorted array: ");

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

printf("%d ", arr[i]);

printf("\n");
// Calling bubble sort on array arr

bubbleSort(arr, N);

printf("Sorted array: ");

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

printf("%d ", arr[i]);

printf("\n");

return 0;

2 . // C program to implement insertion sort

#include <math.h>

#include <stdio.h>

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

// Starting from the second element

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

int key = arr[i];

int j = i - 1;

// Move elements of arr[0..i-1], that are

// greater than key, to one position to

// the right of their current position

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

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

j = j - 1;
}

// Move the key to its correct position

arr[j + 1] = key;

int main() {

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

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

printf("Unsorted array: ");

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

printf("%d ", arr[i]);

printf("\n");

// Calling insertion sort on array arr

insertionSort(arr, N);

printf("Sorted array: ");

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

printf("%d ", arr[i]);

printf("\n");

return 0;

3 // C program for implementation of selection sort


#include <stdio.h>

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

// Start with the whole array as unsorted and one by

// one move boundary of unsorted subarray towards right

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

// Find the minimum element in unsorted array

int min_idx = i;

for (int j = i + 1; j < N; j++) {

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

min_idx = j;

// Swap the found minimum element with the first

// element in the unsorted part

int temp = arr[min_idx];

arr[min_idx] = arr[i];

arr[i] = temp;

int main() {

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

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

printf("Unsorted array: \n");

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

printf("%d ", arr[i]);

}
printf("\n");

// Calling selection sort

selectionSort(arr, N);

printf("Sorted array: \n");

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

printf("%d ", arr[i]);

printf("\n");

return 0;

4 . // C program for the implementation of merge sort

#include <stdio.h>

#include <stdlib.h>

// Merges two subarrays of arr[].

// First subarray is arr[left..mid]

// Second subarray is arr[mid+1..right]

void merge(int arr[], int left, int mid, int right) {

int i, j, k;

int n1 = mid - left + 1;

int n2 = right - mid;

// Create temporary arrays

int leftArr[n1], rightArr[n2];

// Copy data to temporary arrays

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


leftArr[i] = arr[left + i];

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

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

// Merge the temporary arrays back into arr[left..right]

i = 0;

j = 0;

k = left;

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

if (leftArr[i] <= rightArr[j]) {

arr[k] = leftArr[i];

i++;

else {

arr[k] = rightArr[j];

j++;

k++;

// Copy the remaining elements of leftArr[], if any

while (i < n1) {

arr[k] = leftArr[i];

i++;

k++;

// Copy the remaining elements of rightArr[], if any

while (j < n2) {

arr[k] = rightArr[j];

j++;
k++;

// The subarray to be sorted is in the index range [left-right]

void mergeSort(int arr[], int left, int right) {

if (left < right) {

// Calculate the midpoint

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

// Sort first and second halves

mergeSort(arr, left, mid);

mergeSort(arr, mid + 1, right);

// Merge the sorted halves

merge(arr, left, mid, right);

int main() {

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

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

// Sorting arr using mergesort

mergeSort(arr, 0, n - 1);

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

printf("%d ", arr[i]);

return 0;

}
5. // code for binary search

include <stdio.h>

int main()

int c, first, last, middle, n, search, array[100];

printf("Enter number of elements\n");

scanf("%d", &n);

printf("Enter %d integers\n", n);

for (c = 0; c < n; c++)

scanf("%d", &array[c]);

printf("Enter value to find\n");

scanf("%d", &search);

first = 0;

last = n - 1;

middle = (first+last)/2;

while (first <= last) {

if (array[middle] < search)

first = middle + 1;

else if (array[middle] == search) {

printf("%d found at location %d.\n", search, middle+1);

break;

else

last = middle - 1;
middle = (first + last)/2;

if (first > last)

printf("Not found! %d isn't present in the list.\n", search);

return 0;

6 .*C code of two 2 by 2 matrix multiplication using Strassen's algorithm*/

#include<stdio.h>

int main(){

int a[2][2], b[2][2], c[2][2], i, j;

int m1, m2, m3, m4 , m5, m6, m7;

printf("Enter the 4 elements of first matrix: ");

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

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

scanf("%d", &a[i][j]);

printf("Enter the 4 elements of second matrix: ");

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

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

scanf("%d", &b[i][j]);

printf("\nThe first matrix is\n");

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

printf("\n");

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

printf("%d\t", a[i][j]);

}
printf("\nThe second matrix is\n");

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

printf("\n");

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

printf("%d\t", b[i][j]);

m1= (a[0][0] + a[1][1]) * (b[0][0] + b[1][1]);

m2= (a[1][0] + a[1][1]) * b[0][0];

m3= a[0][0] * (b[0][1] - b[1][1]);

m4= a[1][1] * (b[1][0] - b[0][0]);

m5= (a[0][0] + a[0][1]) * b[1][1];

m6= (a[1][0] - a[0][0]) * (b[0][0]+b[0][1]);

m7= (a[0][1] - a[1][1]) * (b[1][0]+b[1][1]);

c[0][0] = m1 + m4- m5 + m7;

c[0][1] = m3 + m5;

c[1][0] = m2 + m4;

c[1][1] = m1 - m2 + m3 + m6;

printf("\nAfter multiplication using Strassen's algorithm \n");

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

printf("\n");

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

printf("%d\t", c[i][j]);

return 0;

}
Output :

Enter the 4 elements of first matrix:

12

34

Enter the 4 elements of second matrix:

56

78

The first matrix is

1 2

3 4

The second matrix is

5 6

7 8

After multiplication using Strassen's algorithm

19 22

43 50

7 . // A C++ program for Prim's Minimum Spanning Tree (MST) algorithm. The program is for
adjacency matrix representation of the graph .

#include <bits/stdc++.h>

using namespace std;

// Number of vertices in the graph

#define V 5

// A utility function to find the vertex with minimum key value, from the set of vertices not yet
included in MST
int minKey(vector<int> &key, vector<bool> &mstSet) {

// Initialize min value

int min = INT_MAX, min_index;

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

if (mstSet[v] == false && key[v] < min)

min = key[v], min_index = v;

return min_index;

// A utility function to print the constructed MST stored in parent[]

void printMST(vector<int> &parent, vector<vector<int>> &graph) {

cout << "Edge \tWeight\n";

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

cout << parent[i] << " - " << i << " \t"

<< graph[i][parent[i]] << " \n";

// Function to construct and print MST for a graph represented using adjacency matrix
representation

void primMST(vector<vector<int>> &graph) {

// Array to store constructed MST

vector<int> parent(V);

// Key values used to pick minimum weight edge in cut

vector<int> key(V);

// To represent set of vertices included in MST


vector<bool> mstSet(V);

// Initialize all keys as INFINITE

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

key[i] = INT_MAX, mstSet[i] = false;

// Always include first 1st vertex in MST.Make key 0 so that this vertex is picked as first vertex.

key[0] = 0;

// First node is always root of MST

parent[0] = -1;

// The MST will have V vertices

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

// Pick the minimum key vertex from the set of vertices not yet included in MST

int u = minKey(key, mstSet);

// Add the picked vertex to the MST Set

mstSet[u] = true;

// Update key value and parent index of the adjacent vertices of the picked vertex .Consider
only those vertices which are not yet included in MST

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

// graph[u][v] is non zero only for adjacent vertices of m mstSet[v] is false for vertices not
yet included in MST Update the key only

// if graph[u][v] is smaller than key[v]

if (graph[u][v] && mstSet[v] == false

&& graph[u][v] < key[v])

parent[v] = u, key[v] = graph[u][v];

}
// Print the constructed MST

printMST(parent, graph);

// Driver's code

int main() {

vector<vector<int>> graph = { { 0, 2, 0, 6,0}, { 2, 0, 3, 8, 5 }, { 0, 3, 0, 0, 7}, { 6, 8, 0, 0, 9 },

{ 0, 5, 7, 9, 0 } };

// Print the solution

primMST(graph);

return 0;

8 . //Kruskal Algorithm

#include <stdio.h>

#include <stdlib.h>

const int inf = 999999;

int k, a, b, u, v, n, ne = 1;

int mincost = 0;

int cost[3][3] = {{0, 10, 20},{12, 0,15},{16, 18, 0}};

int p[9] = {0};

int applyfind(int i)

while(p[i] != 0)

i=p[i];

return i;

int applyunion(int i,int j)


{

if(i!=j) {

p[j]=i;

return 1;

return 0;

int main()

n = 3;

int i, j;

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

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

if (cost[i][j] == 0) {

cost[i][j] = inf;

printf("Minimum Cost Spanning Tree: \n");

while(ne < n) {

int min_val = inf;

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

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

if(cost[i][j] < min_val) {

min_val = cost[i][j];

a = u = i;

b = v = j;

u = applyfind(u);
v = applyfind(v);

if(applyunion(u, v) != 0) {

printf("%d -> %d\n", a, b);

mincost +=min_val;

cost[a][b] = cost[b][a] = 999;

ne++;

printf("Minimum cost = %d",mincost);

return 0;

Output:

Minimum Cost Spanning Tree:

0 -> 1

1 -> 2

Minimum cost = 25

9 .// C program for Dijkstra's single source shortest path algorithm. The program is for adjacency
matrix representation of the graph.

#include <limits.h>

#include <stdbool.h>

#include <stdio.h>

// Number of vertices in the graph

#define V 9
// A utility function to find the vertex with minimum distance value, from the set of vertices not
yet included in shortest path tree.

int minDistance(int dist[], bool sptSet[])

// Initialize min value

int min = INT_MAX, min_index;

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

if (sptSet[v] == false && dist[v] <= min)

min = dist[v], min_index = v;

return min_index;

// A utility function to print the constructed distance array

void printSolution(int dist[])

printf("Vertex \t\t Distance from Source\n");

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

printf("%d \t\t\t\t %d\n", i, dist[i]);

// Function that implements Dijkstra's single source shortest path algorithm for a graph
represented using adjacency matrix representation

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

int dist[V]; // The output array. dist[i] will hold the shortest distance from src to i

bool sptSet[V]; // sptSet[i] will be true if vertex i is included in shortest path tree or shortest
distance from src to i is finalized

// Initialize all distances as INFINITE and stpSet[] as


// false

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

dist[i] = INT_MAX, sptSet[i] = false;

// Distance of source vertex from itself is always 0

dist[src] = 0;

// Find shortest path for all vertices

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


// Pick the minimum distance vertex from the set of vertices not yet processed. u is always
equal to src in the first iteration.

int u = minDistance(dist, sptSet);

// Mark the picked vertex as processed

sptSet[u] = true;

// Update dist value of the adjacent vertices of the picked vertex.

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

// Update dist[v] only if is not in sptSet, there is an edge from u to v, and total weight of
path from src to v throughu is smaller than current value of dist[v]

if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX && dist[u] + graph[u][v] < dist[v])

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

// print the constructed distance array

printSolution(dist);

// driver's code

int main()

{
/* Let us create the example graph discussed above */

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, 0, 0, 9, 0, 10, 0, 0, 0 }, { 0, 0, 4, 14, 10, 0, 2, 0, 0 }, { 0, 0, 0, 0, 0, 2,
0, 1, 6 }, { 8, 11, 0, 0, 0, 0, 1, 0, 7 }, { 0, 0, 2, 0, 0, 0, 6, 7, 0 } };

// Function call

dijkstra(graph, 0);

return 0;

10 .C program for the above approach

#include <stdbool.h>

#include <stdio.h>

#include <stdlib.h>

// A structure to represent a job

typedef struct Job {

char id; // Job Id

int dead; // Deadline of job

int profit; // Profit if job is over before or on

// deadline

} Job;

// This function is used for sorting all jobs according to

// profit

int compare(const void* a, const void* b)

Job* temp1 = (Job*)a;

Job* temp2 = (Job*)b;

return (temp2->profit - temp1->profit);

}
// Find minimum between two numbers.

int min(int num1, int num2)

return (num1 > num2) ? num2 : num1;

// Returns maximum profit from jobs

void printJobScheduling(Job arr[], int n)

// Sort all jobs according to decreasing order of profit

qsort(arr, n, sizeof(Job), compare);

int result[n]; // To store result (Sequence of jobs)

bool slot[n]; // To keep track of free time slots

// Initialize all slots to be free

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

slot[i] = false;

// Iterate through all given jobs

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

// Find a free slot for this job (Note that we start

// from the last possible slot)

for (int j = min(n, arr[i].dead) - 1; j >= 0; j--) {

// Free slot found

if (slot[j] == false) {

result[j] = i; // Add this job to result

slot[j] = true; // Make this slot occupied


break;

// Print the result

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

if (slot[i])

printf("%c ", arr[result[i]].id);

// Driver's code

int main()

Job arr[] = { { 'a', 2, 100 },

{ 'b', 1, 19 },

{ 'c', 2, 27 },

{ 'd', 1, 25 },

{ 'e', 3, 15 } };

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

printf(

"Following is maximum profit sequence of jobs \n");

// Function call

printJobScheduling(arr, n);

return 0;

}
11 . Code for Queen Problem .

#include <bits/stdc++.h>

using namespace std;

// Function to check if the current placement is safe

bool isSafe(const vector<int>& board, int currRow,

int currCol) {

// Check all previously placed queens

for(int i = 0; i < board.size(); ++i) {

int placedRow = board[i];

// Columns are 1-based

int placedCol = i + 1;

// Check if the queen is on the same diagonal

if(abs(placedRow - currRow) ==

abs(placedCol - currCol)) {

return false; // Not safe

// Safe to place the queen

return true;

// Recursive function to generate all possible permutations

void nQueenUtil(int col, int n, vector<int>& board, vector<vector<int>>& result, vector<bool>&


visited)

// If all queens are placed, add into result


if(col > n) {

result.push_back(board)

return;

// Try placing a queen in each row of the current column

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

// Check if the row is already used

if(!visited[row]) {

// Check if it's safe to place the queen

if(isSafe(board, row, col)) {

// Mark the row as used

visited[row] = true;

// Place the queen

board.push_back(row);

// Recur to place the next queen

nQueenUtil(col + 1, n, board,

result, visited);

// Backtrack: remove the queen

board.pop_back();

visited[row] = false; // Unmark row

}
// Main function to find all distinct

// result to the n-queens puzzle

vector<vector<int>> nQueen(int n) {

vector<vector<int>> result;

// Current board configuration

vector<int> board;

// Track used rows

vector<bool> visited(n + 1, false);

// Start solving from the first column

nQueenUtil(1, n, board, result, visited);

return result;

int main() {

int n = 4;

vector<vector<int>> result = nQueen(n);

for(auto &res : result) {

cout << "[";

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

cout << res[i];

if(i != n - 1) cout << ", ";

cout << "]\n";

return 0;
}

12 . Code for sum of subset .

#include <stdio.h>

int isSubsetSum(int set[], int n, int sum) {

// Base Cases

if (sum == 0) return 1; // Found a subset with the given sum

if (n == 0) return 0; // No more elements left to explore

// If the last element is greater than the sum, skip it

if (set[n-1] > sum) return isSubsetSum(set, n-1, sum);

// Check two possibilities:

// 1. Include the last element in the subset

// 2. Exclude the last element from the subset

return isSubsetSum(set, n-1, sum) || isSubsetSum(set, n-1, sum - set[n-1]);

int main() {

int set[] = {3, 34, 4, 12, 5, 2};

int sum = 9;

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

if (isSubsetSum(set, n, sum)) printf("Found a subset with given sum");

else printf("No subset with given sum");

return 0;

You might also like