Sublect Code: Kcs553: Design and Analysis of Algorithm Lab

Download as pdf or txt
Download as pdf or txt
You are on page 1of 22

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

DESIGN AND ANALYSIS OF ALGORITHM LAB


SUBLECT CODE: KCS553
SESSION 2022-2023

SUBMITTED BY: SUBMITTED TO:


ESHA GUPTA PEEYUSH KUMAR PATHAK
B-TECH (CSE)
III YEAR (5TH SEMESTER)
ROLL NUMBER-2003600100048
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
VISION AND MISSION OF DEPARTMENT

VISION:
To provide a congenial environment for learning in
discipline of Computer Science and Engineering, and to
mobilize students towards serving a globalized
technological society.

MISSION:
• To ensure that every engineering student is proficient
with necessary computer skills.
• To familiarize students with latest developments in
Computer Science and Information Technology and
motivate them to embrace all challenges and be future
ready.
• To inculcate strong ethical values, research capabilities,
professional behaviour and leadership abilities in your
character so as to work with a commitment to the
progress of the nation.

ESHA GUPTA
INDEX
SR PAGE
TOPIC DATE SIGNATURE
NO. NO

ESHA GUPTA
PRACTICAL 1

AIM- WRITE A PROGRAM FOR INSERTION SORT.


THEORY –
INSERTION SORT is an sorting algorithm in which first element in the array is assumed as
sorted, even if it is an unsorted . Then, each element in the array is checked with the
previous elements, resulting in a growing sorted output list. With each iteration, the sorting
algorithm removes one element at a time and finds the appropriate location within the sorted
array and inserts it there. The iteration continues until the whole list is sorted.
ALGORITHM-
1. for j = 2 to A.length
2. key = A[j]
3. // Insert A[j] into the sorted sequence A[1.. j - 1] 4. i = j - 1
5. while i > 0 and A[i] > key
6. A[i + 1] = A[i]
7. ii = i -1
8. A[i + 1] = key

EXAMPLE:

[ 13, 12, 14, 5, 6 ]

Let 's loop for i = 1 to 4

i = 1. as 12 is smaller than 13, move 13 and insert 12 before 13


[12, 13, 14, 5, 6 ]

i = 2. 14 will remain at same location as all elements in A[0..I-1] are smaller than 14
[12, 13, 14, 5, 6]

i = 3. 5 will move at beginning and other elements from 12 to 14 will move one position to
front from their current location.
[5, 12, 13, 14, 6]

i = 4. 6 will move to position after 5, and elements from 11 to 13 will move one position to
front of their current position.

[5, 6, 12, 13, 14]

PROGRAM –

#include <stdio.h>
int main()
int n, i, j, temp;
int arr[64] {
ESHA GUPTA
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
for (i = 1 ; i <= n - 1; i++)
{
j = i;
while ( j > 0 && arr[j-1] > arr[j])
{
temp = arr[j];
arr[j] = arr[j-1];
arr[j-1] = temp;
j--;
}
}
printf("Sorted list in ascending order:\n");
for (i = 0; i <= n - 1; i++)
{
printf("%d\n", arr[i]);
}
return 0;}

OUTPUT:

COMPLEXITY-

• BEST CASE- O(N)


• AVERAGE CASE – O(N2)
• WORST CASE -O(N2)

ESHA GUPTA
PRACTICAL 2
AIM- WRITE A PROGRAM FOR MERGE SORT.
THEORY –
MERGE SORT is a sorting algorithm that follows divide and conquer approach.
ALGORITHM-

ALGORITHM-MERGE SORT (A,p,r)


1. If p<r
2. Then q → ( p+ r)/2
3. MERGE-SORT (A, p, q)
4. MERGE-SORT ( A, q+1,r)
5. MERGE ( A, p, q, r)

FUNCTIONS: MERGE (A, p, q, r)


1. n 1 = q-p+1
2. n 2= r-q
3. create arrays [1.....n 1 + 1] and R [ 1.....n 2 +1 ]
4. for i ← 1 to n 1
5. do [i] ← A [ p+ i-1]
6. for j ← 1 to n2
7. do R[j] ← A[ q + j]
8. L [n 1+ 1] ← ∞
9. R[n 2+ 1] ← ∞
10. I ← 1
11. J ← 1
12. For k ← p to r
13. Do if L [i] ≤ R[j]
14. then A[k] ← L[ i]
15. i ← i +1
16. else A[k] ← R[j]
17. j ← j+1

