0% found this document useful (0 votes)
3 views29 pages

DAA Lab Manual

The document is a laboratory manual for the Analysis and Design of Algorithms course at Visvesvaraya Technological University. It includes C programming assignments for various algorithms such as Kruskal's, Prim's, Floyd's, Warshall's, Dijkstra's, and the 0/1 Knapsack problem, along with their implementations and sample outputs. Each section provides a brief description of the algorithm, the required code, and example input/output to demonstrate functionality.

Uploaded by

Sunny Sing
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)
3 views29 pages

DAA Lab Manual

The document is a laboratory manual for the Analysis and Design of Algorithms course at Visvesvaraya Technological University. It includes C programming assignments for various algorithms such as Kruskal's, Prim's, Floyd's, Warshall's, Dijkstra's, and the 0/1 Knapsack problem, along with their implementations and sample outputs. Each section provides a brief description of the algorithm, the required code, and example input/output to demonstrate functionality.

Uploaded by

Sunny Sing
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/ 29

Visvesvaraya Technological University

(State University of Government of Karnataka Established as per the VTU Act, 1994)
Belagavi-590018

Department of Computer Science &


Business Systems

Laboratory Manual III Sem

Analysis and Design of Algorithm

Course Code: BCSL404

Bapuji Educational Association (Regd.) Bapuji Institute of Engineering &


Technology Davangere-577004
Bapuji Educational Association (Regd.)
Bapuji Institute of Engineering & Technology, Davangere-4
Department of Computer Science & Business Systems

1.Design and implement C program to find Minimum Cost Spanning Tree of a given connected
undirected graph using Krushkal's algorithm.

#include<stdio.h>
#include<stdlib.h>
int i,j,k,a,b,u,v,n,ne=1;
int min,mincost=0,cost[9][9],parent[9];
int find(int);
int uni(int,int);
int main()
{
printf("\n\nImplementation of Kruskal's Algorithm\n\n");
printf("Enter the number of vertices\n");
scanf("%d",&n);
printf("\nEnter the cost adjacency matrix\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
scanf("%d",&cost[i][j]);
if(cost[i][j]==0)
cost[i][j]=999;
}
}
printf("\nThe edges of the minimum cost spanning tree");
while(ne<n)
{
min=999;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(cost[i][j]<min)
{
min=cost[i][j];
a=u=i;
b=v=j;
}
}
}

u=find(u);
v=find(v);
if(uni(u,v))
{
printf("\n%d edge (%d,%d)=%d",ne++,a,b,min);
mincost+=min;
}
cost[a][b]=cost[b][a]=999;
}
printf("\n\nMinimum cost = %d\n",mincost);
return 0;
2
Bapuji Educational Association (Regd.)
Bapuji Institute of Engineering & Technology, Davangere-4
Department of Computer Science & Business Systems
}
int find(int i)
{
while(parent[i])
i=parent[i];
return i;
}
int uni(int i,int j)
{
if(i!=j)
{
parent[j]=i;
return 1;
}
return 0;
}

Output:
Implementation of Kruskal's Algorithm

Enter the number of vertices


5

Enter the cost adjacency matrix


08500
8 0 9 11 0
5 9 0 15 0
0 11 15 0 7
0 0 10 7 0

The edges of the minimum cost spanning tree


1 edge (1,3)=5
2 edge (4,5)=7
3 edge (1,2)=8
4 edge (5,3)=10

Minimum cost = 30

3
Bapuji Educational Association (Regd.)
Bapuji Institute of Engineering & Technology, Davangere-4
Department of Computer Science & Business Systems

2. Design and implement C program to find Minimum Cost Spanning Tree of a given connected
undirected graph using Prim's algorithm.

#include<stdio.h>
#include<conio.h>
int a,b,u,v,n,i,j,ne=1;
int visited[10]={0},min,mincost=0,cost[10][10];
int main() {
printf("\nEnter the number of nodes: ");
scanf("%d",&n);
printf("\nEnter the adjacency matrix:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++) {
scanf("%d",&cost[i][j]);
if(cost[i][j]==0)
cost[i][j] = 999;
}
visited[1]=1;
printf("\n");
while(ne<n) {
for(i=1,min=999;i<=n;i++)
for(j=1;j<=n;j++)
if(cost[i][j]<min)
if(visited[i]!=0) {
min=cost[i][j];
a=u=i;
b=v=j;
}
if(visited[u]==0 || visited[v]==0) {
printf("\n Edge %d: (%d, %d) cost: %d", ne++, a, b, min);
mincost+=min;
visited[b]=1;
}
cost[a][b]=cost[b][a]=999;
}
printf("\n Minimum cost = %d", mincost);
getch();
}

