Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
13 views23 pages

DAA Lab

The document contains multiple C programs that implement various algorithms including selection sort, quick sort, merge sort, the 0-1 knapsack problem, Dijkstra's algorithm for shortest paths, Kruskal's algorithm for minimum spanning trees, and Prim's algorithm for minimum spanning trees. Each program includes the necessary functions and a main driver code to demonstrate the algorithms' functionalities. The implementations are designed to handle arrays and graphs, showcasing fundamental concepts in algorithm design and analysis.

Uploaded by

Debjit Dutta
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)
13 views23 pages

DAA Lab

The document contains multiple C programs that implement various algorithms including selection sort, quick sort, merge sort, the 0-1 knapsack problem, Dijkstra's algorithm for shortest paths, Kruskal's algorithm for minimum spanning trees, and Prim's algorithm for minimum spanning trees. Each program includes the necessary functions and a main driver code to demonstrate the algorithms' functionalities. The implementations are designed to handle arrays and graphs, showcasing fundamental concepts in algorithm design and analysis.

Uploaded by

Debjit Dutta
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/ 23

1.

// C program for implementation of selection sort

#include <stdio.h>

void selectionSort(int arr[], int N)

// Start with the whole array as unsored 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");

2. // C program to implement Quick Sort Algorithm

#include <stdio.h>

void swap(int* a, int* b)

int temp = *a;

*a = *b;

*b = temp;

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

// Initialize pivot to be the first element

int p = arr[low];

int i = low;

int j = high;

