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

Design & Analysis of Algorithm

The document discusses the implementation of various sorting algorithms like insertion sort, selection sort, shell sort, bubble sort, merge sort, quick sort, linear and binary search, and heap sort. Code snippets are provided for each algorithm in C language along with sample input/output.

Uploaded by

Keshav Mishra
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Design & Analysis of Algorithm

The document discusses the implementation of various sorting algorithms like insertion sort, selection sort, shell sort, bubble sort, merge sort, quick sort, linear and binary search, and heap sort. Code snippets are provided for each algorithm in C language along with sample input/output.

Uploaded by

Keshav Mishra
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 32

DAA Lab 2023

Program – 01

Objective: Implementation of Insertion Sort


Algorithm:
Insertion Sort(A)
1. for j2 to length(A)
2. do key  A[j]
3. |> comment insert A[j] into the second sequence
4. ij-1
5. while i>0 and A[i]>key
6. do A[i+1] A[i]
7. ii-1
8. A[i+1]key
CODE:
#include <stdio.h>
void insert (int a [], int n) {
int i, j, temp;
for (i = 1; i < n; i++) {
temp = a[i];
j = i - 1;
while(j>=0 && temp <= a[j]) {
a[j+1] = a[j];
}
a[j+1] = temp;
}
}
void printArr (int a [], int n) {
int i;
for (i = 0; i < n; i++)
printf ("%d ", a[i]);
}
int main () {
int n, i;
printf ("\n Enter the size of array: ");
scanf ("%d", &n);
int arr[n];
printf ("\n Enter the Elements of array: ");
for (i=0; i<n; i++) {
scanf ("%d", &arr[i]);
}
insertionSort (arr, n);
printArray (arr, n);
return 0;
}

Output:
Program-02

Objective: Implementation of Selection Sort


Algorithm:
Selection Sort (A, n)
1.For i=1 to n-1
2.Min=i
3.For j=j+1 to n
4. If A[j]< A[min]
6. Min=j
7. If min != i
8. A[min]<->A[i]
CODE:
#include <stdio.h>
void selectionSort (int arr [], int n) {
int i, j, key;
for (i = 0; i < n-1; i++) {
key = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[small])
key = j;
int temp = arr[key];
arr[key] = arr[i];
arr[i] = temp;
}
}
void printArr (int a [], int n) {
int i;
for (i = 0; i < n; i++)
printf ("%d ", a[i]);
}
int main () {
int n, i;
printf ("\n Enter the size of array: ");
scanf ("%d", &n);
int arr[n];
printf ("\n Enter the Elements of array: ");
for (i=0; i<n; i++) {
scanf ("%d", &arr[i]);
}
selectionSort (arr, n);
printf ("Sorted array: \n");
printArray (arr, n);
return 0;
}

Output:
Program-03

Objective: Implementation of Shell Sort


Algorithm:
The algorithm for shell sort can be defined in two steps--
Step 1: Divide the original list into smaller lists
Step 2: Sort individual sub list using any known sorting algorithm.
Code:
#include <stdio.h>
void shellSort (int array [], int n) {
for (int interval = n / 2; interval > 0; interval /= 2) {
for (int i = interval; i < n; i += 1) {
int temp = array[i];
int j;
for (j = i; j >= interval && array [j - interval] > temp; j -= interval) {
array[j] = array [j - interval];
}
array[j] = temp;
}
}
}
void printArray (int array [], int size) {
for (int i = 0; i < size; ++i) {
printf ("%d ", array[i]);
}
printf("\n");
}
int main () {
int n, i;
printf ("\n Enter the size of array: ");
scanf ("%d", &n);
int arr[n];
printf ("\n Enter the Elements of array: ");
for (i=0; i<n; i++) {
scanf ("%d", &arr[i]);
}
shellSort (arr, n);
printf ("Sorted array: \n");
printArray (arr, n);
}

Output:
Program-04

Objective: - Implementation of Bubble Sort


Algorithm:

Code:
#include<stdio.h>
void main ()
{
int n, i, j;
printf ("Enter the size of array:");
scanf ("%d", &n);
int a[n];
printf ("Enter the Elements of array:\n");
for (i=0; i<n; i++) {
scanf ("%d", &a[i]);
}
for (i=0; i<n-1; i++) {
for (j=i+1; j<n; j++) {
if(a[j]<a[i]) {
int temp=a[j];
a[j]=a[i];
a[i]=temp;
}
}
}
printf ("\nSorted Array is: ");
for (i=0; i<n; i++) {
printf ("%d ", a[i]);
}
}

