0% found this document useful (0 votes)
19 views22 pages

Daa Pratical File

DAA PRATICAL FILE

Uploaded by

amanrajwansi014
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)
19 views22 pages

Daa Pratical File

DAA PRATICAL FILE

Uploaded by

amanrajwansi014
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/ 22

R.

R INSTITUTE OF MODERN TECHNOLOGY


(NH-24,Bakshi Ka Talab,Sitapur Road Lucknow, Uttar Pradesh)

Lab Manual
Design And Analysis Of Algorithm

(BCS-553)

Session 2024-2025

Submitted by– Submitted to–:


Harsh Upadhyay Mr. Sandip Kumar
(2203611650020) singh
CSD-3rd Year

NAME-:Harsh Upadhyay ROLL NO.-:2203611650020 BRANCH-:CSD YEAR-:3rd


DESIGN AND ANALYSIS OF ALGORITHMS
LAB MANUAL

Ques 1. Program for Recursive Binary Search


Ans. Objective:To implement Binary Search using recursion and analyze its efficiency.
Algorithm:
1. If the target element is equal to the middle element, return the middle index.
2. If the target element is smaller than the middle element, search in the left half.
3. If the target element is larger than the middle element, search in the right half.
4. Repeat the process until the element is found or the search space is exhausted.

Code:
#include <stdio.h>
int binarySearch(int arr[], int target, int low, int high) {
if (low <= high) {
int mid = (low + high) / 2;
// If the target is found
if (arr[mid] == target)
return mid;
// If target is smaller, search in the left half
if (arr[mid] > target)
return binarySearch(arr, target, low, mid - 1)
// If target is larger, search in the right half
return binarySearch(arr, target, mid + 1, high);
}
return -1; // Element not found
NAME-:Harsh Upadhyay ROLL NO.-:2203611650020 BRANCH-:CSD YEAR-:3rd
}

int main() {
int arr[] = {2, 3, 4, 10, 40};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 10;
int result = binarySearch(arr, target, 0, n - 1);
if (result != -1)
printf("Element found at index %d\n", result);
else
printf("Element not found\n");
return 0;
}

Time Complexity:
- Best Case:O(1)
- Worst Case: O(log n)

-------------------------------------------------------------------------------------------------------------------------------------------------

Ques 2. Program for Heap Sort


Ans.Objective:To implement Heap Sort, a comparison-based sorting algorithm using the heap data structure.
Algorithm:
1. Build a max heap from the input data.
2. Swap the root (largest element) with the last element in the heap.
3. Heapify the root of the tree.
4. Repeat the process until the heap is empty.

Code:
NAME-:Harsh Upadhyay ROLL NO.-:2203611650020 BRANCH-:CSD YEAR-:3rd
#include <stdio.h>
void heapify(int arr[], int n, int i) {
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < n &&arr[left] >arr[largest])
largest = left;
if (right < n &&arr[right] >arr[largest])
largest = right;
if (largest != i) {
int temp = arr[i];
arr[i] = arr[largest];
arr[largest] = temp;
heapify(arr, n, largest);
}
}

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


for (int i = n / 2 - 1; i>= 0; i--)
heapify(arr, n, i);
for (int i = n - 1; i>= 1; i--) {
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
heapify(arr, i, 0);
}
}

int main() {

NAME-:Harsh Upadhyay ROLL NO.-:2203611650020 BRANCH-:CSD YEAR-:3rd


int arr[] = {12, 11, 13, 5, 6, 7};
int n = sizeof(arr) / sizeof(arr[0]);
heapSort(arr, n);
printf("Sorted array is: ");
for (int i = 0; i< n; i++)
printf("%d ", arr[i]);
printf("\n");
return 0;
}

Time Complexity:
- Best Case: O(n log n)
- Worst Case: O(n log n)

------------------------------------------------------------------------------------------------------------------------------------------------

Ques 3. Program for Merge Sort.


Ans.Objective:To implement Merge Sort, a divide-and-conquer algorithm.
Algorithm:
1. Divide the array into two halves.
2. Recursively sort each half.
3. Merge the two sorted halves to produce the sorted array.