Output:
Enter the number of nodes: 5
Enter the adjacency matrix:
08500
8 0 9 11 0
5 9 0 25 10
0 11 25 0 7
0 0 10 7 0

Edge 1: (1, 3) cost: 5


Edge 2: (1, 2) cost: 8
Edge 3: (3, 5) cost: 10
Edge 4: (5, 4) cost: 7
Minimum cost = 30
4
Bapuji Educational Association (Regd.)
Bapuji Institute of Engineering & Technology, Davangere-4
Department of Computer Science & Business Systems

3 a. Design and implement C program to solve All-Pairs Shortest Paths problem using Floyd's
algorithm.

#include<stdio.h>
int main(void)
{
int n,i,j,k;
int iaFloyd[10][10];
printf("\n\t PROGRAM TO IMPLEMENT FLOYD'S ALGORITHM \t\n");
printf("enter the number of vertices \n");
scanf("%d",&n);
printf("\n enter the cost adjacency matrix \n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&iaFloyd[i][j]);
for(k=0;k<n;k++)
{
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(iaFloyd[i][j]>(iaFloyd[i][k]+iaFloyd[k][j]))
iaFloyd[i][j]=(iaFloyd[i][k]+iaFloyd[k][j]);
}
}
}
printf("\n all pair shortest path matrix \n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("%d\t",iaFloyd[i][j]);
}
printf("\n");
}
printf("\n");
return 0;
}

Output:
* PROGRAM TO IMPLEMENT FLOYD'S ALGORITHM *

Enter the number of vertices: 5

Enter the cost adjacency matrix:


0 3 999 7 9
3 0 4 2 999
999 4 0 5 6
72504
9 999 6 4 0

5
Bapuji Educational Association (Regd.)
Bapuji Institute of Engineering & Technology, Davangere-4
Department of Computer Science & Business Systems
All pair shortest path matrix:
0 3 7 5 9
3 0 4 2 6
7 4 0 5 6
5 2 5 0 4
9 6 6 4 0

3 b.Design and implement C program to find the transitive closure using Warshall's algorithm.

#include <stdio.h>
void WarshallTransitiveClosure(int graph[100][100], int numVert);
int main(void)
{
int i,j,numVert;
int graph[100][100];
printf("Warshall's Transitive closure \n");
printf("enter the number of vertices: ");
scanf("%d",&numVert);
printf("enter the adjacency matrix: \n");
for(i=0;i<numVert;i++)
for(j=0;j<numVert;j++)
scanf("%d",&graph[i][j]);
WarshallTransitiveClosure(graph,numVert);
printf("\n the trasitive closure for the given graph is \n");
for(i=0;i<numVert;i++)
{
for(j=0;j<numVert;j++)
{
printf("%d\t",graph[i][j]);
}
printf("\n");
}
return 0;
}
void WarshallTransitiveClosure(int graph[100][100],int numVert)
{
int i,j,k;
for(k=0;k<numVert;k++)
{
for(i=0;i<numVert;i++)
{
for(j=0;j<numVert;j++)
{
if(graph[i][j]||(graph[i][k]&&graph[k][j]))
graph[i][j]=1;
}
}
}
}

6
Bapuji Educational Association (Regd.)
Bapuji Institute of Engineering & Technology, Davangere-4
Department of Computer Science & Business Systems

Output:
Warshall's Transitive Closure
Enter the number of vertices: 4
Enter the adjacency matrix:
0010
0001
1000
0100

The transitive closure for the given graph is:


1 0 1 0
0 1 0 1
1 0 1 0
0 1 0 1

4. Design and implement C program to find the shortest paths from a given vertex in a weighted
connected graph to other vertices using Dijkstra's algorithm.