ESHA GUPTA
EXAMPLE-

ESHA GUPTA
PROGRAM –

#include <stdio.h>

#define max 10

int a[11] = { 10, 14, 19, 26, 27, 31, 33, 35, 42, 44, 0 };
int b[10];

void merging(int low, int mid, int high) {


int l1, l2, i;

for(l1 = low, l2 = mid + 1, i = low; l1 <= mid && l2 <= high; i++) {
if(a[l1] <= a[l2])
b[i] = a[l1++];
else
b[i] = a[l2++];
}

while(l1 <= mid)


b[i++] = a[l1++];

while(l2 <= high)


b[i++] = a[l2++];

for(i = low; i<= high; i++)


a[i] = b[i];
}

void sort(int low, int high) {


int mid;

if(low < high) {


mid = (low + high) / 2;
sort(low, mid);
sort(mid+1, high);
merging(low, mid, high);
} else {
return;
}
}

int main() {
int i;

printf("List before sorting\n");

ESHA GUPTA
for(i = 0; i<= max; i++)
printf("%d ", a[i]);

sort(0, max);

printf("\nList after sorting\n");

for(i = 0; i<= max; i++)


printf("%d ", a[i]);
}

OUTPUT-

COMPLEXITY-

• BEST CASE- O(N logN)


• AVERAGE CASE – O(N logN)
• WORST CASE - O(N logN)

ESHA GUPTA
PRACTICAL 3
AIM- WRITE A PROGRAM FOR QUICK SORT.
THEORY –
QUICKSORT is a sorting algorithm that uses divide-and-conquer algorithm. It works by
selecting a "key" element or can say "pivot" element from the array and partitioning the other
elements into two sub-arrays, according to whether they are less than or greater than the
pivot. The sub-arrays are then sorted recursively
ALGORITHM-
PARTITION (ARR, BEG, END, LOC)

1. [INITIALIZE] SET LEFT = BEG, RIGHT = END, LOC = BEG, FLAG =0


2. Repeat Steps 3 to 6 while FLAG =0
3. Repeat while ARR[LOC] <=ARR[RIGHT]
AND LOC != RIGHT
SET RIGHT = RIGHT - 1
[END OF LOOP]
4. IF LOC = RIGHT
SET FLAG = 1
ELSE IF ARR[LOC] > ARR[RIGHT]
SWAP ARR[LOC] with ARR[RIGHT]
SET LOC = RIGHT
[END OF IF]
5. IF FLAG = 0
Repeat while ARR[LOC] >= ARR[LEFT] AND LOC != LEFT
SET LEFT = LEFT + 1
[END OF LOOP]
6. IF LOC = LEFT
SET FLAG = 1
ELSE IF ARR[LOC] < ARR[LEFT]
SWAP ARR[LOC] with ARR[LEFT]
SET LOC = LEFT
[END OF IF]
[END OF IF]
7. [END OF LOOP]
8. END

QUICK_SORT (ARR, BEG, END)

1. IF (BEG < END)


CALL PARTITION (ARR, BEG, END, LOC)
CALL QUICKSORT(ARR, BEG, LOC - 1)
CALL QUICKSORT(ARR, LOC + 1, END)
[END OF IF]
2. END

ESHA GUPTA
EXAMPLE-

A = [20, 90, 40, 100, 50, 60, 80]

low = 0, high = 6, pivot = A[h] = 80

let index of smaller element, i = -1

Traverse from j = low to high-1

j = 0 : A[j] <= pivot, increase i and swap(A[i], A[j])

i=0

A[] = {20, 90, 40, 100, 50, 60, 80} #No change as i and j are same

j = 1 : A[j] > pivot,do nothing #No change in i and A[]

j = 2 : A[j] <= pivot, do i++ and swap(A[i], A[j])

i=1

A[] = {20, 40, 90, 100, 50, 60, 80} #We swap 80 and 30

j = 3 : A[j] > pivot, do nothing #No change in i and A[]

j = 4 : Since A[j] <= pivot, do i++ and swap(A[i],A[j])

i=2

A[] = {20, 40, 50, 100, 90, 60, 80} #90 and 50 Swapped

j = 5 : Since A[j] <= pivot, do i++ and swap A[i] with A[j]

i=3

A[] = {20, 40, 50, 60, 90, 100, 80} #100 and 60 Swapped

