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

Design and Analysis of Algorithm

The document contains several programming tasks related to algorithms, including selection sort, the traveling salesman problem, the knapsack problem, depth-first search (DFS), breadth-first search (BFS), and finding minimum and maximum values using divide and conquer. Each task includes a C program implementation with explanations and sample outputs. The document is structured for a course on Design and Analysis of Algorithms for the academic year 2024-25.
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)
11 views

Design and Analysis of Algorithm

The document contains several programming tasks related to algorithms, including selection sort, the traveling salesman problem, the knapsack problem, depth-first search (DFS), breadth-first search (BFS), and finding minimum and maximum values using divide and conquer. Each task includes a C program implementation with explanations and sample outputs. The document is structured for a course on Design and Analysis of Algorithms for the academic year 2024-25.
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

Design and Analysis of Algorithm 2024-25

1.Write a program to sort list of n elements using selection sort


#include <stdio.h>

void swap(int *xp, int *yp) {


int temp = *xp;
*xp = *yp;
*yp = temp;
}

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


int i, j, min_index;

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


// Assume the current index is the minimum
min_index = i;

// Find the index of the minimum element in the unsorted part


for (j = i+1; j < n; j++) {
if (arr[j] < arr[min_index])
min_index = j;
}

// Swap the found minimum element with the first element


swap(&arr[min_index], &arr[i]);
}
}

int main() {
int n, i;

printf("Enter the number of elements: ");


scanf("%d", &n);

int arr[n];

printf("Enter %d elements:\n", n);


for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("\nOriginal Array: ");
for (i = 0; i < n; i++) {

ARJ-BCA-COLLAGE, ILKAL 1
Design and Analysis of Algorithm 2024-25
printf("%d ", arr[i]);
}

selectionSort(arr, n);

printf("\nSorted Array: ");


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

Output
Enter the number of elements: 5
Enter 5 elements:
56732

Original Array: 5 6 7 3 2
Sorted Array: 2 3 5 6 7

ARJ-BCA-COLLAGE, ILKAL 2
Design and Analysis of Algorithm 2024-25
2. Write a program to perform travelling salesman problem.
#include <stdio.h>
#include <limits.h>
#define MAX_CITIES 10

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


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

void permute(int cities[], int start, int end, int distance[], int numCities, int *minCost,
int bestPath[]) {
int i, cost = 0;

if (start == end) {
// Calculate the cost of the current permutation
for (i = 0; i < end - 1; i++) {
cost += distance[cities[i] * numCities + cities[i + 1]];
}
cost += distance[cities[end - 1] * numCities + cities[0]]; // Return to starting city

// Update minimum cost and best path if a new minimum is found


if (cost < *minCost) {
*minCost = cost;
for (i = 0; i < end; i++) {
bestPath[i] = cities[i]; // Store the best path
}
}
} else {
for (i = start; i < end; i++) {
swap(&cities[start], &cities[i]);
permute(cities, start + 1, end, distance, numCities, minCost, bestPath);
swap(&cities[start], &cities[i]); // Backtrack
}
}
}

int main() {
int numCities, i, j;

printf("Enter the number of cities (max %d): ", MAX_CITIES);

ARJ-BCA-COLLAGE, ILKAL 3
Design and Analysis of Algorithm 2024-25
scanf("%d", &numCities);

if (numCities <= 0 || numCities > MAX_CITIES) {


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

int distance[MAX_CITIES * MAX_CITIES]; // 1D array for distances

// Prompt for distances between each pair of cities


for (i = 0; i < numCities; i++) {
for (j = 0; j < numCities; j++) {
if (i == j) {
distance[i * numCities + j] = 0; // Distance to itself is 0
} else if (i < j) {
printf("Enter the distance from city %d to city %d: ", i + 1, j + 1);
scanf("%d", &distance[i * numCities + j]);
distance[j * numCities + i] = distance[i * numCities + j]; // Assuming distance
is symmetric
}
}
}

int cities[MAX_CITIES];
for (i = 0; i < numCities; i++) {
cities[i] = i; // Initialize cities array
}

int minCost = INT_MAX;


int bestPath[MAX_CITIES]; // Array to store the best path

permute(cities, 0, numCities, distance, numCities, &minCost, bestPath);

printf("\nMinimum Cost: %d\n", minCost);


printf("Optimal Path: ");
for (i = 0; i < numCities; i++) {
printf("%d ", bestPath[i] + 1); // Print cities (1-indexed)
}
printf("%d\n", bestPath[0] + 1); // Return to starting city

return 0;
}

ARJ-BCA-COLLAGE, ILKAL 4
Design and Analysis of Algorithm 2024-25
Output
Enter the number of cities (max 10): 4
Enter the distance from city 1 to city 2: 20
Enter the distance from city 1 to city 3: 35
Enter the distance from city 1 to city 4: 42
Enter the distance from city 2 to city 3: 34
Enter the distance from city 2 to city 4: 30
Enter the distance from city 3 to city 4: 12

Minimum Cost: 97
Optimal Path: 1 2 4 3 1

ARJ-BCA-COLLAGE, ILKAL 5
Design and Analysis of Algorithm 2024-25
3. Write a program to perform knapsack problem using greedy solution.
#include <stdio.h>

typedef struct {
int weight;
int value;
double valuePerWeight; // Value-to-Weight ratio
} Item;

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


// Calculate value-to-weight ratio for each item
for (int i = 0; i < n; i++) {
items[i].valuePerWeight = (double) items[i].value / items[i].weight;
}
// Sort items based on value-to-weight ratio (descending order)
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (items[j].valuePerWeight < items[j + 1].valuePerWeight) {
// Swap
Item temp = items[j];
items[j] = items[j + 1];
items[j + 1] = temp;
}
}
}
double totalValue = 0.0;

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