Code:
#include <stdio.h>
void merge(int arr[], int l, int m, int r) {
int n1 = m - l + 1;
int n2 = r - m;
int L[n1], R[n2];
NAME-:Harsh Upadhyay ROLL NO.-:2203611650020 BRANCH-:CSD YEAR-:3rd
for (int i = 0; i< n1; i++)
L[i] = arr[l + i];
for (int j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];
int i = 0, j = 0, k = l;
while (i< n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
while (i< n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}

void mergeSort(int arr[], int l, int r) {


if (l < r) {

NAME-:Harsh Upadhyay ROLL NO.-:2203611650020 BRANCH-:CSD YEAR-:3rd


int m = (l + r) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
}

int main() {
int arr[] = {12, 11, 13, 5, 6, 7};
int n = sizeof(arr) / sizeof(arr[0]);
mergeSort(arr, 0, n - 1);
printf("Sorted array is: ");
for (int i = 0; i< n; i++)
printf("%d ", arr[i]);
printf("\n");
return 0;
}

Time Complexity:
- Best Case: O(n log n)
- Worst Case: O(n log n)

-------------------------------------------------------------------------------------------------------------------------------------------------

Ques 4.Program for Selection Sort


Ans. Objective:To implement Selection Sort, an in-place comparison sorting algorithm.
Algorithm:
1. Find the minimum element in the unsorted part of the array.
2. Swap it with the element at the beginning of the unsorted part.
NAME-:Harsh Upadhyay ROLL NO.-:2203611650020 BRANCH-:CSD YEAR-:3rd
3. Repeat until the array is sorted.

Code:
#include <stdio.h>
void selectionSort(int arr[], int n) {
for (int i = 0; i< n - 1; i++) {
int minIdx = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] <arr[minIdx])
minIdx = j;
}
int temp = arr[minIdx];
arr[minIdx] = arr[i];
arr[i] = temp;
}
}

int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr) / sizeof(arr[0]);
selectionSort(arr, n);
printf("Sorted array is: ");
for (int i = 0; i< n; i++)
printf("%d ", arr[i]);
printf("\n");
return 0;
}

Time Complexity:

NAME-:Harsh Upadhyay ROLL NO.-:2203611650020 BRANCH-:CSD YEAR-:3rd


- Best Case:O(n^2)
- Worst Case: O(n^2)

--------------------------------------------------------------------------------------------------------------------------------------------------

Ques 5. Program for Insertion Sort


Ans. Objective:To implement Insertion Sort, which builds the sorted array one item at a time.

Algorithm:
1. Start with the second element. Compare it with the elements before it.
2. Shift all larger elements to the right and insert the current element in its correct position.
3. Repeat for all elements in the array.

Code:
#include <stdio.h>
void insertionSort(int arr[], int n) {
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;
}
}

int main() {
int arr[] = {12, 11, 13, 5, 6};
NAME-:Harsh Upadhyay ROLL NO.-:2203611650020 BRANCH-:CSD YEAR-:3rd
int n = sizeof(arr) / sizeof(arr[0]);
insertionSort(arr, n);
printf("Sorted array is: ");
for (int i = 0; i< n; i++)
printf("%d ", arr[i]);
printf("\n");
return 0;
}

Time Complexity:
-Best Case: O(n)
- Worst Case: O(n^2)

--------------------------------------------------------------------------------------------------------------------------------------------------

Ques 6. Program for Quick Sort.


Ans. Objective:To implement Quick Sort, a divide-and-conquer sorting algorithm.
Algorithm:
1. Choose a pivot element.
2. Partition the array such that elements less than the pivot are on the left and elements greater are onright.
3. Recursively apply the same procedure tothe left and right subarrays.

