You are on page 1of 49

ANALYSIS AND DESIGN OF ALGORITHM

LAB MANUAL

Department of Computer Science & Engineering


BHAGWAN MAHAVIR COLLEGE OF ENGINEERING AND TECHNOLOGY

Prepared By: Dhruv Gandhi


Enrollment number: 180064131001
Guide: Ms. Twinkle Ankleshwaria, (Hod, CE department.)
Subject code: 3150703
Year/sem.: 3rd/ 5th
ANALYSIS AND DESIGN OF ALGORITHMS LAB

ANALYSIS AND DESIGN OF ALGORITHMS LAB SYLLABUS

(Practical Hours: 02, Credits: 05)

Exp.No Division of Page Mark


List of Experiments date sign
. Experiments No. s

Implementation and Time analysis of sorting


1 Analysis of Algorithm 1    
algorithms.

And Divide and Bubble sort, Selection sort, Insertion sort,


  1    
Conquer Algorithm Merge sort and Quick Sort.

Divide and Conquer Implementation and Time analysis of linear


2 27    
Algorithm and binary search algorithm.

3 Analysis of Algorithm Implementation of max-heap sort algorithm. 36    

Implementation and Time analysis of factorial


4 Analysis of Algorithm 44    
program using iterative and recursive method.

Dynamic Implementation of a knapsack problem using


5    
Programming dynamic programming.
Dynamic Implementation of chain matrix multiplication
6    
Programming using dynamic programming.
Dynamic Implementation of making a change
7    
Programming problem using dynamic programming
Implementation of a knapsack problem using
8 Greedy Algorithm    
greedy algorithm.
Implementation of Graph and Searching (DFS
9 Exploring Graphs    
and BFS).

10 Greedy algorithm Implement prim’s algorithm.    

11 Greedy algorithm Implement kruskal’s algorithm.    

Dynamic
12 Implement LCS problem.    
Programming
1|Page

 PRACTICAL 1 :
 AIM: - Implementation and Time analysis of
sorting algorithms. Bubble sort,
Selection sort, Insertion sort, Merge sort and
Quicksort

[i] BUBBLE SORT-


Bubble sort is the simplest kind of the
sorting method. The time complexity of
bubble sort is…
 Best case: When the list is already
sorted (best-case), the complexity of
bubble sort is only O(n).
 
 Average case: O(n^2)

 Worst case: O(n^2) ( Worst case occurs


when array is reverse sorted.)

180063131001
2|Page

Algorithm(pseudo code) :-

Procedure bubble_Sort(A : list of sortable items)


{
n := length(A)
Repeat
Swapped: = false
for i := 1 to n-1 inclusive do
{
If A[i-1] > A[i] then
{
Swap (A[i-1], A[i])
Swapped: = true
} end if
} end for
Until not swapped
} end procedure

180063131001
3|Page