if (items[i].weight <= capacity) {
// Take the whole item
totalValue += items[i].value;
capacity -= items[i].weight;
} else {
// Take a fraction of the item
double fraction = (double) capacity / items[i].weight;
totalValue += fraction * items[i].value;
capacity = 0;
}
}

ARJ-BCA-COLLAGE, ILKAL 6
Design and Analysis of Algorithm 2024-25
printf("Maximum value in the knapsack: %.2f\n", totalValue);
}

int main() {
int n, capacity;
printf("Enter the number of items: ");
scanf("%d", &n);
Item items[n];
printf("Enter the weight and value for each item:\n");
for (int i = 0; i < n; i++) {
printf("Item %d:\n", i + 1);
printf("Weight: ");
scanf("%d", &items[i].weight);
printf("Value: ");
scanf("%d", &items[i].value);
}

printf("Enter the knapsack capacity: ");


scanf("%d", &capacity);

fractionalKnapsack(items, n, capacity);

return 0;
}

Output
Enter the number of items: 3
Enter the weight and value for each item:
Item 1:
Weight: 10
Value: 60
Item 2:
Weight: 20
Value: 100
Item 3:
Weight: 30
Value: 120
Enter the knapsack capacity: 50
Maximum value in the knapsack: 240.00

ARJ-BCA-COLLAGE, ILKAL 7
Design and Analysis of Algorithm 2024-25
4. Write a program to implement DFs algorithm for a graph.
#include <stdio.h>
#include <stdbool.h>

#define MAX_VERTICES 100

typedef struct {
int vertices[MAX_VERTICES];
int adjacencyMatrix[MAX_VERTICES][MAX_VERTICES];
int numVertices;
} Graph;

void initGraph(Graph* g, int numVertices) {


g->numVertices = numVertices;

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


g->vertices[i] = 0;
for (int j = 0; j < numVertices; j++) {
g->adjacencyMatrix[i][j] = 0;
}
}
}

void addEdge(Graph* g, int start, int end) {


g->adjacencyMatrix[start][end] = 1;
g->adjacencyMatrix[end][start] = 1;
}

void DFS(Graph* g, int startVertex, bool visited[]) {


visited[startVertex] = true;
printf("%d ", startVertex);

for (int i = 0; i < g->numVertices; i++) {


if (g->adjacencyMatrix[startVertex][i] == 1 && !visited[i]) {
DFS(g, i, visited);
}
}
}