Now , because j == equal to high-1 we need to move out of loop.

Finally we place pivot at correct position by swapping

A[i+1] and A[high] (or pivot)

A[] = {20, 40, 50, 60, 80, 100, 90} #90 and 80 Swapped

Now 80 is at its correct place. All elements smaller than

80 are before it and all elements greater than 80 are after

it.

ESHA GUPTA
PROGRAM –

#include <stdio.h>

int partition(int a[], int beg, int end);

void quickSort(int a[], int beg, int end);

void main()

clrscr();

int i;

int arr[10]={90,23,101,45,65,23,67,89,34,23};

quickSort(arr, 0, 9);

printf("The sorted array is:");

for(i=0;i<10;i++)

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

getch();

int partition(int a[], int beg, int end)

int left, right, temp, loc, flag;

loc = left = beg;

right = end;

flag = 0;

while(flag != 1)

while((a[loc] <= a[right]) && (loc!=right))

right--;

if(loc==right)

flag =1;

ESHA GUPTA
else if(a[loc]>a[right])

temp = a[loc];

a[loc] = a[right];

a[right] = temp

loc = right;

if(flag!=1)

while((a[loc] >= a[left]) && (loc!=left))

left++;

if(loc==left)

flag =1;

else if(a[loc] <a[left])

temp = a[loc];

a[loc] = a[left];

a[left] = temp;

loc = left;

return loc;

void quickSort(int a[], int beg, int end)

int loc;

ESHA GUPTA
if(beg<end)

loc = partition(a, beg, end);

quickSort(a, beg, loc-1);

quickSort(a, loc+1, end);

OUTPUT-

COMPLEXITY-

• BEST CASE- O(N logN)


• AVERAGE CASE – O(N logN)
• WORST CASE - O(N2)

ESHA GUPTA
PRACTICAL 4
AIM- WRITE A PROGRAM FOR HEAP SORT.
THEORY –
HEAP SORT processes the elements by creating the min heap or max heap using the
elements of the given array. Min heap or max heap represents the ordering of the array in
which root element represents the minimum or maximum element of the array. At each step,
the root element of the heap gets deleted and stored into the sorted array and the heap will
again be heapified.
ALGORITHM-
MAX-HEAPIFY (A, i)
1. l ← left [i]
2. r ← right [i]
3. if l≤ heap-size [A] and A[l] > A [i]
4. then largest ← l
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. MAX-HEAPIFY (A, largest)

BUILDHEAP (array A, int n)


1 for i ← n/2 down to 1
2 do
3 HEAPIFY (A, i, n)

HEAP-SORT (A)
1. BUILD-MAX-HEAP (A)
2. For I ← length[A] down to Z
3. Do exchange A [1] ←→ A [i]
4. Heap-size [A] ← heap-size [A]-1
5. MAX-HEAPIFY (A,1)

ESHA GUPTA
EXAMPLE:
A: 40, 100, 30, 50, 10

40(0)

/ \

100(1) 30(2)

/ \

5(30) 10(4)

The numbers in bracket represent indexes to the elements .

if we Apply heap procedure to index 1:

40(0)

/ \

100(1) 30(2)

/ \

50(3) 10(4)

If we Apply heap procedure to 0 index:

100(0)

/ \

50(1) 30(2)

/ \

40(3) 10(4)

heap procedure calls itself recursively to build heap

in top down manner

PROGRAM –

#include<stdio.h>

#include<conio.h>

int temp;

ESHA GUPTA
void heapify(int arr[], int size, int i)

int largest = i;

int left = 2*i + 1;

int right = 2*i + 2;

if (left < size && arr[left] >arr[largest])

largest = left;

if (right < size && arr[right] > arr[largest])

largest = right;

if (largest != i)

temp = arr[i];

arr[i]= arr[largest];

arr[largest] = temp;

heapify(arr, size, largest);

void heapSort(int arr[], int size)

int i;

for (i = size / 2 - 1; i >= 0; i--)

heapify(arr, size, i);

for (i=size-1; i>=0; i--)

temp = arr[0];

arr[0]= arr[i];

arr[i] = temp;

ESHA GUPTA
heapify(arr, i, 0); } }

void main()

{ clrscr();

int arr[] = {10,14,19,26,27,31,33,35,42,44,0};

int i;

printf(“List before sort:”)

for (i=0; i<size; ++i)

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

int i;

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

heapSort(arr, size);

printf("\nList after sorting:");

for (i=0; i<size; ++i)

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

getch(); }