#include<stdio.h>
#define INFINITY 9999
#define MAX 10
void dijikstra(int cost[10][10], int n, int start) {
int distance[10], count, mindist, next, i, j;
int visited[10], path[10];
for(i=0;i<n;i++) {
distance[i] = cost[start][i];
path[i] = start;
visited[i] = 0;
}
distance[start] = 0;
visited[start] = 1;
count = 1;
while(count < n-1) {
mindist = INFINITY;
for(i=0;i<n;i++)
if(distance[i] < mindist && !visited[i]) {
mindist = distance[i];
next = i;
}
visited[next] = 1;
for(i=0;i<n;i++)
if(!visited[i])
if(mindist + cost[next][i] < distance[i]) {
distance[i] = mindist + cost[next][i];
path[i] = next;
}
count++;
}
for(i=0;i<n;i++)
if(i!=start) {
printf("\nDistance of %d = %d", i, distance[i]);
7
Bapuji Educational Association (Regd.)
Bapuji Institute of Engineering & Technology, Davangere-4
Department of Computer Science & Business Systems
printf("\nPath = %d", i);
j = i;
do {
j = path[j];
printf("<--%d", j);
} while(j != start);
}
}

void main() {
int G[MAX][MAX], i, j, n, u;
printf("\nEnter the number of vertices: ");
scanf("%d", &n);
printf("\nEnter the adjacency matrix:\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++) {
scanf("%d", &G[i][j]);
if(G[i][j] == 0)
G[i][j] = INFINITY;
}
printf("\nEnter the starting node: ");
scanf("%d", &u);
dijikstra(G,n,u);
}

Output:
Enter the number of vertices: 5

Enter the adjacency matrix:


08500
80910
5 9 0 15 10
0 1 15 0 2
0 0 10 2 0

Enter the starting node: 0

Distance of 1 = 8
Path = 1<--0
Distance of 2 = 5
Path = 2<--0
Distance of 3 = 9
Path = 3<--1<--0
Distance of 4 = 11
Path = 4<--3<--1<--0

8
Bapuji Educational Association (Regd.)
Bapuji Institute of Engineering & Technology, Davangere-4
Department of Computer Science & Business Systems

5. Design and implement C program to obtain the Topological ordering of vertices in a given digraph.

#include<stdio.h>

int a[10][10], n, indegre[10];

void find_indegre() {
int j, i, sum;
for(j = 0; j < n; j++) {
sum = 0;
for(i = 0; i < n; i++)
sum += a[i][j];
indegre[j] = sum;
}
}

void topology() {
int i, u, v, t[10], s[10], top = -1, k = 0;
find_indegre();
for(i = 0; i < n; i++)
if(indegre[i] == 0)
s[++top] = i;
while(top != -1) {
u = s[top--];
t[k++] = u;
for(v = 0; v < n; v++) {
if(a[u][v] == 1) {
indegre[v]--;
if(indegre[v] == 0)
s[++top] = v;
}
}
}
printf("The topological sequence is: \n");
for(i = 0; i < n; i++)
printf("%d ", t[i]);
printf("\n");
}

void main() {
int i, j;
printf("Enter the number of jobs: ");
scanf("%d", &n);
printf("Enter the adjacency matrix:\n");
for(i = 0; i < n; i++) {
for(j = 0; j < n; j++) {
scanf("%d", &a[i][j]);
}
}
topology();
}

9
Bapuji Educational Association (Regd.)
Bapuji Institute of Engineering & Technology, Davangere-4
Department of Computer Science & Business Systems

Output:
Enter the number of jobs: 5
Enter the adjacency matrix:
01000
00011
01000
00001
00000
The topological sequence is:
20134

6. Design and implement C/C++ program to solve 0/1 Knapsack problem using Dynamic Programming
method

#include<stdio.h>
int max(int a, int b) {
return (a>b)?a:b;
}

int Knapsack(int W, int wt[], int val[], int n) {


int i, w;
int k[n+1][W+1];
for(i=0;i<=n;i++) {
for(w=0; w<=W;w++) {
if(i==0||w==0)
k[i][w]=0;
else if(wt[i-1]<=w)
k[i][w]=max(val[i-1]+k[i-1][w-wt[i-1]], k[i-1][w]);
else
k[i][w]=k[i-1][w];
}
}
return k[n][W];
}