void performDFS(Graph* g, int startVertex) {

ARJ-BCA-COLLAGE, ILKAL 8
Design and Analysis of Algorithm 2024-25
bool visited[MAX_VERTICES] = {false};
printf("DFS traversal starting from vertex %d: ", startVertex);
DFS(g, startVertex, visited);
}
int main() {
Graph g;
int numVertices, startVertex;

printf("Enter the number of vertices: ");


scanf("%d", &numVertices);

initGraph(&g, numVertices);

printf("Enter the adjacency matrix:\n");


for (int i = 0; i < numVertices; i++) {
for (int j = 0; j < numVertices; j++) {
scanf("%d", &g.adjacencyMatrix[i][j]);
}
}

printf("Enter the starting vertex for DFS: ");


scanf("%d", &startVertex);

performDFS(&g, startVertex);

return 0;
}

Output
Enter the number of vertices: 4
Enter the adjacency matrix:
0110
1011
1101
0110
Enter the starting vertex for DFS: 0
DFS traversal starting from vertex 0: 0 1 2 3

ARJ-BCA-COLLAGE, ILKAL 9
Design and Analysis of Algorithm 2024-25
5. Write program to implement the BFS algorithm for a graph.
#include <stdio.h>
#include <stdbool.h>
#define MAX_VERTICES 100
typedef struct
{
int vertices[MAX_VERTICES];
int adjacencyMatrix[MAX_VERTICES][MAX_VERTICES];
int numVertices;
} Graph;

void initGraph(Graph *g, int numVertices)


{
g->numVertices = numVertices;

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


{
g->vertices[i] = 0;
for (int j = 0; j < numVertices; j++)
{
g->adjacencyMatrix[i][j] = 0;
}
}
}

void addEdge(Graph *g, int start, int end)


{
g->adjacencyMatrix[start][end] = 1;
g->adjacencyMatrix[end][start] = 1;
}
void BFS(Graph *g, int startVertex)
{
bool visited[MAX_VERTICES] = {false};
int queue[MAX_VERTICES];
int front = 0, rear = 0;
visited[startVertex] = true;
queue[rear++] = startVertex;
while (front < rear)
{
int currentVertex = queue[front++];

ARJ-BCA-COLLAGE, ILKAL 10
Design and Analysis of Algorithm 2024-25
printf("%d ", currentVertex);
for (int i = 0; i < g->numVertices; i++)
{
if (g->adjacencyMatrix[currentVertex][i] == 1 && !visited[i])
{
visited[i] = true;
queue[rear++] = i;
}
}
}
}

int main()
{
Graph g;
int numVertices, startVertex;

printf("Enter the number of vertices: ");


scanf("%d", &numVertices);

initGraph(&g, numVertices);

printf("Enter the adjacency matrix:\n");


for (int i = 0; i < numVertices; i++)
{
for (int j = 0; j < numVertices; j++)
{
scanf("%d", &g.adjacencyMatrix[i][j]);
}
}

printf("Enter the starting vertex for BFS: ");


scanf("%d", &startVertex);
printf("BFS traversal starting from vertex %d: ", startVertex);
BFS(&g, startVertex);

return 0;
}

ARJ-BCA-COLLAGE, ILKAL 11
Design and Analysis of Algorithm 2024-25
Output
Enter the number of vertices: 4
Enter the adjacency matrix:
0110
1011
1101
0110
Enter the starting vertex for BFS: 0
BFS traversal starting from vertex 0: 0 1 2 3

ARJ-BCA-COLLAGE, ILKAL 12
Design and Analysis of Algorithm 2024-25
6. Write a program to find minimum and maximum value in an array using
divide and conquer.
#include <stdio.h>
#include <stdlib.h>

typedef struct {
int min;
int max;
} MinMax;