Output: -
Program-05

Objective: - Implementation of Merge Sort


Algorithm: -
Code: -
#include <stdio.h>
#include <stdlib.h>
void merge (int arr [], int l, int m, int r) {
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
int L[n1], R[n2];
for (i = 0; i < n1; i++)
L[i] = arr [l + i];
for (j = 0; j < n2; j++)
R[j] = arr [m + 1 + j];
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) {
int m = l + (r - l) / 2;
mergeSort (arr, l, m);
mergeSort (arr, m + 1, r);
merge (arr, l, m, r);
}
}

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


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

int main () {
int n, i;
printf ("\n Enter the size of array: ");
scanf ("%d", &n);
int arr[n];
printf ("\n Enter the Elements of array: ");
for (i=0; i<n; i++) {
scanf ("%d", &arr[i]);
}
Printf ("Given array is \n");
printArray (arr, n);
mergeSort (arr, 0, n - 1);
printf ("\nSorted array is \n");
printArray (arr, n);
return 0;
}

Output:-
Program-06

Objective: - Implementation of Quick Sort


Algorithm: -
quickSort (A, p, r)
1. if p<r
2. then q partition (A, p, r)
3. quickSort (A, p, q-1)
4 quickSort (A, p+1, r)

PARTITION (A, p, r)
1. XA[r]
2. ip-1
3. For jp to r-1
4. do if A[j] <= x
5. Theni i+1
6. Exchange A[i]A[j]
7. Exchange A[i+1]A[r]
8. Return i+1

CODE: -
#include <stdio.h>
void swap (int *a, int *b) {
int t = *a;
*a = *b;
*b = t;
}
int partition (int array [], int low, int high) {
int pivot = array[high];
int i = (low - 1);
for (int j = low; j < high; j++) {
if (array[j] <= pivot) {
i++;
swap(&array[i], &array[j]);
}
}
swap (&array [i + 1], &array[high]);
return (i + 1);
}
void quickSort (int array [], int low, int high) {
if (low < high) {
int pi = partition (array, low, high);
quickSort (array, low, pi - 1);
quickSort (array, pi + 1, high);
}
}
void printArray (int array [], int size) {
for (int i = 0; i < size; ++i) {
printf ("%d ", array[i]);
}
printf("\n");
}
int main () {
int n, i;
printf ("\n Enter the size of array: ");
scanf ("%d", &n);
int arr[n];
printf ("\n Enter the Elements of array: ");
for (i=0; i<n; i++) {
scanf ("%d", &arr[i]);
}
printf ("Unsorted Array\n");
printArray (arr, n);
quickSort (arr, 0, n - 1);
printf ("Sorted array in ascending order: \n");
printArray (arr, n);
}

Output: -
Program-07

Objective: - Implementation of Linear and Binary Search


Algorithm: -
Linear Search
Linear Search (Array A, Value x)
1: Set I to 1
2: if I > n then go to step 7
3: if A[i] = x then go to step 6
4: Set I to I + 1
5: Go to Step 2
6: Print Element x Found at index I and go to step 8
7: Print element not found
8: Exit

Binary Search
1. Def. binary Search (A, x):
2. N = only (A)
3. Beg=0
4. End = n – 1
5. Result = -1
6. While (beg <= end):
7. Mid = (beg + end)/2
8. If (A[mid] <= x):
9. Beg = mid + 1
10. result = mid
11. Else:
12. end = mid – 1
Return result
Code: -
Linear search:
#include<stdio.h>
int main () {
int i, n, e;
printf ("\nEnter the size of array: ");
scanf ("%d", &n);
int arr [n];
printf ("Enter Elements of array:\n");
for (i=0; i<n; i++) {
scanf ("%d", &arr[i]);
}
printf ("Enter the Element to Search: ");
scanf ("%d", &e);
for (i=0; i<n; i++) {
if (arr [i] == e) {
printf ("Required Element is found at index %d", i);
}
} return 0;
}

Binary search:
#include<stdio.h>
int main () {
int n, i, e;
printf ("\nEnter the size of array: ");
scanf ("%d", &n);
int arr [n];
printf ("Enter Elements of array:\n");
for (i=0; i<n; i++) {
scanf ("%d", &arr[i]);
}
printf ("Enter the Element to Search: ");
scanf ("%d", &e);
int low=0, high=9, mid;
while (low<= high) {
mid = (low + high)/2;
if(e==arr[mid]) {
printf ("Required Element is found at index %d", mid);
break;
} else if(e>arr[mid]) {
low=mid+1;
} else {
high=mid-1;
}
}
return 0;
}