int main() {
int val[100], wt[100];
int i,W,n;
printf("Enter the no. of items: ");
scanf("%d", &n);
printf("Enter the values and weights of %d items:\n",n);
for(i=0;i<n;i++) {
printf("Enter value and weight of item %d: ", i+1);
scanf("%d %d", &val[i], &wt[i]);
}
printf("Enter the Knapsack capacity: ");
scanf("%d", &W);
printf("Maximum value that can be obtained: %d\n", Knapsack(W, wt, val, n));
return 0;
}

10
Bapuji Educational Association (Regd.)
Bapuji Institute of Engineering & Technology, Davangere-4
Department of Computer Science & Business Systems

Output:
Enter the no. of items: 4
Enter the values and weights of 4 items:
Enter value and weight of item 1: 42 7
Enter value and weight of item 2: 12 3
Enter value and weight of item 3: 40 4
Enter value and weight of item 4: 25 5
Enter the Knapsack capacity: 10
Maximum value that can be obtained: 65

7. Design and implement C/C++ Program to solve discrete Knapsack and continuous Knapsack
problems using greedy approximation method

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

struct Item {
int value;
int weight;
double ratio;
};

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


struct Item *item1 = (struct Item *)a;
struct Item *item2 = (struct Item *)b;
double ratio1 = item1->ratio;
double ratio2 = item2->ratio;
if (ratio1 > ratio2) return -1;
else if (ratio1 < ratio2) return 1;
else return 0;
}

void discreteKnapsack(struct Item items[], int n, int capacity) {


int i, j;
int dp[n + 1][capacity + 1];
for (i = 0; i<=n; i++) {
for (j =0; j <= capacity; j++) {
if (i == 0||j ==0)
dp[i][j] = 0;
else if (items[i - 1].weight <= j)
dp[i][j] = (items[i - 1].value + dp[i - 1][j - items[i - 1].weight] > dp[i - 1][j]) ?
(items[i - 1].value + dp[i - 1][j - items[i-1].weight]) : dp[i - 1][j];
else
dp[i][j]=dp[i-1][j];
}
}
printf("Total value obtained for discrete knapsack: %d\n", dp[n][capacity]);
}
11
Bapuji Educational Association (Regd.)
Bapuji Institute of Engineering & Technology, Davangere-4
Department of Computer Science & Business Systems

void continuousKnapsack(struct Item items[], int n, int capacity) {


int i;
double totalValue = 0.0;
int remainingCapacity=capacity;
for (i = 0; i<n; i++) {
if (remainingCapacity >= items[i].weight) {
totalValue += items[i].value;
remainingCapacity -= items[i].weight;
}else{
totalValue+=(double)remainingCapacity/items[i].weight*items[i].value;
break;
}
}
printf("Total Value obtained for continuous Knapsack: %0.2f\n", totalValue);
}

int main() {
int n, capacity, i;
printf("Enter the number of items: ");
scanf("%d", &n);
struct Item items[n];
printf("Enter the capacity of the knapsack: ");
scanf("%d", &capacity);
printf("Enter the value and weight of each item:\n");
for (i = 0;i<n; i++) {
scanf("%d %d", &items[i].value, &items[i].weight);
items[i].ratio=(double)items[i].value/items[i].weight;
}
qsort(items, n, sizeof(struct Item), compare);
discreteKnapsack(items, n, capacity);
continuousKnapsack(items, n, capacity);
return 0;
}

Output:
Enter the number of items: 4
Enter the capacity of the knapsack: 10
Enter the value and weight of each item:
42 7
12 3
40 4
25 5
Total value obtained for discrete knapsack: 65
Total Value obtained for continuous Knapsack: 76.00

12
Bapuji Educational Association (Regd.)
Bapuji Institute of Engineering & Technology, Davangere-4
Department of Computer Science & Business Systems

8. Design and implement C/C++ Program to find a subset of a given set S = {sl , s2,.....,sn} of n
positive integers whose sum is equal to a given positive integer d.

#include<stdio.h>
#define MAX 10
int s[MAX],x[MAX],d;
void sumofsub(int p,int k,int r)
{
int i;
x[k]=1;
if((p+s[k])==d)
{
for(i=1; i<=k; i++)
if(x[i]==1)
printf("%d ",s[i]);
printf("\n");
}
else if(p+s[k]+s[k+1]<=d)
sumofsub(p+s[k],k+1,r-s[k]);
if((p+r-s[k]>=d) && (p+s[k+1]<=d))
{
x[k]=0;
sumofsub(p,k+1,r-s[k]);
}
}