OUTPUT-

COMPLEXITY-

• BEST CASE- O(N logN)


• AVERAGE CASE – O(N logN)
• WORST CASE - O(N logN)

ESHA GUPTA
PRACTICAL 5
AIM- WRITE A PROGRAM FOR COUNTING SORT.
THEORY –
COUNTING SORT is a linear time sorting algorithm which works faster by not making a
comparison. It assumes that the number to be sorted is in range 1 to k where k is small.Basic
idea is to determine the "rank" of each number in the final sorted array.Counting Sort uses
three arrays:
1. A [1, n] holds initial input.
2. B [1, n] holds sorted output.
3. C [1, k] is the array of integer. C [x] is the rank of x in A where x ∈ [1, k]

Firstly C [x] to be a number of elements of A [j] that is equal to x

o Initialize C to zero
o For each j from 1 to n increment C [A[j]] by 1

We set B[C [x]] =A[j]. If there are duplicates, we decrement C [i] after copying.

ALGORITHM-

Counting Sort (array P, array Q, int k)


1. For i ← 1 to k
2. do C [i] ← 0 [ θ(k) times]
3. for j ← 1 to length [A]
4. do C[A[j]] ← C [A [j]]+1 [θ(n) times]
5. // C [i] now contain the number of elements equal to i
6. for i ← 2 to k
7. do C [i] ← C [i] + C[i-1] [θ(k) times]
8. //C[i] now contain the number of elements ≤ i
9. for j ← length [A] down to 1 [θ(n) times]
10. do B[C[A[j] ← A [j]
11. C[A[j] ← C[A[j]-1

ESHA GUPTA
EXAMPLE:
Let us trace the above algorithm using an example:Consider the following input array
A to be sorted. All the elements are in range 0 to 9

A[]= {1, 3, 2, 8, 5, 1, 5, 1, 2, 7}

Copy
Step 1: Initialize an auxiliary array, say count and store the frequency of every
distinct element. Size of count is 10 (k+1, such that range of elements in A is 0 to k)

Figure 1: count array

Step 2: Using the formula, updated count array is -

Figure 2: Formula for updating count array

Figure 3 : Updated count array

Step 3: Add elements of array A to resultant array B using the following steps:

• For, i=0, t=1, count[1]=3, v=2. After adding 1 to B[2], count[1]=2 and i=1

Figure 4: For i=0

• For i=1, t=3, count[3]=6, v=5. After adding 3 to B[5], count[3]=5 and i=2

Figure 5: For i=1

• For i=2, t=2, count[2]= 5, v=4. After adding 2 to B[4], count[2]=4 and i=3

Figure 6: For i=2

ESHA GUPTA
• For i=3, t=8, count[8]= 10, v=9. After adding 8 to B[9], count[8]=9 and i=4

Figure 7: For i=3

• On similar lines, we have the following:

Figure 8: For i=4

Figure 9: For i=5

Figure 10: For i=6

Figure 11: For i=7

Figure 12: For i=8

Figure 13: For i=9

ESHA GUPTA
Thus, array B has the sorted list of elements.

PROGRAM –

#include <stdio.h> /* Counting sort function */


int counting_sort(int a[], int k, int n)
{ int i, j;
int b[15], c[100];
for (i = 0; i <= k; i++)
c[i] = 0;
for (j = 1; j <= n; j++)
c[a[j]] = c[a[j]] + 1;
for (i = 1; i <= k; i++)
c[i] = c[i] + c[i-1];
for (j = n; j >= 1; j--)
{
b[c[a[j]]] = a[j];
c[a[j]] = c[a[j]] - 1;
}
printf("The Sorted array is : ");
for (i = 1; i <= n; i++)
printf("%d,", b[i]);
}
int main()
{ int n, k = 0, a[15], i;
printf("Input number of elements: ");
scanf("%d", &n);
printf("Input the array elements one by one: \n");
for (i = 1; i <= n; i++)
{
scanf("%d", &a[i]);
if (a[i] > k) {
k = a[i];
}}
counting_sort(a, k, n);
printf("\n");
return 0; }

OUTPUT-

COMPLEXITY-

• BEST CASE- O(N+k)


• AVERAGE CASE – O(N+k)
• WORST CASE - O(N+k)

ESHA GUPTA

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