MinMax findMinMax(int arr[], int low, int high) {


MinMax result, leftResult, rightResult;
int mid;

// Base case: only one element


if (low == high) {
result.min = arr[low];
result.max = arr[low];
return result;
}

// Base case: two elements


if (high == low + 1) {
if (arr[low] < arr[high]) {
result.min = arr[low];
result.max = arr[high];
} else {
result.min = arr[high];
result.max = arr[low];
}
return result;
}

// Recursive case: more than two elements


mid = (low + high) / 2;
leftResult = findMinMax(arr, low, mid);
rightResult = findMinMax(arr, mid + 1, high);

result.min = (leftResult.min < rightResult.min) ? leftResult.min : rightResult.min;


result.max = (leftResult.max > rightResult.max) ? leftResult.max : rightResult.max;

ARJ-BCA-COLLAGE, ILKAL 13
Design and Analysis of Algorithm 2024-25
return result;
}

int main() {
int n;

printf("Enter the number of elements in the array: ");


scanf("%d", &n);

// Check for non-positive number of elements


if (n <= 0) {
printf("Array size must be a positive integer.\n");
return 1; // Exit with error code
}

int *arr = (int *)malloc(n * sizeof(int)); // Dynamically allocate memory for the array
if (arr == NULL) {
printf("Memory allocation failed.\n");
return 1; // Exit with error code
}

printf("Enter the elements of the array:\n");


for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

MinMax result = findMinMax(arr, 0, n - 1);

printf("Minimum value in the array: %d\n", result.min);


printf("Maximum value in the array: %d\n", result.max);
free(arr);
}

Output
Enter the number of elements in the array: 5
Enter the elements of the array:
45 3 78 11 41
Minimum value in the array: 3
Maximum value in the array: 7

ARJ-BCA-COLLAGE, ILKAL 14
Design and Analysis of Algorithm 2024-25
7. Write a test program to implement Divide and Conquer Strategy for
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) {


int pivot = arr[high];
int i = low - 1;

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


if (arr[j] < pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}

swap(&arr[i + 1], &arr[high]);


return i + 1;
}

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


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

int main() {
int n;

printf("Enter the number of elements in the array: ");


scanf("%d", &n);

int arr[n];

ARJ-BCA-COLLAGE, ILKAL 15
Design and Analysis of Algorithm 2024-25
printf("Enter the elements of the array:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

quickSort(arr, 0, n - 1);
printf("Sorted array using Quick Sort:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}

return 0;
}

Output
Enter the number of elements in the array: 5
Enter the elements of the array:
65 77 82 23 11
Sorted array using Quick Sort:
11 23 65 77 82

ARJ-BCA-COLLAGE, ILKAL 16
Design and Analysis of Algorithm 2024-25
8. Write a program to implement Merge sort algorithm for sorting a list of
integers in ascending order

#include <stdio.h>

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


int n1 = mid - left + 1;
int n2 = right - mid;

int leftArr[n1], rightArr[n2];

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


leftArr[i] = arr[left + i];
}
for (int j = 0; j < n2; j++) {
rightArr[j] = arr[mid + 1 + j];
}

int i = 0, j = 0, k = left;

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


if (leftArr[i] <= rightArr[j]) {
arr[k++] = leftArr[i++];
} else {
arr[k++] = rightArr[j++];
}
}

while (i < n1) {


arr[k++] = leftArr[i++];
}

while (j < n2) {


arr[k++] = rightArr[j++];
}
}

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


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

ARJ-BCA-COLLAGE, ILKAL 17
Design and Analysis of Algorithm 2024-25

mergeSort(arr, left, mid);


mergeSort(arr, mid + 1, right);

merge(arr, left, mid, right);


}
}

int main() {
int n;

printf("Enter the number of elements in the array: ");


scanf("%d", &n);

int arr[n];
printf("Enter the elements of the array:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

mergeSort(arr, 0, n - 1);

printf("Sorted array using Merge Sort:\n");


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

return 0;
}

Output
Enter the number of elements in the array: 5
Enter the elements of the array:
54 67 33 87 41
Sorted array using Merge Sort:
33 41 54 67 87

ARJ-BCA-COLLAGE, ILKAL 18
Design and Analysis of Algorithm 2024-25
9. Write C program that accepts the vertices and edges for a graph and
stores it as an adjacency matrix.

#include <stdio.h>

#define MAX_VERTICES 100

typedef struct {
int adjacencyMatrix[MAX_VERTICES][MAX_VERTICES];
int numVertices;
} Graph;

void initGraph(Graph* g, int numVertices) {


g->numVertices = numVertices;

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


for (int j = 0; j < numVertices; j++) {
g->adjacencyMatrix[i][j] = 0;
}
}
}