int main()
{
int i,n,sum=0;
printf("\nEnter the n value:");
scanf("%d",&n);
printf("\nEnter the set in increasing order:");
for(i=1; i<=n; i++)
scanf("%d",&s[i]);
printf("\nEnter the max subset value:");
scanf("%d",&d);
for(i=1; i<=n; i++)
sum=sum+s[i];
if(sum<d || s[1]>d)
printf("\nNo subset possible");
else
sumofsub(0,1,sum);
return 0;
}

OUTPUT:
Enter the n value:9
Enter the set in increasing order:1 2 3 4 5 6 7 8 9
Enter the max subset value:9
126
135
13
Bapuji Educational Association (Regd.)
Bapuji Institute of Engineering & Technology, Davangere-4
Department of Computer Science & Business Systems

18
234
27
36
45
9

9. Design and implement C/C++ Program to sort a given set of n integer elements using Selection
Sort method and compute its time complexity. Run the program for varied values of n> 5000 and
record the time taken to sort. Plot a graph of the time taken versus n. The elements can be read
from a file or can be generated using the random number generator

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

void selectionSort(int A[], int n);


void swap(int *a, int *b);
void printArray(int A[], int n);
void generateRandomArray(int X[], int n);
double timeSelectionSort(int arr[], int n);

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


int i, j;
for (i = 0; i < n - 1; i++) {
int min_idx = i;
for (j = i + 1; j < n; j++) {
if (A[j] < A[min_idx]) {
min_idx = j;
}
}
if (min_idx != i) {
swap(&A[i], &A[min_idx]);
}
}
}

void swap(int *a, int *b) {


int temp = *a;
*a = *b;
*b = temp;
}

void printArray(int A[], int n) {


int i;
for (i = 0; i < n; i++) {
printf("%d\n", A[i]);
}
printf("\n");
}

14
Bapuji Educational Association (Regd.)
Bapuji Institute of Engineering & Technology, Davangere-4
Department of Computer Science & Business Systems
void generateRandomArray(int X[], int n) {
srand(time(NULL));
int i;
for (i = 0; i < n; i++) {
X[i] = rand() % 10000;
}
}

double timeSelectionSort(int arr[], int n) {

clock_t start = clock();


selectionSort(arr, n);
clock_t end = clock();

double elapsedTime = ((double)(end - start)) * 1000.0 / CLOCKS_PER_SEC;


return elapsedTime;
}

int main() {
FILE *fp;
fp = fopen("time_vs_n.dat", "w");
if (fp == NULL) {
printf("Error opening file.\n");
return 1;
}

int num, n, i;
printf("Enter the number of elements to sort: ");
scanf("%d", &num);

int *arr = (int *)malloc(num * sizeof(int));


if (arr == NULL) {
perror("Memory allocation failed");
return 1;
}

generateRandomArray(arr, num);
printf("Unsorted array:\n");
printArray(arr, num);

printf("n\tTime (ms)\n");
for (n = 5000; n <= 15000; n += 1000) {
double totalTime = 0.0;
int num_tests = 5;

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


int *tempArr = (int *)malloc(n * sizeof(int));
if (tempArr == NULL) {
perror("Memory allocation failed");
return 1;
}
memcpy(tempArr, arr, num * sizeof(int));
totalTime += timeSelectionSort(tempArr, n);
free(tempArr);
15
Bapuji Educational Association (Regd.)
Bapuji Institute of Engineering & Technology, Davangere-4
Department of Computer Science & Business Systems
}

double averageTime = totalTime / num_tests;


printf("%d\t%.2f\n", n, averageTime);
fprintf(fp, "%d\t%.2f\n", n, averageTime);
}

selectionSort(arr, num);
printf("\nSorted Array:\n");
printArray(arr, num);

free(arr);
fclose(fp);

printf("Data saved to 'time_vs_n.dat'\n");


return 0;
}

Output:
Enter the number of elements to sort: 10
Unsorted array:
8072
1750
9634
1195
9827
6252
659
4255
4311
6873