while (i < j) {

// Find the first element greater than


// the pivot (from starting)

while (arr[i] <= p && i <= high - 1) {

i++;

// Find the first element smaller than

// the pivot (from last)

while (arr[j] > p && j >= low + 1) {

j--;

if (i < j) {

swap(&arr[i], &arr[j]);

swap(&arr[low], &arr[j]);

return j;

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

if (low < high)

// call partition function to find Partition Index

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

// Recursively call quickSort() for left and right

// half based on Partition Index

quickSort(arr, low, pi - 1);

quickSort(arr, pi + 1, high);

}
int main()

int arr[] = { 4, 2, 5, 3, 1 };

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

// calling quickSort() to sort the given array

quickSort(arr, 0, n - 1);

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

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

return 0;

3. // 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;

4. // C Program for 0-1 KnapSack Problem using Recursion

#include <stdio.h>

// Function to find maximum between two numbers

int max(int a, int b)

{
if (a > b)

return a;

return b;

// Returns the maximum value that can be put in a knapsack

// of capacity W

int knapsackRecursive(int W, int wt[], int val[], int n)

// Base Case

if (n == 0 || W == 0)

return 0;

if (wt[n - 1] > W)

return knapsackRecursive(W, wt, val, n - 1);

else

return max(val[n - 1]

+ knapsackRecursive(W - wt[n - 1],

wt, val, n - 1),

knapsackRecursive(W, wt, val, n - 1));

// Driver Code

int main()

int values[] = { 3, 4, 5, 6 };

int weight[] = { 2, 3, 4, 5 };

int W = 8;

// Find the number of items

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

// Output the maximum profit for the knapSack

printf(
"Maximum value that can be put in knapsack: %d\n",

knapsackRecursive(W, weight, values, n));

return 0;

5. Dijkstra's Algorithm for shortest paths in C

#include <stdio.h>

#include <limits.h>

#define MAX_VERTICES 100

// Function to find the vertex with the minimum distance value


int minDistance(int dist[], int sptSet[], int vertices) {
int min = INT_MAX, minIndex;

for (int v = 0; v < vertices; v++) {


if (!sptSet[v] && dist[v] < min) {
min = dist[v];
minIndex = v;
}
}

return minIndex;
}

// Function to print the constructed distance array


void printSolution(int dist[], int vertices) {
printf("Vertex \tDistance from Source\n");
for (int i = 0; i < vertices; i++) {
printf("%d \t%d\n", i, dist[i]);
}
}

// Function to implement Dijkstra's algorithm for a given graph and source vertex
void dijkstra(int graph[MAX_VERTICES][MAX_VERTICES], int src, int vertices) {
int dist[MAX_VERTICES]; // The output array dist[i] holds the shortest distance
from src to i
int sptSet[MAX_VERTICES]; // sptSet[i] will be true if vertex i is included in
the shortest path tree or the shortest distance from src to i is finalized

// Initialize all distances as INFINITE and sptSet[] as false


for (int i = 0; i < vertices; i++) {
dist[i] = INT_MAX;
sptSet[i] = 0;
}

// Distance from source vertex to itself is always 0


dist[src] = 0;

// Find the shortest path for all vertices


for (int count = 0; count < vertices - 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, vertices);

// Mark the picked vertex as processed


sptSet[u] = 1;

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


for (int v = 0; v < vertices; v++) {
// Update dist[v] only if it is not in the sptSet, there is an edge from
u to v,
// and the total weight of path from src to v through u is smaller than
the 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, vertices);
}

int main() {
int vertices;

// Input the number of vertices


printf("Input the number of vertices: ");
scanf("%d", &vertices);

if (vertices <= 0 || vertices > MAX_VERTICES) {


printf("Invalid number of vertices. Exiting...\n");
return 1;
}

int graph[MAX_VERTICES][MAX_VERTICES];

// Input the adjacency matrix representing the weighted graph


printf("Input the adjacency matrix for the graph (use INT_MAX for infinity):\n");
for (int i = 0; i < vertices; i++) {
for (int j = 0; j < vertices; j++) {
scanf("%d", &graph[i][j]);
}
}

int source;

// Input the source vertex


printf("Input the source vertex: ");
scanf("%d", &source);

if (source < 0 || source >= vertices) {


printf("Invalid source vertex. Exiting...\n");
return 1;
}

// Perform Dijkstra's algorithm


dijkstra(graph, source, vertices);

return 0;
}
6. // C code to implement Kruskal's algorithm

#include <stdio.h>

#include <stdlib.h>

// Comparator function to use in sorting

int comparator(const int p1[], const int p2[])

return p1[2] - p2[2];

// Initialization of parent[] and rank[] arrays

void makeSet(int parent[], int rank[], int n)

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

parent[i] = i;

rank[i] = 0;

// Function to find the parent of a node

int findParent(int parent[], int component)

if (parent[component] == component)

return component;

return parent[component]

= findParent(parent, parent[component]);

// Function to unite two sets

void unionSet(int u, int v, int parent[], int rank[], int n)

{
// Finding the parents

u = findParent(parent, u);

v = findParent(parent, v);

if (rank[u] < rank[v]) {

parent[u] = v;

else if (rank[u] > rank[v]) {

parent[v] = u;

else {

parent[v] = u;

// Since the rank increases if

// the ranks of two sets are same

rank[u]++;

// Function to find the MST

int kruskalAlgo(int n, int edge[n][3])

// First we sort the edge array in ascending order

// so that we can access minimum distances/cost

qsort(edge, n, sizeof(edge[0]), comparator);

int parent[n];

int rank[n];

// Function to initialize parent[] and rank[]

makeSet(parent, rank, n);


// To store the minimun cost

int minCost = 0;

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

int v1 = findParent(parent, edge[i][0]);

int v2 = findParent(parent, edge[i][1]);

int wt = edge[i][2];

// If the parents are different that

// means they are in different sets so

// union them

if (v1 != v2) {

unionSet(v1, v2, parent, rank, n);

minCost += wt;

return minCost;

// Driver code

int main()

int edge[5][3] = { { 0, 1, 10 },

{ 0, 2, 6 },

{ 0, 3, 5 },

{ 1, 3, 15 },

{ 2, 3, 4 } };

printf("%d",kruskalAlgo(5, edge));
return 0;

7. // A C program for Prim's Minimum


// Spanning Tree (MST) 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 5

// A utility function to find the vertex with

// minimum key value, from the set of vertices

// not yet included in MST

int minKey(int key[], 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[]

int printMST(int parent[], int graph[V][V])

printf("Edge \tWeight\n");

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


printf("%d - %d \t%d \n", parent[i], i,

graph[parent[i]][i]);

// Function to construct and print MST for

// a graph represented using adjacency

// matrix representation

void primMST(int graph[V][V])

// Array to store constructed MST

int parent[V];

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

int key[V];

// To represent set of vertices included in MST

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

int graph[V][V] = { { 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. Shortest Path using Floyd’s Algorithm


#include <iostream>

#include <vector>

#include <climits>

using namespace std;

// Solves the all-pairs shortest path

// problem using Floyd Warshall algorithm

void floydWarshall(vector<vector<int>> &dist) {

int V = dist.size();

// Add all vertices one by one to

// the set of intermediate vertices.

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

// Pick all vertices as source one by one

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

// Pick all vertices as destination

// for the above picked source

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

// shortest path from

// i to j

if(dist[i][k] != 1e8 && dist[k][j]!= 1e8)

dist[i][j] = min(dist[i][j],dist[i][k] + dist[k][j]);

int main() {

int INF = 100000000;


vector<vector<int>> dist = {

{0, 4, INF, 5, INF},

{INF, 0, 1, INF, 6},

{2, INF, 0, 3, INF},

{INF, INF, 1, 0, 2},

{1, INF, INF, 4, 0}

};

floydWarshall(dist);

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

for(int j = 0; j<dist.size(); j++) {

cout<<dist[i][j]<<" ";

cout<<endl;

return 0;

9. // C++ program to find the shortest possible route by for Traveling


Salesman Problem (TSP)

// that visits every city exactly once and returns to

// the starting point

#include <bits/stdc++.h>

using namespace std;

int tsp(vector<vector<int>> &cost) {

// Number of nodes

int numNodes = cost.size();

vector<int> nodes;
// Initialize the nodes excluding the fixed

// starting point (node 0)

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

nodes.push_back(i);

int minCost = INT_MAX;

// Generate all permutations of the remaining nodes

do {

int currCost = 0;

// Start from node 0

int currNode = 0;

// Calculate the cost of the current permutation

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

currCost += cost[currNode][nodes[i]];

currNode = nodes[i];

// Add the cost to return to the starting node

currCost += cost[currNode][0];

// Update the minimum cost if the current cost

// is lower

minCost = min(minCost, currCost);

} while (next_permutation(nodes.begin(), nodes.end()));

return minCost;

}
int main() {

vector<vector<int>> cost = {{0, 10, 15, 20},

{10, 0, 35, 25},

{15, 35, 0, 30},

{20, 25, 30, 0}};

int res = tsp(cost);

cout << res << endl;

return 0;

10. /* C program for solution of Hamiltonian Cycle problem


using backtracking */

#include<stdio.h>

// Number of vertices in the graph

#define V 5

void printSolution(int path[]);

/* A utility function to check if the vertex v can be added at

index 'pos' in the Hamiltonian Cycle constructed so far (stored

in 'path[]') */

int isSafe(int v, int graph[V][V], int path[], int pos)

/* Check if this vertex is an adjacent vertex of the previously

added vertex. */

if (graph [ path[pos-1] ][ v ] == 0)

return 0;

/* Check if the vertex has already been included.

This step can be optimized by creating an array of size V */

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


if (path[i] == v)

return 0;

return 1;

/* A recursive utility function to solve hamiltonian cycle problem */

int hamCycleUtil(int graph[V][V], int path[], int pos)

/* base case: If all vertices are included in Hamiltonian Cycle */

if (pos == V)

// And if there is an edge from the last included vertex to the

// first vertex

if ( graph[ path[pos-1] ][ path[0] ] == 1 )

return 1;

else

return 0;

// Try different vertices as a next candidate in Hamiltonian Cycle.

// We don't try for 0 as we included 0 as starting point in hamCycle()

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

/* Check if this vertex can be added to Hamiltonian Cycle */

if (isSafe(v, graph, path, pos))

path[pos] = v;

/* recur to construct rest of the path */

if (hamCycleUtil (graph, path, pos+1) == 1)

return 1;

/* If adding vertex v doesn't lead to a solution,

then remove it */

path[pos] = -1;
}

/* If no vertex can be added to Hamiltonian Cycle constructed so far,

then return false */

return 0;

/* This function solves the Hamiltonian Cycle problem using Backtracking.

It mainly uses hamCycleUtil() to solve the problem. It returns false

if there is no Hamiltonian Cycle possible, otherwise return true and

prints the path. Please note that there may be more than one solutions,

this function prints one of the feasible solutions. */

int hamCycle(int graph[V][V])

int path[V];

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

path[i] = -1;

/* Let us put vertex 0 as the first vertex in the path. If there is

a Hamiltonian Cycle, then the path can be started from any point

of the cycle as the graph is undirected */

path[0] = 0;

if ( hamCycleUtil(graph, path, 1) == 0 )

printf("\nSolution does not exist");

return 0;

printSolution(path);

return 1;

/* A utility function to print solution */

void printSolution(int path[])

{
printf ("Solution Exists:"

" Following is one Hamiltonian Cycle \n");

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

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

// Let us print the first vertex again to show the complete cycle

printf(" %d ", path[0]);

printf("\n");

// driver program to test above function

int main()

/* Let us create the following graph

(0)--(1)--(2)

| / \ |

| / \ |

| / \ |

(3)-------(4) */

int graph1[V][V] = {{0, 1, 0, 1, 0},

{1, 0, 1, 1, 1},

{0, 1, 0, 0, 1},

{1, 1, 0, 0, 1},

{0, 1, 1, 1, 0},

};

// Print the solution

hamCycle(graph1);

/* Let us create the following graph

(0)--(1)--(2)

| / \ |

| / \ |
| / \ |

(3) (4) */

int graph2[V][V] = {{0, 1, 0, 1, 0},

{1, 0, 1, 1, 1},

{0, 1, 0, 0, 1},

{1, 1, 0, 0, 0},

{0, 1, 1, 0, 0},

};

// Print the solution

hamCycle(graph2);

return 0;

You might also like