Code:
#include <stdio.h>
int partition(int arr[], int low, int high) {
int pivot = arr[high];
int i = low - 1;
for (int j = low; j < high; j++) {
NAME-:Harsh Upadhyay ROLL NO.-:2203611650020 BRANCH-:CSD YEAR-:3rd
if (arr[j] <= pivot) {
i++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int temp = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp;
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 arr[] = {10, 7, 8, 9, 1, 5};
int n = sizeof(arr) / sizeof(arr[0]);
quickSort(arr, 0, n - 1);
printf("Sorted array is: ");
for (int i = 0; i< n; i++)
printf("%d ", arr[i]);
printf("\n");

NAME-:Harsh Upadhyay ROLL NO.-:2203611650020 BRANCH-:CSD YEAR-:3rd


return 0;
}

Time Complexity:
- Best Case: O(n log n)
- Worst Case: O(n^2)

--------------------------------------------------------------------------------------------------------------------------------------------------

Ques 7. Knapsack Problem Using Greedy Solution.


Ans. Objective:To solve the Knapsack Problem using the Greedy approach, where items are chosen based on
the maximum value-to-weight ratio.
Algorithm:
1. Sort the items in decreasing order of their value-to-weight ratio.
2. Start adding the items to the knapsack in sorted order.
3. If the current item can fit into the knapsack, add it; otherwise, skip it.

Code:
#include <stdio.h>
struct Item {
int value;
int weight;
};

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


double r1 = ((struct Item *)a)->value / (double)((struct Item *)a)->weight;
double r2 = ((struct Item *)b)->value / (double)((struct Item *)b)->weight;
NAME-:Harsh Upadhyay ROLL NO.-:2203611650020 BRANCH-:CSD YEAR-:3rd
return (r1 > r2) ? -1 : 1;
}

double knapsack(struct Item items[], int n, int capacity) {


qsort(items, n, sizeof(struct Item), cmp);
int currentWeight = 0;
double finalValue = 0.0;
for (int i = 0; i< n; i++) {
if (currentWeight + items[i].weight<= capacity) {
currentWeight += items[i].weight;
finalValue += items[i].value;
} else {
int remain = capacity - currentWeight;
finalValue += items[i].value * ((double) remain / items[i].weight);
break;
}
}
return finalValue;
}

int main() {
struct Item items[] = {{60, 10}, {100, 20}, {120, 30}};
int n = sizeof(items) / sizeof(items[0]);
int capacity = 50;
printf("Maximum value we can obtain = %.2f\n", knapsack(items, n, capacity));
return 0;
}

Time Complexity:

NAME-:Harsh Upadhyay ROLL NO.-:2203611650020 BRANCH-:CSD YEAR-:3rd


- Best Case: O(n log n) (for sorting)
- Worst Case: O(n log n) (for sorting)

--------------------------------------------------------------------------------------------------------------------------------------------------

Ques 8. Travelling Salesman Problem (TSP).


Ans. Objective:To solve the Travelling Salesman Problem using a brute force approach to find the shortest
path that visits every city once and returns to the starting point.
Algorithm:
1. Generate all permutations of cities.
2. Calculate the total distance for each permutation.
3. Return the minimum distance.

Code:
#include <stdio.h>
#include <limits.h>
#define V 4
int min(int a, int b) {
return (a < b) ? a : b;
}

int tsp(int dist[][V], int visited[], int currPos, int count, int cost, int ans) {
if (count == V) {
if (dist[currPos][0] != 0)
return min(ans, cost + dist[currPos][0]);
return ans;
}
for (int i = 0; i< V; i++) {
if (!visited[i] &&dist[currPos][i] != 0) {

NAME-:Harsh Upadhyay ROLL NO.-:2203611650020 BRANCH-:CSD YEAR-:3rd


visited[i] = 1;
ans = tsp(dist, visited, i, count + 1, cost + dist[currPos][i], ans);
visited[i] = 0;
}
}
return ans;
}

int main() {
int dist[V][V] = {{0, 10, 15, 20},
{10, 0, 35, 25},
{15, 35, 0, 30},
{20, 25, 30, 0}};
int visited[V] = {0};
visited[0] = 1;
int ans = INT_MAX;
printf("Minimum cost of traveling: %d\n", tsp(dist, visited, 0, 1, 0, ans));
return 0;
}

Time Complexity:
- Best Case: O(n!)
- Worst Case: O(n!)

--------------------------------------------------------------------------------------------------------------------------------------------------

Ques 9. Find Minimum Spanning Tree Using Kruskal’s Algorithm.


Ans. Objective:To find the Minimum Spanning Tree (MST) of a graph using Kruskal's algorithm, which finds the
edge with the least weight to form a spanning tree.

NAME-:Harsh Upadhyay ROLL NO.-:2203611650020 BRANCH-:CSD YEAR-:3rd


Algorithm:
1. Sort all edges in non-decreasing order of their weight.
2. Add edges one by one to the MST, making sure no cycle is formed.
3. Use a Union-Find data structure to detect cycles.

Code:
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
struct Edge {
int u, v, weight;
};

struct Subset {
int parent;
int rank;
};

int find(struct Subset subsets[], int i) {


if (subsets[i].parent != i)
subsets[i].parent = find(subsets, subsets[i].parent);
return subsets[i].parent;
}

void unionSets(struct Subset subsets[], int x, int y) {


int xroot = find(subsets, x);
int yroot = find(subsets, y);
if (subsets[xroot].rank< subsets[yroot].rank)
subsets[xroot].parent = yroot;

NAME-:Harsh Upadhyay ROLL NO.-:2203611650020 BRANCH-:CSD YEAR-:3rd


else if (subsets[xroot].rank> subsets[yroot].rank)
subsets[yroot].parent = xroot;
else {
subsets[yroot].parent = xroot;
subsets[xroot].rank++;
}
}

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


return ((struct Edge *)a)->weight - ((struct Edge *)b)->weight;
}