n Time (ms)
5000 45.60
6000 65.00
7000 85.20
8000 111.40
9000 141.60
10000 171.00
11000 210.80
12000 251.20
13000 289.80
14000 338.20
15000 385.00

Sorted Array:
659
1195
1750
4255
4311
6252
6873
8072
16
Bapuji Educational Association (Regd.)
Bapuji Institute of Engineering & Technology, Davangere-4
Department of Computer Science & Business Systems
9634
9827

Data saved to 'time_vs_n.dat'

Python Code to plot Graph:


import matplotlib.pyplot as plt

# data collected
n_values = [6000, 7000, 8000, 9000, 10000]
time_taken = [0.031000, 0.034000, 0.047000, 0.052000, 0.077000] # replace with actual times recorded

plt.plot(n_values, time_taken, marker='o')


plt.title('Selection Sort Time Complexity')
plt.xlabel('Number of Elements (n)')
plt.ylabel('Time taken (seconds)')
plt.grid(True)
plt.show()

Graph:

10. Design and implement C/C++ Program to sort a given set of n integer elements using Quick Sort
method and compute its time complexity. Run the program for varied values of n> 5000 and
record the time taken to sort. Plot a graph of the time taken versus n. The elements can be read
from a file or can be generated using the random number generator.

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

17
Bapuji Educational Association (Regd.)
Bapuji Institute of Engineering & Technology, Davangere-4
Department of Computer Science & Business Systems

void quickSort(int A[], int low, int high);


int partition(int A[], int low, int high);
void swap(int *a, int *b);
void printArray(int A[], int n);
void generateRandomArray(int X[], int n);
double timeQuickSort(int arr[], int n);

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


if (low < high) {
int pi = partition(A, low, high);
quickSort(A, low, pi - 1);
quickSort(A, pi + 1, high);
}
}

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


int pivot = A[high];
int i = (low - 1), j;
for (j = low; j <= high - 1; j++) {
if (A[j] < pivot) {
i++;
swap(&A[i], &A[j]);
}
}
swap(&A[i + 1], &A[high]);
return (i + 1);
}

void swap(int *a, int *b) {


int temp = *a;
*a = *b;
*b = temp;
}

void printArray(int A[], int n) {


int i;
for (i = 0; i < n; i++) {
printf("%d\n", A[i]);
}
printf("\n");
}

void generateRandomArray(int X[], int n) {


srand(time(NULL));
int i;
for (i = 0; i < n; i++) {
X[i] = rand() % 10000;
}
}

double timeQuickSort(int arr[], int n) {


clock_t start, end;
18
Bapuji Educational Association (Regd.)
Bapuji Institute of Engineering & Technology, Davangere-4
Department of Computer Science & Business Systems
double time_used;

start = clock();
quickSort(arr, 0, n - 1);
end = clock();

time_used = ((double)(end - start)) * 1000.0 / CLOCKS_PER_SEC;

return time_used;
}

int main() {
FILE *fp;
fp = fopen("time_vs_n_quick.dat", "w");
if (fp == NULL) {
printf("Error opening file.\n");
return 1;
}

int num, n, i;
printf("Enter the number of elements to sort: ");
scanf("%d", &num);

int *arr = (int *)malloc(num * sizeof(int));


if (arr == NULL) {
perror("Memory allocation failed");
return 1;
}

generateRandomArray(arr, num);

printf("Unsorted array:\n");
printArray(arr, num);

printf("n\tTime (ms)\n");
for (n = 5000; n <= 15000; n += 1000) {
double totalTime = 0.0;
int num_tests = 5;

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


int *tempArr = (int *)malloc(n * sizeof(int));
if (tempArr == NULL) {
perror("Memory allocation failed");
return 1;
}
memcpy(tempArr, arr, num * sizeof(int));
totalTime += timeQuickSort(tempArr, n);
free(tempArr);
}

double averageTime = totalTime / num_tests;


printf("%d\t%.2f\n", n, averageTime);
fprintf(fp, "%d\t%.2f\n", n, averageTime);
19
Bapuji Educational Association (Regd.)
Bapuji Institute of Engineering & Technology, Davangere-4
Department of Computer Science & Business Systems
}

quickSort(arr, 0, num - 1);


printf("\nSorted Array:\n");
printArray(arr, num);

free(arr);
fclose(fp);