Output: -
Linear Search:

Binary Search:
Program-08
Objective: - Implementation of Heap Sort
Algorithm: -
Heapsort (A)
Build maxHeap[A]
1. for i<-- length [A] downto 2
2. do exchange A[I] ← A[i].
3. Heap. Size (A) ← heapsize [A]-l
4. maxHeapify (A, l)

maxHeapify (A, i)
1. l<-- left [i]
2. r<-- right [i]
3. if I <= heapsize [A] and A[l]>A[I]
4. then largest <-- I
5. else largest<--i
6. if r <= heap size[A] and A[r]> A[largest]
7. then largest <--r
8. if largest != i
9. then exchange A [i]<--> A[largest]
10. maxHeapify (A, Largest)

Code: -
#include<stdio.h>
void swap (int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
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) {
swap(&arr[i], &arr[largest]);
heapify (arr, N, largest);
}
}

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


int i;
for (i = N / 2 - 1; i >= 0; i--)
heapify (arr, N, i);

for (i = N - 1; i >= 0; i--) {


swap (&arr [0], &arr[i]);
heapify (arr, i, 0);
}
}

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


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

int main () {
int n, i;
printf ("\n Enter the size of array: ");
scanf ("%d", &n);
int arr[n];
printf ("\n Enter the Elements of array: ");
for (i=0; i<n; i++) {
scanf ("%d", &arr[i]);
}
heapSort (arr, n);
printf ("Sorted array is\n");
printArray (arr, n);
}

Output: -

Program-09
Objective: - Implementation of Greedy Fractional Knapsack.
Algorithm: -
Greedy Fractional Knapsack ()
1. {
2. For i=1 to n
3. do x[i]=0
4. Weight =0;
5. For i1 to n
6. If weight +w<=W
7. Then xi=1
8. Weight = weight +w[i]
9. Else x[i]=(w-weight )/wi
10. Weight =w
11. Break
12. Return x
13. }

CODE: -
#include <stdio.h>
#include <stdlib.h>
struct Item {
int profit, weight;
};
static int cmp (const void* a, const void* b) {
struct Item* itemA = (struct Item*)a;
struct Item* itemB = (struct Item*)b;
double r1 = (double)itemA->profit / (double)itemA->weight;
double r2 = (double)itemB->profit / (double)itemB->weight;
if (r1 > r2)
return -1;
else if (r1 < r2)
return 1;
else
return 0;
}
double fractionalKnapsack (int W, struct Item arr [], int N) {
int i;
qsort (arr, N, sizeof (struct Item), cmp);
double finalvalue = 0.0;
for (i = 0; i < N; i++) {
if (arr[i].weight <= W) {
W -= arr[i].weight;
finalvalue += arr[i].profit;
}
else {
finalvalue += arr[i].profit * ((double)W / (double)arr[i].weight);
break;
}
}
return finalvalue;
}
int main () {
int W = 50;
struct Item arr [] = { { 60, 10}, { 100, 20}, { 120, 30} };
int N = sizeof(arr) / sizeof (arr [0]);
printf ("\nMaximum profit is: %f", fractionalKnapsack (W, arr, N));
return 0;
}

Output: -