Program : =
#include<stdio.h>
#include<conio.h>
void bubble(int a[10],int n);
void main()
{
int n,i;
int a[10];
clrscr();
printf("enter the value of elements: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("the array element is..");
scanf("%d",&a[i]);
}
bubble(a,n);
getch();
}
void bubble(int a[10],int n)
{
int i,j,temp;
for(i=0;i<n-1;i++)
{
for(j=0;j<i;j++)
{
if(a[j]>a[j+1])
180063131001
4|Page

{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
printf("the sorted array is....");
for(i=0;i<n;i++)
{
printf("\n");
printf("%d",a[i]);
}
}

Output:

[ii] selection sort :-


180063131001
5|Page

 In selection sort, the smallest value


among the unsorted elements of the
array is selected in every pass and
inserted to its appropriate position into
the array.
 First, find the smallest element of the
array and place it on the first position.
Then, find the second smallest
element of the array and place it on
the second position. The process
continues until we get the sorted
array.
 The array with n elements is sorted by
using n-1 pass of selection sort
algorithm.
 In 1st pass, smallest element of the
array is to be found along with its
index pos. then, swap A[0] and
A[pos]. Thus A[0] is sorted, we now
have n -1 elements which are to be
sorted.

180063131001
6|Page

 In 2nd pas, position pos of the


smallest element present in the sub-
array A[n-1] is found. Then, swap,
A[1] and A[pos]. Thus A[0] and A[1]
are sorted, we now left with n-2
unsorted elements.
 In n-1th pass, position pos of the
smaller element between A[n-1] and
A[n-2] is to be found. Then, swap,
A[pos] and A[n-1].
 Therefore, by following the above
explained process, the elements A[0],
A[1], A[2],...., A[n-1] are sorted.

 Time analysis :-
Best case = O(n^2)
Avg case = O(n^2)
Worst cae = O(n^2)

 Algorithm (pseudo code) :-


1. Step 1 − Set min to the first location.

180063131001
7|Page

2. Step 2 − Search the minimum element in the


array.
3. Step 3 – swap the first location with the
minimum value in the array.
4. Step 4 – assign the second element as min.
5. Step 5 − Repeat the process until we get
a sorted array.

 Program :-

#include <stdio.h>
int main()
{
int array[100], n, c, d, position, t;

printf("Enter number of elements\n");


scanf("%d", &n);

printf("Enter %d integers\n", n);

for (c = 0; c < n; c++)


scanf("%d", &array[c]);

180063131001
8|Page

for (c = 0; c < (n - 1); c++) // finding minimum


element (n-1) times
{
position = c;

for (d = c + 1; d < n; d++)


{
if (array[position] > array[d])
position = d;
}
if (position != c)
{
t = array[c];
array[c] = array[position];
array[position] = t;
}
}

printf("Sorted list in ascending order:\n");

for (c = 0; c < n; c++)


printf("%d\n", array[c]);

return 0;

180063131001
9|Page

 out put:-

180063131001
10 | P a g e

[iii] Insertion sort:-

In this method the elements are inserted at their


appropriate place. Hence is the name insertion
sort.

Insertion sort is a sorting algorithm that builds a


final sorted array (sometimes called a list) one
element at a time.

 Time analysis:-

Best case: O(n)


Avg case: O(n^2)
Worst case: O(n^2)
Space analysis: O(n)

 Algorithm:
i←1
while i < length(A)
180063131001
11 | P a g e

j←i
while j > 0 and A[j-1] > A[j]
swap A[j] and A[j-1]
j←j-1
end while
i←i+1
end while

 program:-

#include<stdio.h>
#include<conio.h>
void insertion(int a[10],int n)
{
int i,j,temp;
for(i=0;i<n;i++)
{
temp = a[i];
j = i-1;
while((j>=0)&&(a[j]>temp))

180063131001
12 | P a g e

{
a[j+1]=a[j];
j=j-1;
}
a[j+1]=temp;
}
printf("\n the sorted array is...");
for(i=0;i<n;i++)
{
printf("\n%d",a[i]);
}
}
void main()
{
int a[10],n,i;
clrscr();
printf("enter the value of n: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{

180063131001
13 | P a g e

scanf("%d",&a[i]);
}
insertion(a,n);
printf("\n successfull!!");
getch();
}

 Output:-

180063131001
14 | P a g e

[iv] Quick sort:-

Theory:-
Quick sort is a highly efficient sorting algorithm
and is based on partitioning of array of data into
smaller arrays. A large array is partitioned into
two arrays one of which holds values smaller
than the specified value, say pivot, based on
which the partition is made and another array
holds values greater than the pivot value.

Quicksort partitions an array and then calls itself


recursively twice to sort the two resulting sub
arrays. This algorithm is quite efficient for large-
sized data sets

Time complexity:-
Best case:- O(N)
Avg. case:- O(NlogN)
Worst case:- O(N)

180063131001
15 | P a g e

Algorithm:-
quicksort(A, lo, hi)
if lo < hi then
p := partition(A, lo, hi)
quicksort(A, lo, p)
quicksort(A, p + 1, hi)

algorithm partition(A, lo, hi) is


pivot := A[⌊(hi + lo) / 2⌋]
i := lo - 1
j := hi + 1
loop forever
do
i := i + 1
while A[i] < pivot
do
j := j - 1
while A[j] > pivot
if i ≥ j then
return j
swap A[i] with A[j]
180063131001
16 | P a g e

Program:-
#include<stdio.h>
#include<conio.h>
void swap(int* a, int* b)
{
int t = *a;
*a = *b;
*b = t;
}
int partition (int arr[], int low, int high)
{
int pivot = arr[high]; // pivot
int i = (low - 1); // Index of smaller element

for (int j = low; j <= high- 1; j++)


{
if (arr[j] < pivot)
{
i++;

180063131001
17 | P a g e

swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}
arr[] --> Array to be sorted,
low --> Starting index,
high --> Ending index */
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);
}
}
void printArray(int arr[], int size)
{

180063131001
18 | P a g e

int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}
int main()
{
int arr[],m,n,i;
printf(“enter the size of array that is to be
sorted: “);
scanf(“%d”,&m);
printf(“enter the elements of the array one by
one”);
for(i=0;i<m;i++)
{
Scanf(“%d”,&a[i]);
}
quickSort(arr, 0, n-1);
printf("Sorted array: \n");
printArray(arr, n);

180063131001
19 | P a g e

return 0;

180063131001
20 | P a g e

[v] Merge sort:-

Like QuickSort, Merge Sort is a Divide and


Conquer algorithm. It divides input array in two
halves, calls itself for the two halves and then
merges the two sorted halves. The merge()
function is used for merging two halves. The
merge(arr, l, m, r) is key process that assumes
that arr[l..m] and arr[m+1..r] are sorted and
merges the two sorted sub-arrays into one.

Time analysis:-
Best case:- O(NlogN)
Avg. case:- O(NlogN)
Worst case:- O(NlogN)

180063131001
21 | P a g e

Algorithm:-
MergeSort(arr[], l, r)
If r > l
1. Find the middle index of the array to
divide it in two halves:
m = (l+r)/2
2. Call MergeSort for first half:
mergeSort(array, l, m)
3. Call mergeSort for second half:
mergeSort(array, m+1, r)
4. Recursively, merge the two halves in a
sorted manner, so that only one sorted array
is left:
merge(array, l, m, r)

180063131001
22 | P a g e

Program:-

#include<stdio.h>
#include<conio.h>
void merge(int a[10], int low,int high)
{
int mid, a[10];
void combine(int a[10], int low, int mid, int
high);
if(low<high)
{
mid = (low+high)/2;
merge(a,low,mid);
merge(a,mid+1,high);
combine(a,low,mid,high);
}
}
void combine(int a[10], int low, int mid, int high)
{
int i,j,k;
180063131001
23 | P a g e

int temp[10];
k=low;
i=high;
j=mid+1;
while(i<=mid&&j<=high)
{
if(a[i]<=a[j])
{
temp[k]=a[i];
i++;
k++;
}
else
{
temp[k]=a[j];
j++;
k++;
}
}
while(i<mid)

180063131001
24 | P a g e

{
temp[k]=a[i];
i++;
k++;
}
while(j<=high)
{
temp[k]=a[j];
j++;
k++;
}
for(k=low;k<=high;k++)
{
a[k]=temp[k];
}
}
void main()
{
int a[10],i,n;
printf("enter the element you want to sort: ");

180063131001
25 | P a g e

scanf("%d",&n);
printf("the array elements are...");
for(i=0;i<n;i++)
{
printf("\n");
scanf("%d",&a[i]);
}
merge(a,low,high);
for(i=0;i<n;i++)
{
printf("%d",a[i]);
}
getch();
}

180063131001
26 | P a g e

Maximu
Notes Description Marks Evaluation m Actual

Marks Marks
0 1 2
A Laboratory Attendance Absent Late Present 2

B Execution & involvement in Poor Medium Good 2


performance of experiment
C General attitude & behavior Misbehavior Average Good 2
in laboratory
D Immediate Outcome in form Poor Good Excellent 2
of Question & Answer
E Journal write up completion - Late On time 2
on time or not
Total 10

 Signature

180063131001
27 | P a g e

 PRACTICAL 2 :
 Aim: Implementation and Time analysis of linear and
binary search algorithm.

[1] linear search:-

It is also called sequential search. In this tech.


each record is visited sequentially form the
beginning of the list and compare with the key
element.
In this tech. unnecessary comparisons are
perform. This method does not used for large
series of element.
Time complexity:- O(N)
It is a special case of brute-force search.

Algorithm:-
Linear Search ( Array A, Value x)
Step 1: Set i to 1
180063131001
28 | P a g e

Step 2: if i > n then go to step 7


Step 3: if A[i] = x then go to step 6
Step 4: Set i to i + 1
Step 5: Go to Step 2
Step 6: Print Element x Found at index i and go
to step 8
Step 7: Print element not found
Step 8: Exit

Program:-

#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,a[10],key,x;
printf("enter the number the of element in
array: ");
scanf("%d",&n);
printf("enter bumber");

180063131001
29 | P a g e

for(i=0;i<n;i++)
{
prntf("\n");
scanf("%d",&a[i]);
}
printf("enter the number to search: ");
scanf("%d",&key");
for(i=0;i<n;i++)
{
if(a[i]=key)
{
printf("number is prsent in array");
x=a[i];
printf("%d",x);
}
else
{
i=i+1;
}

180063131001
30 | P a g e

}
getch();

[2] Binary search:-


Theory:-
Binary search algorithm can be applied on a
sorted array to search an element. Search
begins with comparing middle element of array
to target element. If both are equal then position
of element is returned. If target element is less
than middle element of array then upper half of
array is discarded and again search continued
by dividing the lower half. If target element is
greater than middle element then lower half is
discarded and search is continued in upper half.
180063131001
31 | P a g e

Time complexity:-

Best-case performance:- O(1)


Average performance:- O(log n)
Worst-case performance:- O(log n)

Algorithm:-

Binarysearch(a[0…n-1],key)
Low=0;
High=n-1;
While(low<high) do
{
M=(low+high)/2;
If(key=a[m]) then
Return m
Else if(key<a[m]) then
High = m-1
Else
Low=m+1

180063131001
32 | P a g e

}
Return -1

Program:-

#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],key,i,flag,low,high,n;
int binarysearch(int a[10],int key,int low,int
high);
clrscr();
printf("enter the number of elements: ");
scanf("%d",&n);
printf("enter the elements");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}

180063131001
33 | P a g e

printf("enter the element is to be search: ");


scanf("%d",&key);
low=0;
high =n-1;
flag=binarysearch(a,key,low,high);
printf("\n the elementis at a[%d] location"
,flag);
getch();
}
int binarysearch(int a[10], int key, int low, int
high)
{
int mid;
mid=(low+high)/2;
if(key==a[mid])
{
return mid;
}
else if(key<a[mid])
{

180063131001
34 | P a g e

binarysearch(a,key,low,mid-1);
}
else
{
binarysearch(a,key,mid+1,high);
}
return 0;
}

Maximu
Notes Description Marks Evaluation m Actual

180063131001
35 | P a g e

Marks Marks
0 1 2
A Laboratory Attendance Absent Late Present 2

B Execution & involvement in Poor Medium Good 2


performance of experiment
C General attitude & behavior Misbehavior Average Good 2
in laboratory
D Immediate Outcome in form Poor Good Excellent 2
of Question & Answer
E Journal write up completion - Late On time 2
on time or not
Total 10

 PRACTICAL 3:
180063131001
36 | P a g e

AIM: Implementation of max-heap sort


algorithm.

Theory:-
• Heap sort is the sorting method discovered
by J.W.J. Williams.
• It is one type of complete binary tree.
• It satisfy all the properties of the complete
binary tree.
• The main purpose behind the creation of the
heap sort is to reduce the time complexity
up to O(logn) from Θ(n )2

• There are two types of heap tree


1] min heap
2] max heap

 Heap properties:
• There are two kind of binary heaps: max‐
heaps and min‐heaps.

180063131001
37 | P a g e

• In a max‐heap, the max‐heap property is


that for every node i other than the root,
A[PARENT(i) ] ≥ A[i]
• the largest element in a max‐heap is
stored at the root.
• the subtree rooted at a node contains
values smaller than that contained at the
node itself.
• In a min‐heap, the min‐heap property is
that for every node i other than the root,
A[PARENT(i) ] ≤ A[i]
• the smallest element in a min‐heap is at
the root.
• the subtree rooted at a node contains
values no smaller than that contained at
the node itself.
Algorithm:-
ALGORITHM Parent (A, i)
return ⌊ i/2⌋

ALGORITHM Left (A, i)

180063131001
38 | P a g e

if 2 ∗ i ≤ heap-size[A]
return 2 ∗ i
else return NULL

ALGORITHM Right (A, i)


if 2 ∗ i + 1 ≤ heap-size[A]
return 2 ∗ i + 1

else return NULL

ALGORITHM Max-Heapify (A, i)


l ← Le (i)

r ← Right(i)
if l ≤ heap-size[A] and A[l] > A[i]
largest ← l
else largest ← i
if r ≤ heap-size[A] and A[r] < A[largest]
largest ← r
if largest 6= i

180063131001
39 | P a g e

exchange A[i] and A[largest]


Max-Heapify(A, largest)

ALGORITHM Build-Max-Heap (A)


heap-size[A] ← length[A]
for i ← ⌊ length[A]/2⌋ downto 1

Max-Heapify(A, i)

ALGORITHM Heap-Sort (A)


Build-Max-Heap(A)

for i = length[A] downto 2


exchange A[1] and A[i]
heap-size[A] ← heap-size[A] − 1
Max-Heapify(A, 1)

Program:-

180063131001
40 | P a g e

#include <stdio.h>
#include<conio.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) {

180063131001
41 | P a g e

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]);