void addEdge(Graph* g, int start, int end) {


g->adjacencyMatrix[start][end] = 1;
}

void displayGraph(Graph* g) {
printf("Adjacency Matrix:\n");
for (int i = 0; i < g->numVertices; i++) {
for (int j = 0; j < g->numVertices; j++) {
printf("%d ", g->adjacencyMatrix[i][j]);
}
printf("\n");
}
}

int main() {
Graph g;
int numVertices, numEdges;

ARJ-BCA-COLLAGE, ILKAL 19
Design and Analysis of Algorithm 2024-25
printf("Enter the number of vertices: ");
scanf("%d", &numVertices);

initGraph(&g, numVertices);
printf("Enter the number of edges: ");
scanf("%d", &numEdges);

printf("Enter the edges (start vertex end vertex):\n");


for (int i = 0; i < numEdges; i++) {
int start, end;
scanf("%d %d", &start, &end);
addEdge(&g, start, end);
}

displayGraph(&g);

return 0;
}

Output
Enter the number of vertices: 5
Enter the number of edges: 7
Enter the edges (start vertex end vertex):
01
02
12
13
23
34
40
Adjacency Matrix:
01100
00110
00010
00001
10000

ARJ-BCA-COLLAGE, ILKAL 20
Design and Analysis of Algorithm 2024-25
10. Implement function to print In-Degree, Out-Degree and to display that
adjacency matrix.

#include <stdio.h>

#define MAX_VERTICES 100

typedef struct {
int adjacencyMatrix[MAX_VERTICES][MAX_VERTICES];
int numVertices;
} Graph;

void initGraph(Graph* g, int numVertices) {


g->numVertices = numVertices;

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


for (int j = 0; j < numVertices; j++) {
g->adjacencyMatrix[i][j] = 0;
}
}
}

void addEdge(Graph* g, int start, int end) {


g->adjacencyMatrix[start][end] = 1;
}

void displayGraph(Graph* g) {
printf("Adjacency Matrix:\n");
for (int i = 0; i < g->numVertices; i++) {
for (int j = 0; j < g->numVertices; j++) {
printf("%d ", g->adjacencyMatrix[i][j]);
}
printf("\n");
}
}

void calculateDegrees(Graph* g) {
printf("Vertex\tIn-Degree\tOut-Degree\n");
for (int i = 0; i < g->numVertices; i++) {
int inDegree = 0, outDegree = 0;

ARJ-BCA-COLLAGE, ILKAL 21
Design and Analysis of Algorithm 2024-25
for (int j = 0; j < g->numVertices; j++) {
inDegree += g->adjacencyMatrix[j][i];
outDegree += g->adjacencyMatrix[i][j];
}
printf("%d\t%d\t\t%d\n", i, inDegree, outDegree);
}
}

int main() {
Graph g;
int numVertices, numEdges;

printf("Enter the number of vertices: ");


scanf("%d", &numVertices);

initGraph(&g, numVertices);

printf("Enter the number of edges: ");


scanf("%d", &numEdges);

printf("Enter the edges (start vertex end vertex):\n");


for (int i = 0; i < numEdges; i++) {
int start, end;
scanf("%d %d", &start, &end);
addEdge(&g, start, end);
}

displayGraph(&g);
calculateDegrees(&g);

return 0;
}

ARJ-BCA-COLLAGE, ILKAL 22
Design and Analysis of Algorithm 2024-25

Output
Enter the number of vertices: 5
Enter the number of edges: 7
Enter the edges (start vertex end vertex):
01
02
12
13
23
34
40
Adjacency Matrix:
01100
00110
00010
00001
10000
Vertex In-Degree Out-Degree
0 1 2
1 1 2
2 2 1
3 2 1
4 1 1

ARJ-BCA-COLLAGE, ILKAL 23

You might also like