void kruskal(struct Edge edges[], int V, int E) {


struct Subset subsets[V];
for (int i = 0; i< V; i++) {
subsets[i].parent = i;
subsets[i].rank = 0;
}
qsort(edges, E, sizeof(struct Edge), compareEdges);
printf("Edges in MST:\n");
int mstWeight = 0;
for (int i = 0; i< E; i++) {
int x = find(subsets, edges[i].u);
int y = find(subsets, edges[i].v);
if (x != y) {
printf("%d -- %d: %d\n", edges[i].u, edges[i].v, edges[i].weight);
mstWeight += edges[i].weight;
unionSets(subsets, x, y);
}

NAME-:Harsh Upadhyay ROLL NO.-:2203611650020 BRANCH-:CSD YEAR-:3rd


}
printf("Weight of MST: %d\n", mstWeight);
}

int main() {
int V = 4, E = 5;
struct Edge edges[] = {{0, 1, 10}, {0, 2, 6}, {0, 3, 5}, {1, 3, 15}, {2, 3, 4}};
kruskal(edges, V, E);
return 0;
}

Time Complexity:
- Best Case: O(E log E)
- Worst Case: O(E log E)

--------------------------------------------------------------------------------------------------------------------------------------------------

Ques 10. Implement N-Queen Problem Using Backtracking.


Ans. Objective:To solve the N-Queens problem using Backtracking, where the goal is to place N queens on an
N×N chessboard such that no two queens threaten each other.
Algorithm:
1. Start placing queens in the first column.
2. Move to the next column and try to place a queen in every row.
3. If placing the queen leads to a valid configuration, move to the next column.
4. If placing the queen leads to an invalid configuration, backtrack and try a different position.

Code:
#include <stdio.h>
#define N 4

NAME-:Harsh Upadhyay ROLL NO.-:2203611650020 BRANCH-:CSD YEAR-:3rd


int board[N][N];
int isSafe(int row, int col) {
for (int i = 0; i< col; i++)
if (board[row][i] == 1)
return 0;
for (int i = row, j = col; i>= 0 && j >= 0; i--, j--)
if (board[i][j] == 1)
return 0;
for (int i = row, j = col; j >= 0 &&i< N; i++, j--)
if (board[i][j] == 1)
return 0;
return 1;
}

int solveNQueens(int col) {


if (col >= N)
return 1;
for (int i = 0; i< N; i++) {
if (isSafe(i, col)) {
board[i][col] = 1;
if (solveNQueens(col + 1))
return 1;
board[i][col] = 0;
}
}
return 0;
}
void printSolution() {
for (int i = 0; i< N; i++) {

NAME-:Harsh Upadhyay ROLL NO.-:2203611650020 BRANCH-:CSD YEAR-:3rd


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

int main() {
if (solveNQueens(0) == 0) {
printf("Solution does not exist");
return 0;
}
printSolution();
return 0;
}

Time Complexity:
- Worst Case: O(N!)

--------------------------------------------------------------------------------------------------------------------------------------------------

Ques 11. Quick Sort with Time Complexity Analysis*


Ans.Objective:To implement Quick Sort for sorting a given set of integers and compute its time complexity.
Algorithm:
1. Choose a pivot element.
2. Partition the array such that elements less than the pivot are on the left and elements greater are on right.
3. Recursively apply Quick Sort to the left and right subarrays.

Code:
#include <stdio.h>
#include <stdlib.h>
NAME-:Harsh Upadhyay ROLL NO.-:2203611650020 BRANCH-:CSD YEAR-:3rd
#include <time.h>
void quickSort(int arr[], int low, int high) {
if (low < high) {
int pivot = arr[high];
int i = (low - 1);
for (int j = low; j < high; j++) {
if (arr[j] < pivot) {
i++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int temp = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp;
int pi = i + 1;
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}

int main() {
int n = 5000; // Can be varied
int arr[n];
for (int i = 0; i< n; i++) {
arr[i] = rand() % 10000; // Generating random numbers
}
clock_t start = clock();

NAME-:Harsh Upadhyay ROLL NO.-:2203611650020 BRANCH-:CSD YEAR-:3rd


quickSort(arr, 0, n - 1);
clock_t end = clock();
double time_taken = ((double)(end - start)) / CLOCKS_PER_SEC;
printf("Time taken to sort %d elements: %f seconds\n", n, time_taken);
return 0;
}

Time Complexity:
- Best Case: O(n log n)
- Worst Case: O(n²)

NAME-:Harsh Upadhyay ROLL NO.-:2203611650020 BRANCH-:CSD YEAR-:3rd

You might also like