180063131001
42 | P a g e

printf("\n");
}

void main()
{
int arr[10],n,i;
clrscr();
printf("enter the number of elements:");
scanf("%d",&n);
printf("enter the elements to sort:");
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
heapSort(arr, n);

printf("Sorted array is \n");


printArray(arr, n);
getch(); }
OUTPUT:

180063131001
43 | P a g e

Maximu
Notes Description Marks Evaluation m Actual

Marks Marks
0 1 2
A Laboratory Attendance Absent Late Present 2

B Execution & involvement in Poor Medium Good 2


performance of experiment
C General attitude & behavior Misbehavior Average Good 2
in laboratory
D Immediate Outcome in form Poor Good Excellent 2
of Question & Answer
E Journal write up completion - Late On time 2
on time or not
Total 10

180063131001
44 | P a g e

 PRACTICAL 4:

AIM: Implementation and Time analysis of


factorial program using iterative and recursive
method.

THEORY
Compute the factorial function F(n) = n! for an
arbitrary nonnegative integer n.
Since

n!= 1 . . . . . (n − 1) . n = (n − 1)! . n for n ≥ 1


and 0!= 1
By definition, we can compute F(n) = F(n − 1) . n
with the following recursive algorithm.

Algorithm:-
ALGORITHM factorial_iterative (n)
ans ← 1
if n=0 return 1
180063131001
45 | P a g e

else
for j←1 to n do
ans *= j
return ans

ALGORITHM Factorial_recursive(n)
if n = 0 return 1
else return Factorial_recursive (n − 1) * n

time analysis:-
C (n) = O (n!)

Program :-
#include <stdio.h>

int factorial(int n)
{
int res = 1, i;
for (i = 2; i <= n; i++)
res *= i;

180063131001
46 | P a g e

return res;
}

void main()
{
int num;
clrscr();
printf("enter the number:");
scanf("%d",&num);
printf("Factorial of %d is %d", num,
factorial(num));
getch();
}

OUTPUT:

180063131001
47 | P a g e

Maximu
Notes Description Marks Evaluation m Actual

Marks Marks
0 1 2
A Laboratory Attendance Absent Late Present 2

B Execution & involvement in Poor Medium Good 2


performance of experiment
C General attitude & behavior Misbehavior Average Good 2
in laboratory
D Immediate Outcome in form Poor Good Excellent 2
of Question & Answer
E Journal write up completion - Late On time 2
on time or not
Total 10

180063131001

You might also like