printf("Data saved to 'time_vs_n_quick.dat'\n");

return 0;
}

Output:
Enter the number of elements to sort: 10
Unsorted array:
8503
1515
8408
9057
5095
292
8286
1071
1152
1760

n Time (ms)
5000 45.00
6000 61.80
7000 83.60
8000 108.20
9000 137.40
10000 168.80
11000 197.60
12000 231.00
13000 269.20
14000 312.20
15000 355.00

Sorted Array:
292

1071
1152
1515
1760
5095
8286
8408
8503
9057
20
Bapuji Educational Association (Regd.)
Bapuji Institute of Engineering & Technology, Davangere-4
Department of Computer Science & Business Systems

Data saved to 'time_vs_n_quick.dat'

Python Code to plot graph:


import matplotlib.pyplot as plt

# Example data collected


n_values = [10000, 20000, 30000, 35000, 50000]
time_taken = [0.0000, 0.015000, 0.011000, 0.003000, 0.015000] # replace with actual times recorded

plt.plot(n_values, time_taken, marker='o')


plt.title('Quick Sort Time Complexity')
plt.xlabel('Number of Elements (n)')
plt.ylabel('Time taken (seconds)')
plt.grid(True)
plt.show()

Graph:

11. Design and implement C/C++ Program to sort a given set of n integer elements using Merge Sort
method and compute its time complexity. Run the program for varied values of n> 5000, and
record the time taken to sort. Plot a graph of the time taken versus n. The elements can be read
from a file or can be generated using the random number generator.

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

void mergeSort(int A[], int low, int high);


void merge(int A[], int low, int mid, int high);
21
Bapuji Educational Association (Regd.)
Bapuji Institute of Engineering & Technology, Davangere-4
Department of Computer Science & Business Systems

void swap(int *a, int *b);


void printArray(int A[], int n);
void generateRandomArray(int X[], int n);
double timeMergeSort(int arr[], int n);

void mergeSort(int A[], int low, int high) {


if (low < high) {
int mid = low + (high - low) / 2;
mergeSort(A, low, mid);
mergeSort(A, mid + 1, high);
merge(A, low, mid, high);
}
}

void merge(int A[], int low, int mid, int high) {


int n1 = mid - low + 1;

int n2 = high - mid;


int i, j;
int L[n1], R[n2];
for (i = 0; i < n1; i++) {
L[i] = A[low + i];
}
for (j = 0; j < n2; j++) {
R[j] = A[mid + 1 + j];
}

i = 0, j = 0;

int k = low;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
A[k] = L[i];
i++;
} else {
A[k] = R[j];
j++;
}
k++;
}

while (i < n1) {


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

while (j < n2) {


A[k] = R[j];
j++;
k++;
}
}
22
Bapuji Educational Association (Regd.)
Bapuji Institute of Engineering & Technology, Davangere-4
Department of Computer Science & Business Systems

void swap(int *a, int *b) {


int temp = *a;
*a = *b;

*b = temp;
}

void printArray(int A[], int n) {


int i;
for (i = 0; i < n; i++) {
printf("%d\n", A[i]);
}
printf("\n");
}

void generateRandomArray(int X[], int n) {

srand(time(NULL));
int i;
for (i = 0; i < n; i++) {
X[i] = rand() % 10000;
}
}

double timeMergeSort(int arr[], int n) {


clock_t start, end;
double time_used;

start = clock();
mergeSort(arr, 0, n - 1);
end = clock();
time_used = ((double)(end - start)) * 1000.0 / CLOCKS_PER_SEC;
return time_used;
}