Program-10
Objective: - Implementation of MST using Kruskal Method.
Algorithm: -
1. A(|)
2. for each vertex u (- V (G)
3. do Make Set (v)
4. sort the edge of E into nondecreasing order by weight W
5. for each edge (u,v) (- E taken in nondecresing order by weight W
6. do if find set (u) =/ find set (v)
7. then AAU{(u,v)}
8. union(u,v)
9. return A

CODE: -
#include <stdio.h>
#include <stdlib.h>
int comparator (const void* p1, const void* p2) {
const int(*x) [3] = p1;
const int(*y) [3] = p2;
return (*x) [2] - (*y) [2];
}
void makeSet (int parent [], int rank [], int n) {
int i;
for (i = 0; i < n; i++) {
parent[i] = i;
rank[i] = 0;
}
}
int findParent (int parent [], int component) {
if (parent[component] == component)
return component;
return parent[component]
= findParent (parent, parent [component]);
}
void unionSet (int u, int v, int parent [], int rank [], int n) {
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;
rank[u]++;
}
}
void kruskalAlgo (int n, int edge[n][3]) {
qsort (edge, n, sizeof (edge [0]), comparator);
int parent[n];
int rank[n];
makeSet (parent, rank, n);
int minCost = 0, i;
printf ("Following are the edges in the constructed MST\n");
for (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 (v1 != v2) {
unionSet (v1, v2, parent, rank, n);
minCost += wt;
printf ("%d -- %d == %d\n", edge[i][0],
edge[i][1], wt);
}
}
printf ("Minimum Cost Spanning Tree: %d\n", minCost);
}
int main () {
int edge [5][3] = { { 0, 1, 10},
{ 0, 2, 6},
{ 0, 3, 5},
{ 1, 3, 15},
{ 2, 3, 4} };
kruskalAlgo (5, edge);
return 0;
}

Output: -

Program-11
Objective: - Implementation of N-Queens problem.
Algorithm: -
N-Queens (k, n)
1. for i1 to n
2. do if place (k, i)
3. then n[k]i
4. if(k=n)
5. then write (n, (1….n))
6. else N-Queens (k+1, n);

place (k, i)
1. for j1 to k-1
2. do if (x(j)=1) or abs(x(j)-1) = (abs (j-k))
3. then return false
4. else return true
CODE: -
#include <stdbool.h>
#include <stdio.h>
#define N 4
void printSolution (int board[N][N]) {
int i, j;
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++)
printf (" %d ", board[i][j]);
printf ("\n");
}
}
bool isSafe (int board[N][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[N][N], int col) {
int i;
if (col >= N)
return true;
for (i = 0; i < N; i++) {
if (isSafe (board, i, col)) {
board[i][col] = 1;
if (solveNQUtil (board, col + 1))
return true;
board[i][col] = 0; // BACKTRACK
}
}
return false;
}
bool solveNQ () {
int board[N][N] = { { 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 } };

if (solveNQUtil (board, 0) == false) {


printf ("Solution does not exist");
return false;
}
printf("\n");
printSolution (board);
return true;
}
int main () {
solveNQ ();
return 0;
}

OUTPUT: -

Program-12
Objective: - Implementation of Travelling Salesman Problem.
Algorithm: -
C ({1}, 1) = 0
for s = 2 to n do
for all subsets S Є {1, 2, 3, …, n} of size s and containing 1
C (S, 1) = ∞
for all j Є S and j ≠ 1
C (S, j) = min {C (S – {j}, i) + d(i, j) for i Є S and i ≠ j}
Return minj C ({1, 2, 3, …, n}, j) + d(j, i)

CODE: -
#include <stdio.h>
int matrix [25][25], visited_cities [10], limit, cost = 0;
int tsp (int c) {
int count, nearest_city = 999;
int minimum = 999, temp;
for (count = 0; count < limit; count++) {
if((matrix[c][count] != 0) && (visited_cities[count] == 0)) {
if(matrix[c][count] < minimum) {
minimum = matrix[count][0] + matrix[c][count];
}
temp = matrix[c][count];
nearest_city = count;
}
}
if (minimum != 999) {
cost = cost + temp;
}
return nearest_city;
}
void minimum_cost (int city) {
int nearest_city;
visited_cities[city] = 1;
printf ("%d ", city + 1);
nearest_city = tsp(city);
if (nearest_city == 999) {
nearest_city = 0;
printf ("%d", nearest_city + 1);
cost = cost + matrix[city][nearest_city];
return;
}
minimum_cost(nearest_city);
}
int main () {
int i, j;
printf ("Enter Total Number of Cities:\t");
scanf ("%d", &limit);
printf ("\nEnter Cost Matrix\n");
for (i = 0; i < limit; i++) {
printf ("\nEnter %d Elements in Row[%d]\n", limit, i + 1);
for (j = 0; j < limit; j++) {
scanf ("%d", &matrix[i][j]);
}
visited_cities[i] = 0;
}
printf ("\nEntered Cost Matrix\n");
for (i = 0; i < limit; i++) {
printf("\n");
for (j = 0; j < limit; j++)
{
printf ("%d ", matrix[i][j]);
}
}
printf ("\n\nPath: \t");
minimum_cost (0);
printf ("\n\nMinimum Cost: \t");
printf ("%d\n", cost);
return 0;
}

OUTPUT: -

You might also like