int main() {
FILE *fp;
fp = fopen("time_vs_n_merge.dat", "w");
if (fp == NULL) {
printf("Error opening file.\n");
return 1;
}

int num, n, i;
printf("Enter the number of elements to sort: ");
scanf("%d", &num);

int *arr = (int *)malloc(num * sizeof(int));


if (arr == NULL) {
perror("Memory allocation failed");
return 1;
}

23
Bapuji Educational Association (Regd.)
Bapuji Institute of Engineering & Technology, Davangere-4
Department of Computer Science & Business Systems

generateRandomArray(arr, num);
printf("Unsorted array:\n");
printArray(arr, num);
printf("\nGENERATING DATA......\n");

for (n = 5000; n <= 150000; n += 500) {


double totalTime = 0.0;
int num_tests = 5;
for (i = 0; i < num_tests; i++) {
int *tempArr = (int *)malloc(n * sizeof(int));
if (tempArr == NULL) {
perror("Memory allocation failed");
return 1;
}
memcpy(tempArr, arr, num * sizeof(int));
totalTime += timeMergeSort(tempArr, n);
free(tempArr);

double averageTime = totalTime / num_tests;


fprintf(fp, "%d\t%.2f\n", n, averageTime);
}

mergeSort(arr, 0, num - 1);


printf("\nSorted Array:\n");
printArray(arr, num);
free(arr);
fclose(fp);
printf("Data saved to 'time_vs_n_merge.dat'\n");
return 0;
}

Output:
Enter the number of elements to sort: 10
Unsorted array:
8930
532
2087
5623
2816
3174
33
814
1483
5563

GENERATING DATA......

Sorted Array:
33
532
24
Bapuji Educational Association (Regd.)
Bapuji Institute of Engineering & Technology, Davangere-4
Department of Computer Science & Business Systems
814
1483
2087
2816
3174
5563
5623
8930

Data saved to 'time_vs_n_merge.dat'

Python Code to plot graph:


import matplotlib.pyplot as plt

# data collected (replace with actual data)


n_values = [6000, 7000, 8000, 9000, 10000, 11000, 12000, 13000, 15000]
time_taken = [0.000709, 0.000752, 0.000916, 0.001493, 0.001589, 0.002562, 0.001944, 0.002961, 0.003563]
# Replace with actual times recorded

plt.plot(n_values, time_taken, marker='o')


plt.title('Merge Sort Time Complexity')
plt.xlabel('Number of Elements (n)')
plt.ylabel('Time taken (seconds)')
plt.grid(True)
plt.show()

Graph:

25
Bapuji Educational Association (Regd.)
Bapuji Institute of Engineering & Technology, Davangere-4
Department of Computer Science & Business Systems

12. Design and implement C/C++ Program for N Queen's problem using Backtracking.

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

void printSolution(int **board, int N)


{
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
printf("%s ", board[i][j] ? "Q" : "#");
}
printf("\n");

}
}

bool isSafe(int **board, int N, int row, int col)


{
int i, j;
for (i = 0; i < col; i++)
{
if (board[row][i])
{
return false;
}
}

for (i = row, j = col; i >= 0 && j >= 0; i--, j--)


{
if (board[i][j])
{
return false;
}
}

for (i = row, j = col; j >= 0 && i < N; i++, j--)


{
if (board[i][j])
{
return false;
}
}

return true;
}

bool solveNQUtil(int **board, int N, int col)


{
26
Bapuji Educational Association (Regd.)
Bapuji Institute of Engineering & Technology, Davangere-4
Department of Computer Science & Business Systems

if (col >= N)
{
return true;
}

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


{
if (isSafe(board, N, i, col))
{
board[i][col] = 1;
if (solveNQUtil(board, N, col + 1))
{
return true;
}
board[i][col] = 0; // BACKTRACK
}
}

return false;
}

bool solveNQ(int N)
{
int **board = (int **)malloc(N * sizeof(int *));
for (int i = 0; i < N; i++)
{
board[i] = (int *)malloc(N * sizeof(int));
for (int j = 0; j < N; j++)
{
board[i][j] = 0;
}
}

if (!solveNQUtil(board, N, 0))
{
printf("Solution does not exist\n");
for (int i = 0; i < N; i++)
{
free(board[i]);
}
free(board);
return false;
}

printSolution(board, N);

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


{
free(board[i]);
}
free(board);
return true;
}
27
Bapuji Educational Association (Regd.)
Bapuji Institute of Engineering & Technology, Davangere-4
Department of Computer Science & Business Systems

int main()
{
int N;
printf("Enter the number of queens: ");
scanf("%d", &N);
solveNQ(N);
return 0;
}

OUTPUT:

1.Enter the number of queens: 4


##Q#
Q###
###Q
#Q##

2.Enter the number of queens: 3


Solution does not exist

28
Bapuji Educational Association (Regd.)
Bapuji Institute of Engineering & Technology, Davangere-4
Department of Computer Science & Business Systems

29

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy