ADA Practical File - Complete 1
ADA Practical File - Complete 1
PRACTICAL 1.1
AIM: Implementation and Time analysis of sorting algorithms: Bubble sort
INPUT
#include<stdio.h>
#include<math.h> //use rand() with warning
#include<stdlib.h> //use rand() without warning
#include<time.h> //calculate time using clock_t with clock() function
int main()
{
int n,temp;
clock_t start,end;
double time_diff;
for(int i=0;i<n;i++)
{
printf("\n%d number is: %d",i+1,a[i]=rand()%1000);
}
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 2 of 61
OUTPUT
Enter size of element:5
1 number is: 41
2 number is: 467
3 number is: 334
4 number is: 500
5 number is: 169
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 3 of 61
Algorithm Bubble_Sort(a[], n)
Problem description: Write an algorithm to sort number of elements in any order.
Input: n number store in array; Ex: 23, 92, 10, 5, 26
Output: sorted order of number n; Ex: 5, 10, 23, 26, 92 (Ascending order)
Step 1: Start
Step 2: Input n (number of elements)
Step 3: Initialize an integer array a of size n
Step 4: Generate n random integers between 0 and 999 and store them in array a;
For i 0 to n do i+1
a[i] rand()%100
Step 5: Record the start time
Start time Clock()
Step 6: Perform Bubble Sort to sort the array a
a) Compare adjacent elements and swap them if they are in the wrong order
For i 0 to n-1 do i+1
For j 0 to n-1-i do j+1
If a[j] is greater than a[j+1] then
Swap(a[j],a[j+1])
b) Repeat this process until the entire array is sorted
Step 7: Record the end time
End time Clock()
Step 8: Calculate the sorting time as (end time - start time) / CLOCKS_PER_SEC
Step 9: Print the sorted array
Step 10: Print the total time taken for sorting in seconds
Step 11: End
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 4 of 61
TIME ANALYSIS
The above algorithm can be analysed mathematically. We will use general plan for non-
recursive mathematical analysis.
Step 1: The input size is total number of elements in the list or array.
Step 2: In this algorithm the basic operation is key comparison.
If a[j] > a[j+1]
Step 3: We can obtain sum as follows:
C(n) = Outer for loop with variable i X Inner for loop with variable j X Basic operation
𝑛−2 ∑𝑛−2−𝑖
C(n) = ∑𝑖=0 𝑗=0 1
∑ 𝑛𝑖=1 1 = 𝑛 − 1 + 1 = 𝑛
= ∑𝑖=0
𝑛−2(𝑛 − 2 − 𝑖 − 0 + 1)
= ∑𝑖=0
𝑛−2(𝑛 − 1 − 𝑖)
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 5 of 61
PRACTICAL 1.2
int main()
{
int n,min,temp;
clock_t start,end;
double time_diff;
printf("Enter Size of array:");
scanf("%d",&n);
int arr[n];
for(int i=0;i<n;i++)
{
printf("\n%d number is:%d",i+1,arr[i]=rand()%100);
}
start=clock();
for(int i=0;i<n-1;i++)
{
min=i;
for(int j=i+1;j<n;j++)
{
if(arr[j]<arr[min])
{
min=j;
}
}
temp=arr[min];
arr[min]=arr[i];
arr[i]=temp;
}
end=clock();
time_diff=((double)(end-start)/CLOCKS_PER_SEC);
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 6 of 61
OUTPUT
Enter Size of array:5
1 number is:83
2 number is:86
3 number is:77
4 number is:15
5 number is:93
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 7 of 61
Algorithm Selection_Sort(a[], n)
Problem description: Write an algorithm to sort number of elements in any order.
Input: n number store in array; Ex: 23, 92, 10, 5, 26
Output: sorted order of number n; Ex: 5, 10, 23, 26, 92 (Ascending order)
Step 1: Start
Step 2: Input n (number of elements) & Declare integer variables min and temp
Step 3: Initialize an integer array a of size n
Step 4: Generate n random integers between 0 and 999 and store them in array a;
For i 0 to n do i+1
a[i] rand()%100
Step 5: Record the start time
Start time Clock()
Step 6: Perform Selection Sort to sort the array a;
For i 0 to n-1 do i+1
Set min equals to i
For j i+1 to n do j+1
If a[j] is lesser than a[min] then
Set min equals to j
Swap(a[min],a[i])
(Repeat this process until the entire array is sorted)
Step 7: Record the end time
End time Clock()
Step 8: Calculate the sorting time as (end time - start time) / CLOCKS_PER_SEC
Step 9: Print the sorted array
Step 10: Print the total time taken for sorting in seconds
Step 11: End
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 8 of 61
TIME ANALYSIS
The above algorithm can be analysed mathematically. We will apply a general plan for
non-recursive mathematical analysis.
Step 1: The input size is n i.e., total number of elements in the list or array.
Step 2: In this algorithm the basic operation is key comparison.
If a[j] < a[min]
Step 3: This basic operation depends only on array size n. hence we can find sum as:
C(n) = Outer for loop with variable i X Inner for loop with variable j X Basic operation
C(n) = ∑𝑛−2 ∑𝑛−1 1
𝑖=0 𝑗=𝑖+1
∑ 𝑛𝑖=1 1 = 𝑛 − 1 + 1 = 𝑛
= ∑𝑖=0
𝑛−2[(𝑛 − 1) − (𝑖 + 1) + 1]
= ∑𝑖=0
𝑛−2(𝑛 − 1 − 𝑖)
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 9 of 61
PRACTICAL 1.3
int main()
{
int n,key,j; //Before key element are sorted
clock_t start,end;
double time_diff;
for(int i=0;i<n;i++)
{
printf("\n%d number is:%d",i+1,arr[i]=rand()%100);
}
start=clock();
for(int i=1;i<n;i++)
{
key=arr[i];
j=i-1;
end=clock();
time_diff=((double)(end-start)/CLOCKS_PER_SEC);
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 10 of 61
OUTPUT
Enter Size of array:5
1 number is:41
2 number is:67
3 number is:34
4 number is:0
5 number is:69
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 11 of 61
Algorithm Insertion_Sort(a[], n)
Problem description: Write an algorithm to sort number of elements in any order.
Input: n number store in array; Ex: 23, 92, 10, 5, 26
Output: sorted order of number n; Ex: 5, 10, 23, 26, 92 (Ascending order)
Step 1: Start
Step 2: Input n (number of elements) & Declare integer variables key and j
Step 3: Initialize an integer array a of size n
Step 4: Generate n random integers between 0 and 999 and store them in array a;
For i 0 to n do i+1
a[i] rand()%100
Step 5: Record the start time
Start time Clock()
Step 6: Perform Bubble Sort to sort the array a;
For i 1 to n do i+1
Set key equals to a[i]
Set j equals to i-1
While j is greater than equals to 0 and a[j] is greater than key
Move arr[j] to arr[j + 1] (shift right)
Decrement j by 1
Place key at index j+1
(Repeat this process until the entire array is sorted)
Step 7: Record the end time
End time Clock()
Step 8: Calculate the sorting time as (end time - start time) / CLOCKS_PER_SEC
Step 9: Print the sorted array
Step 10: Print the total time taken for sorting in seconds
Step 11: End
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 12 of 61
TIME ANALYSIS
The above algorithm can be analysed mathematically. We will apply a general plan for
non-recursive mathematical analysis.
INSERTION_SORT(ARR) Cost Time
1 for(int i=1;i<n;i++) C1 n
2 key=arr[i]; C2 n-1
3 j=i-1; C3 n-1
4 while(j>=0 && arr[j]>key) C4 𝑛
∑ 𝑖
𝑖=1
𝑛
5 arr[j+1]=arr[j]; C5
∑ (𝑖 − 1)
𝑖=1
𝑛
6 j=j-1; C6
∑ (𝑖 − 1)
𝑖=1
7 arr[j+1]=key; C7 n-1
Best Case:
Occurs if the array is already sorted.
For each i=1 to n because index start with zero, arr[j] <= key in line 4 when j has its initial value of i-1
Thus i=0
T(n) = C1(n) + C2(n-1) + C3(n-1) + C4(n-1) + C7(n-1)
= (C1+C2+C3+C4+C7)n – (C2+C3+C4+C7)
an + C; take highest degree of polynomial equation
Thus, T(n) = (n)
Worst Case:
T(n) = C1(n) + C2(n-1) + C3(n-1) + C4(∑𝑛 𝑖) + C5(∑𝑛 (𝑖 − 1)) + C6(∑𝑛 (𝑖 − 1)) + C7(n-1)
𝑖=1 𝑖=1 𝑖=1
𝑛(𝑛+1)
∑ 𝑛𝑖=1 𝑖 =
2
∑ 𝑛𝑖=1 1 = 𝑛 − 1 + 1 = 𝑛
𝑛(𝑛+1) 𝑛(𝑛−1) 𝑛(𝑛−1)
= C1(n) + C2(n-1) + C3(n-1) + C4( ) + C5( ) + C6 ( ) + C7(n-1)
2
2+𝑛 2−𝑛2 2−𝑛 2
= C1 (n) + C2 (n-1) + C3 (n-1) + C (𝑛 ) + C (𝑛 ) + C (𝑛 ) + C (n-1)
4 5 6 7
𝐶4+𝐶5+𝐶6 2
𝐶4 𝐶5 𝐶6 2 2
=( )n2 + (C1+C2+C3+ - - )n – (C2+C3+C7)
2 2 2 2
an + bn + C; take highest degree of polynomial equation
2
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 13 of 61
PRACTICAL 1.4
AIM: Implementation and Time analysis of factorial program using iterative and recursive
method.
INPUT
#include <stdio.h>
#include <time.h>
void display(int a, double fact, double time);
double factorial1(int num);
double factorial2(int num);
int a;
int main()
{
int n, num;
double fact = 0;
clock_t start, end;
double time_diff;
printf("Enter factorial number:");
scanf("%d", &n);
a = n;
printf("1. Iterative Method\n2. Recursive Method");
printf("\nChoose method NO:");
scanf("%d", &num);
switch (num)
{
case 1:
// iterative
start = clock();
fact = factorial1(n);
end = clock();
time_diff = ((double)(end - start)) / CLOCKS_PER_SEC;
display(a, fact, time_diff);
break;
case 2:
// recursive
start = clock();
fact = factorial2(n);
end = clock();
time_diff = ((double)(end - start)) / CLOCKS_PER_SEC;
display(a, fact, time_diff);
break;
default:
printf(" ---- >>>>> Enter Valid Choice.");
}
return 0;
}
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 14 of 61
OR
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 15 of 61
Algorithm factorial(n)
Problem description: Write an algorithm to find factorial of given number.
Input: n number Ex: 5
Output: Factorial of number n Ex: 120 (Iterative and Recursive method)
Step 1: Start
Step 2: Input for number n (n for factorial)
Step 3: Display method choices:
1. Iterative Method
2. Recursive Method
Step 4: Take choice from user
Step 5: Record the start time
Start time Clock()
Step 6: Find factorial for user choice method case 1 or case 2.
Case 1:
If n equals to 0 then return 1
Otherwise
Initialize f equal 1
While n is greater 0 then
Ff*n
Decrement n by 1
Then return f
Case 2:
If n equals to 0 then return 1
Otherwise
Recursively call n*function(n-1) & return it self
Step 7: Record the end time
End time Clock()
Step 8: Calculate the sorting time as (end time - start time) / CLOCKS_PER_SEC
Step 9: Print factorial of given number
Step 10: End
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 16 of 61
TIME ANALYSIS
The above algorithm can be analysed mathematically. We will apply a general plan for
iterative and recursive mathematical analysis.
USING RECURSIVE METHOD:
Factorial(0) is only comparison 1 unit of time.
Factorial(n) is 1 comparison, 1 subtraction and time for factorial(n-1).
Factorial(n):
If n is 0
Return 1
Return n*factorial(n-1)
For the above analysis we can write recurrence equation as:
T(n)=T(n-1) + 3
…(1)
We solve above recurrence equation using master theorem is:
T(n)=a*(T(n-b)) + f(n)
…(2)
Compare equation 1 & 2;
a=1, b=1, f(n)=3
here; a=1 so, T(n) = (n*f(n)) ….applying case 1 in decreasing function
= (3n)
That gives a time complexity which is highest order of polynomial is n so time complexity of recursive
factorial method is (n).
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 17 of 61
Here brief analysis during execution time taken by specific method is:
()Method/Number(→) 10 15 20
ITERATIVE 0.000001 0.000001 0.000002
RECURSIVE 0.000001 0.000001 0.000002
Now we discuss the time complexity of factorial of number n using different method as follows:
Factorial of number n
Method Best Case Worst Case Average Case
Iterative (1) (n) (n/2)
Recursive (1) (n) (n/2)
Space complexity of the iterative method is (1), since it does not need to store any recursive calls on
the stack. The space complexity of the recursive method is (n), since it need to store n recursive calls
on the stack.
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 18 of 61
PRACTICAL 2.1
int main()
{
int n,key,index;
clock_t start,end;
double linear_time;
printf(" \n");
printf(" Linear Search (index start with 0)");
printf("\n ");
printf("\nEnter number of element:");
scanf("%d",&n);
int a[n];
for(int i=0;i<n;i++)
{
printf("%d ",a[i]=rand()%100);
}
start=clock();
index=linear_search(a,key,n);
end=clock();
if(index!=1)
{
printf("Key element %d is present in given array at index %d.",key,index);
}
else
{
printf("Key element %d is not found in given array",key);
}
linear_time=((double)(end-start))/CLOCKS_PER_SEC;
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 19 of 61
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 20 of 61
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 21 of 61
TIME ANALYSIS
1. Time Complexity
Case Time Complexity
Best Case (1)
Worst Case (n)
Average Case (n)
• Best Case Complexity: In Linear search, best case occurs when the element we are finding is at the
first position of the array. The best-case time complexity of linear search is (1).
• Average Case Complexity: The average case time complexity of linear search is (n)
• Worst Case Complexity: In Linear search, the worst case occurs when the element we are looking is
present at the end of the array. The worst-case in linear search could be when
the target element is not present in the given array, and we have to traverse
the entire array. The worst-case time complexity of linear search is (n).
The time complexity of linear search is (n)because every element in the array is compared only once.
2. Space Complexity
The space complexity of linear search is (1).
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 22 of 61
PRACTICAL 2.2
for(int i=0;i<n;i++){
printf("Enter %d element:",i+1);
scanf("%d",&a[i]);
}
printf("Enter key element:");
scanf("%d",&key);
status=check_sort_or_not(a,n);
if(status==1){
printf("<<<<<<<< ------------- >>>>>>>>\n");
printf("Array not in Ascending order.\n");
printf("<<<<<<<< ------------- >>>>>>>>");
}
else{
start=clock();
binary=binary_search(a,key,n); //Non-recursive method
end=clock();
binary_time=((double)(end-start))/CLOCKS_PER_SEC;
if(binary!=-1){
printf("Key element [%d] is found at position %d",key,binary);
printf("\nTime taken by algorithm:%lf",binary_time);
}
else{
printf("Key element [%d] not found.",key);
printf("\nTime taken by algorithm:%lf",binary_time);
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 23 of 61
}
}
return 0;
}
while(left<=right){
int mid;
mid=(left+right)/2;
if(key==a[mid]){
return mid;
}
else if(key < a[mid]){
right=mid-1;
}
else{
left=mid+1;
}
}
return -1;
}
OUTPUT
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 24 of 61
Step 1: Start
Step 2: Input n (number of elements)
Step 3: Initialize an integer array a of size n
Step 4: Initialize key
Step 5: For i from 0 to n-1, do Steps 6-7
Step 6: Input a[i]
Step 7: Continue the loop
Step 8: Input key
Step 9: Check whether the array a is in ascending order:
For i from 0 to n-2, do Steps 10-12
Step 10: If a[i] > a[i+1], go to Step 13
Step 11: Continue the loop
Step 12: Go to Step 14
Step 13: Print "Array not in Ascending order."
Step 14: Perform a binary search (binary_search) on array a to find key:
Initialize left to 1 and right to n
While left <= right, do Steps 15-20
Step 15: Calculate mid as (left + right) / 2
Step 16: If key equals a[mid], go to Step 17
Step 17: Print "Key element [key] is found at position [mid]."
Step 18: Return mid
Step 19: If key < a[mid], update right to mid - 1
Step 20: If key > a[mid], update left to mid + 1
Step 21: Print "Key element [key] not found."
Step 22: End
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 25 of 61
TIME ANALYSIS
1. Time Complexity
• Best Case Time Complexity of Binary Search Algorithm: (1)
Best case is when the element is at the middle index of the array. It takes only one comparison to find
the target element. So the best case complexity is (1).
• Average Case Time Complexity of Binary Search Algorithm: (log N)
Consider array arr[] of length N and element X to be found. There can be two cases:
Case1: Element is present in the array
Case2: Element is not present in the array.
There are N Case1 and 1 Case2. So total number of cases = N+1. Now notice the following:
An element at index N/2 can be found in 1 comparison
Elements at index N/4 and 3N/4 can be found in 2 comparisons.
Elements at indices N/8, 3N/8, 5N/8 and 7N/8 can be found in 3 comparisons and so on.
Based on this we can conclude that elements that require:
1 comparison = 1
2 comparisons = 2
3 comparisons = 4
x comparisons = 2x-1 where x belongs to the range [1, logN] because maximum comparisons =
maximum time N can be halved = maximum comparisons to reach 1st element = logN.
So, total comparisons
= 1*(elements requiring 1 comparisons) + 2*(elements requiring 2 comparisons) + . . . +
logN*(elements requiring logN comparisons)
= 1*1 + 2*2 + 3*4 + . . . + logN * (2logN-1)
= 2logN * (logN – 1) + 1
= N * (logN – 1) + 1
Total number of cases = N+1.
Therefore, the average complexity = (N*(logN – 1) + 1)/N+1 = N*logN / (N+1) + 1/(N+1). Here the
dominant term is N*logN/(N+1) which is approximately logN. So the average case complexity is
(logN)
• Worst CaseTime Complexity of Binary Search Algorithm: (log N)
The worst case will be when the element is present in the first position. As seen in the average case, the
comparison required to reach the first element is logN.
So the time complexity for the worst case is (logN).
Case Time Complexity
Best Case (1)
Worst Case (log N)
Average Case (log N)
2. Space Complexity
Binary Search Algorithm uses no extra space to search the element. Hence its auxiliary space
complexity is (1).
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 26 of 61
PRACTICAL 2.3
int main()
{
int n,low,high;
clock_t start,end;
double merge_time;
printf("Enter number of element:");
scanf("%d",&n);
int a[n];
for(int i=0;i<n;i++)
{
printf("%d ",a[i]=rand()%100);
}
low=0,high=n-1;
start=clock();
merge(a,low,high);
end=clock();
printf("\n");
printf("Sorted array is:");
for(int i=0;i<n;i++)
{
printf("%d ",a[i]);
}
merge_time=((double)(end-start))/CLOCKS_PER_SEC;
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 27 of 61
}
}
while(j<=high)
{
b[k]=a[j];
k++,j++;
}
while(i<=mid)
{
b[k]=a[i];
k++,i++;
}
for(i=low;i<=high;i++)
{
a[i]=b[i];
}
}
OUTPUT
Enter number of element:10
41 67 34 0 69 24 78 58 62 64
Sorted array is:0 24 34 41 58 62 64 67 69 78
Time taken by merge sort algorithm is:0.000002
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 28 of 61
Step 1: Start
Step 2: Input n (number of elements)
Step 3: Initialize an integer array a of size n
Step 4: Generate n random integers between 0 and 999 and store them in array a:
For i from 0 to n-1, do
I. Generate a random integer rand_num between 0 and 999
II. Set a[i] to rand_num
Step 5: Record the start time:
start_time = Clock()
Step 6: Perform Merge Sort to sort the array a:
a) Check if low is less than high:
If true, calculate mid as (low + high) / 2
Recursively call merge_sort(a, low, mid, high)
Recursively call merge_sort(a, mid+1, high)
Call merge(a, low, mid, high)
b) Within merge_sort, initialize i, j, and k
i = low
j = mid + 1
k = low
c) While i is less than or equal to mid and j is less than or equal to high, do
I. Check if a[i] is less than a[j]
If true, set b[k] to a[i], increment i and k
If false, set b[k] to a[j], increment j and k
II. Increment k, i, and j
d) While j is less than or equal to high, do
Set b[k] to a[j], increment k, and j
e) While i is less than or equal to mid, do
Set b[k] to a[i], increment k and i
f) For i from low to high, copy the values from b to a
Step 7: Record the end time:
end_time = Clock()
Step 8: Calculate the sorting time as (end_time - start_time) / CLOCKS_PER_SEC
Step 9: Print the sorted array
Step 10: Print the total time taken for sorting in seconds
Step 11: End
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 29 of 61
TIME ANALYSIS
1. Time Complexity
Let T(n) be the total time taken by the Merge Sort algorithm.
Sorting two halves will take at the most 2T𝑛 time.
2
When we merge the sorted lists, we come up with a total n-1 comparison because the last element
which is left will need to be copied down in the combined list, and there will be no comparison.
• Thus, the relational formula will be
T(n) = 2T(𝑛) + n - 1
2
• But we ignore '-1' because the element will take some time to be copied in merge lists.
So T(n) = 2T(𝑛) + n ……equation 1
2
Note: Stopping Condition T (1) =0 because at last, there will be only 1 element left that need to be
copied, and there will be no comparison.
Putting n=𝑛 in place of n in equation 1 T(n) = 2i T( 𝑛𝑖)+ in …….equation 6
2 2
T(𝑛) = 2T( 𝑛 2) + 𝑛 ……equation 2 • From stopping condition:
2 2 2 𝑛 𝑛
• Put 2 equation in 1 equation 2𝑖
= 1 And T(2𝑖) = 0
T(n) = 2[2T(𝑛2) + 𝑛2] + n n = 2i
• Apply log both sides:
= 22T( 𝑛 ) + 2𝑛 + n
22 2 log n = log 2i
= 22T( 𝑛2) + 2n ……equation 3 log n = i log 2
2
• Putting n= 𝑛2in equation 1 log 𝑛
=i
2 log 2
T(n) = 22[T( 𝑛 ) + 𝑛 ] + 2n log2 n = i
23 22
= 23[T( 𝑛3) +n] + 2n From equation 6
2
T(n) = 2i T( 𝑛𝑖)+ in
= 23 T( 𝑛3)+ 3n ……equation 5 2
2
= 2i * 0 + (log2 n)n
From eq 1, eq 3, eq 5 …we get
= T(n) = n.log2n
Best Case Complexity: The merge sort algorithm has a best-case time complexity of (n*log n) for the
already sorted array.
Average Case Complexity: The average-case time complexity for the merge sort algorithm is (n*log n),
which happens when 2 or more elements are jumbled, i.e., neither in the
ascending order nor in the descending order.
Worst Case Complexity: The worst-case time complexity is also (n*log n), which occurs when we sort
the descending order of an array into the ascending order.
2. Space Complexity
The space complexity of merge sort is (n).
Now we discuss the time complexity of factorial of number n using different method as follows:
Merge Sort
Array size Required Time(sec.)
10 0.000002
100 0.000010
1000 0.000223
10000 0.001247
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 30 of 61
PRACTICAL 2.4
int main()
{
int n,low,high;
clock_t start,end;
double quick_time;
printf("Enter number of element:");
scanf("%d",&n);
int a[n];
for(int i=0;i<n;i++)
{
printf("%d ",a[i]=rand()%100);
}
low=0,high=n-1;
start=clock();
quick_sort(a,low,high);
end=clock();
printf("\n");
printf("Sorted array is:");
for(int i=0;i<n;i++)
{
printf("%d ",a[i]);
}
quick_time=((double)(end-start))/CLOCKS_PER_SEC;
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 31 of 61
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 32 of 61
Step 1: Start
Step 2: Input n (number of elements)
Step 3: Initialize an integer array a of size n
Step 4: Generate n random integers between 0 and 999 and store them in array a:
For i from 0 to n-1, do
I. Generate a random integer rand_num between 0 and 999
II. Set a[i] to rand_num
Step 5: Record the start time:
start_time = Clock()
Step 6: Perform Quick Sort to sort the array a:
a) Check if low is less than high:
If true, call partition(a, low, high) to determine p
Recursively call quick_sort(a, low, p-1)
Recursively call quick_sort(a, p+1, high)
b) Within partition, initialize pivot, i, and j:
pivot = a[low]
i = low
j = high
c) While i is less than j, do
I. While a[i] is less than or equal to pivot and i is less than or equal to high, increment i
II. While a[j] is greater than pivot and j is greater than or equal to low, decrement j
III. If i is less than j, swap a[i] and a[j]
d) Swap a[low] and a[j]
e) Return j
Step 7: Record the end time:
end_time = Clock()
Step 8: Calculate the sorting time as (end_time - start_time) / CLOCKS_PER_SEC
Step 9: Print the sorted array
Step 10: Print the total time taken for sorting in seconds
Step 11: End
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 33 of 61
TIME ANALYSIS
1. Time Complexity
Let us consider the following terminologies:
T(K): Time complexity of quick sort of K elements
P(K): Time complexity for finding the position of pivot among K elements.
❖ Best Case:
The best case occurs when we select the pivot as the mean. So here
T(N) = 2*T(N/2) + N/2 * constant
Now T(N/2) is also 2*T(N/4) + N/2 * constant. So,
T(N/2) = 2(2*T(N/2) + N/2 * constant) + N*constant
= 4*T(N/4) + 2 * constant * N
So, we can say that
T(N) = 2k * T(N/2k) + k * constant * N
Then, 2k = N
k = log2N
So T(N) = N * T(1) + N*log2N. Therefore, the time complexity is (N*logN)
❖ Worst Case:
The worst case will occur when the array gets divided into two parts, one part consisting of N – 1
elements and the other and so on. So,
T(N) = T(N-1) + n*constant
= T(N-2) + (N-1)*constant + N*constant
= T(N-2) + 2*N*constant - constant
= T(N-3) + 3*N*constant – 2*constant – constant
……
= T(N-k) + k*N*constant – constant*(k*(k-1))/2
If we put k=N in the above equation, then
T(N) = T(0) + N*N*constant – constant * (N*(N-1)/2)
= N2 – N*(N-1)/2
= N2/2 + N/2
So the worst case complexity is O(N2).
❖ Average Case:
For the average case consider the array gets divided into two parts of size k and (N-k). So,
T(N) = T(N-k) + T(k)
= 1/N * [∑𝑁−1 𝑇(𝑖) + ∑𝑁−1 𝑇(𝑁 − 𝑖)]
𝑖=1 𝑖=1
• As ∑𝑁−1 𝑇(𝑖) and ∑𝑁−1 𝑇(𝑁 − 𝑖) are equal likely function, we can say
𝑖=1 𝑖=1
𝑁−1 𝑇(𝑖)]
T(N) = 2/N * [∑𝑖=1
N*T(N) = 2 * [∑𝑖=1𝑁−1 𝑇(𝑖)]
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 34 of 61
2. Space Complexity
The required space is (1) as we are not using extra space in the algorithm. If we don’t consider the
recursive stack space. If we consider the recursive stack space then, in the worst-case quicksort could
make (N).
Now we discuss the time complexity of factorial of number n using different method as follows:
Quick Sort
Array size Required Time(sec.)
10 0.000002
100 0.000031
1000 0.000157
10000 0.001888
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 35 of 61
PRACTICAL 2.5
int a[n];
int choice;
printf("1: Using Random function\n2: Using manually create-array");
printf("\n ");
printf("\nEnter your choice here:");
scanf("%d",&choice);
printf(" --------------------------- \n");
switch(choice)
{
case 1:
// Using random function
printf("Random array data are:");
for(int i=0;i<n;i++)
{
printf("%d ",a[i]=rand()%100);
}
printf(" \n");
printf("Manually created array data are:");
for(int i=0;i<n;i++)
{
printf("%d ",a[i]);
}
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 36 of 61
printf("\n ");
printf("\nAfter Applying Max-Heap sort:");
for(int i=0;i<n;i++)
{
printf("%d ",a[i]);
}
return 0;
}
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 37 of 61
swap(&a[i],&a[larg]);
heapify(a,n,larg); //recursively called for sub-tree
}
}
OR
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 38 of 61
PRACTICAL 3.1
return K[n][W];
}
int main()
{
int val[] = {60, 100, 120};
int wt[] = {10, 20, 30};
int W = 50;
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 39 of 61
printf("\n");
printf("Maximum value that can be obtained is %d", knapSack(W, wt, val, n));
return 0;
}
OUTPUT
Value of the Items: 60 100 120 50 13243648
Weight of the Items: 10 20 30 60 100
Maximum value that can be obtained is 220
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 40 of 61
PRACTICAL 3.2
int main()
{
int arr[] = {1, 2, 3, 4};
int size = sizeof(arr) / sizeof(arr[0]);
printf("Sequence of the data for chain matrix multiplication is:\n");
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 41 of 61
PRACTICAL 3.3
int main()
{
int coins[] = {9, 6, 5, 1};
int m = sizeof(coins) / sizeof(coins[0]);
int V = 11;
printf("Coin Number is:\n");
for (int i = 0; i < m; i++)
{
printf("%d ", coins[i]);
}
printf("\ncount the number of coins required to make a given value sum is: %d", V);
printf("\nMinimum coins required is %d ", minCoins(coins, m, V));
return 0;
}
OUTPUT
Coin Number is:
9651
count the number of coins required to make a given value sum is: 11
Minimum coins required is 2
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 42 of 61
PRACTICAL 3.4
#include <stdio.h>
#include <string.h>
return L[m][n];
}
int main()
{
char X[] = "AGGTAB";
char Y[] = "GXTXAYB";
printf("X: %s\n", X);
printf("Y: %s\n", Y);
int m = strlen(X);
int n = strlen(Y);
printf("Length of LCS is %d", lcs(X, Y, m, n));
return 0;
}
OUTPUT
X: AGGTAB
Y: GXTXAYB
Length of LCS is 4
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 43 of 61
PRACTICAL 3.5
if (i < n)
x[i] = u / weight[i];
tp = tp + (x[i] * profit[i]);
int main()
{
float weight[20], profit[20], capacity;
int num, i, j;
float ratio[20], temp;
printf("\nEnter the weights first and then profits of each object:- ");
for (i = 0; i < num; i++){
scanf("%f %f", &weight[i], &profit[i]);
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 44 of 61
}
printf("\nItem |Weight |Profit");
printf("\n \n");
for (i = 0; i < num; i++){
printf("%d |%f |%f \n", i + 1, weight[i], profit[i]);
}
printf("\nEnter the capacity of knapsack:- ");
scanf("%f", &capacity);
for (i = 0; i < num; i++){
ratio[i] = profit[i] / weight[i];
}
temp = weight[j];
weight[j] = weight[i];
weight[i] = temp;
temp = profit[j];
profit[j] = profit[i];
profit[i] = temp;
}
}
}
knapsack(num, weight, profit, capacity);
return (0);
}
OUTPUT
Enter the no. of objects:- 3
Enter the weights first and then profits of each object:- 10
60
20
100
30
120
1 |10.000000 |60.000000
2 |20.000000 |100.000000
3 |30.000000 |120.000000
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 45 of 61
PRACTICAL 3.6
Referance: https://www.geeksforgeeks.org/prims-minimum-spanning-tree-mst-greedy-algo-5/
*/
#include <stdio.h>
#include <stdlib.h>
#define infinity 9999
#define MAX 20
int main()
{
int total_cost;
printf("Enter no. of vertices:");
scanf("%d", &n);
printf(" \n");
printf("Enter the weight for grph adjacency matrix:\n");
printf(" \n");
printf("Enter weight for edges-vertex at position:\n");
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 46 of 61
}
}
int prims()
{
int cost[MAX][MAX];
int u, v, min_distance, distance[MAX], from[MAX];
int visited[MAX], no_of_edges, min_cost;
// create cost[][] matrix,spanning[][]
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 47 of 61
u = from[v];
// insert the edge in spanning tree
spanning[u][v] = distance[v];
spanning[v][u] = distance[v];
no_of_edges--;
visited[v] = 1;
// updated the distance[] array
}
return min_cost;
}
OUTPUT
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 48 of 61
G[0][0] ==> 0
G[0][1] ==> 4
G[0][2] ==> 0
G[0][3] ==> 0
G[0][4] ==> 0
G[0][5] ==> 0
G[0][6] ==> 0
G[0][7] ==> 8
G[0][8] ==> 0
G[1][0] ==> 4
G[1][1] ==> 0
G[1][2] ==> 8
G[1][3] ==> 0
G[1][4] ==> 0
G[1][5] ==> 0
G[1][6] ==> 0
G[1][7] ==> 11
G[1][8] ==> 0
G[2][0] ==> 0
G[2][1] ==> 8
G[2][2] ==> 0
G[2][3] ==> 7
G[2][4] ==> 0
G[2][5] ==> 4
G[2][6] ==> 0
G[2][7] ==> 0
G[2][8] ==> 2
G[3][0] ==> 0
G[3][1] ==> 0
G[3][2] ==> 7
G[3][3] ==> 0
G[3][4] ==> 9
G[3][5] ==> 14
G[3][6] ==> 0
G[3][7] ==> 0
G[3][8] ==> 0
G[4][0] ==> 0
G[4][1] ==> 0
G[4][2] ==> 0
G[4][3] ==> 9
G[4][4] ==> 0
G[4][5] ==> 10
G[4][6] ==> 0
G[4][7] ==> 0
G[4][8] ==> 0
G[5][0] ==> 0
G[5][1] ==> 0
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 49 of 61
G[5][2] ==> 4
G[5][3] ==> 14
G[5][4] ==> 10
G[5][5] ==> 0
G[5][6] ==> 2
G[5][7] ==> 0
G[5][8] ==> 0
G[6][0] ==> 0
G[6][1] ==> 0
G[6][2] ==> 0
G[6][3] ==> 0
G[6][4] ==> 0
G[6][5] ==> 2
G[6][6] ==> 0
G[6][7] ==> 1
G[6][8] ==> 7
G[7][0] ==> 8
G[7][1] ==> 11
G[7][2] ==> 0
G[7][3] ==> 0
G[7][4] ==> 0
G[7][5] ==> 0
G[7][6] ==> 1
G[7][7] ==> 0
G[7][8] ==> 7
G[8][0] ==> 0
G[8][1] ==> 0
G[8][2] ==> 2
G[8][3] ==> 0
G[8][4] ==> 0
G[8][5] ==> 0
G[8][6] ==> 6
G[8][7] ==> 7
G[8][8] ==> 0
0 4 0 0 0 0 0 0 0
4 0 8 0 0 0 0 0 0
0 8 0 7 0 4 0 0 2
0 0 7 0 9 0 0 0 0
0 0 0 9 0 0 0 0 0
0 0 4 0 0 0 2 0 0
0 0 0 0 0 2 0 1 0
0 0 0 0 0 0 1 0 0
0 0 2 0 0 0 0 0 0
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 50 of 61
PRACTICAL 3.7
#define MAX 30
int parent[MAX];
int find(int i)
{
while (parent[i])
i = parent[i];
return i;
}
void kruskal(graph g)
{
int i, j, u, v;
int ne = 0, mincost = 0;
int selected[MAX]; // To keep track of selected edges
for (i = 1; i <= g.n; i++)
{
parent[i] = 0;
selected[i] = 0; // Initialize selected array
}
while (ne < g.n - 1)
{
int min = 9999;
int selectedEdge = -1; // Variable to keep track of the selected edge
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 51 of 61
int main()
{
graph g;
int i, j, k, wt;
printf("Enter number of vertices:");
scanf("%d", &g.n);
printf("Enter number of edges:");
scanf("%d", &g.e);
for (i = 0; i < g.e; i++){
printf("\n");
printf("Enter edge (u, v) and weight:\n");
printf("source vertex:");
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 52 of 61
scanf("%d", &g.edges[i].u);
printf("Destination vertex:");
scanf("%d", &g.edges[i].v);
printf("Weight of the edge:");
scanf("%d", &g.edges[i].w);
}
kruskal(g);
return 0;
}
OUTPUT
Enter number of vertices:4
Enter number of edges:6
Minimum cost = 5
Selected Edges:
(0, 1) cost: 2
(2, 3) cost: 1
(2, 1) cost: 2
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 53 of 61
PRACTICAL 4.1
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 54 of 61
if (isEmpty(q))
{
printf("This Queue is empty\n");
}
else
{
q->f++;
a = q->arr[q->f];
}
return a;
}
int main()
{
struct queue q;
q.size = 400;
q.f = q.r = 0;
q.arr = (int *)malloc(q.size * sizeof(int));
// BFS Implementation
int node;
int i = 0;
int visited[7] = {0, 0, 0, 0, 0, 0, 0};
printf("\nThe Adjacency Matrix of the Graph is:\n");
int a[7][7] = {
{0, 1, 1, 0, 0, 0, 0},
{1, 0, 0, 1, 0, 0, 0},
{1, 0, 0, 1, 1, 0, 0},
{0, 1, 1, 0, 0, 0, 0},
{0, 0, 1, 0, 0, 1, 1},
{0, 0, 0, 0, 1, 0, 1},
{0, 0, 0, 0, 1, 1, 0}};
for (int i = 0; i < 7; i++)
{
for (int j = 0; j < 7; j++)
{
printf("%d ", a[i][j]);
}
printf("\n");
}
printf("\nBFS traversal of the graph:\n");
printf("%d ", i);
enqueue(&q, i);
while (!isEmpty(&q))
{
int node = dequeue(&q); // remove
visited[i] = 1; // mark visited
for (int j = 0; j < 7; j++)
{
if (a[node][j] == 1 && visited[j] == 0)
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 55 of 61
{
printf("%d ", j); // add to the bfs
visited[j] = 1;
enqueue(&q, j); // add neighbors
}
}
}
printf("\n");
return 0;
}
OUTPUT
The Adjacency Matrix of the Graph is:
0110000
1001000
1001100
0110000
0010011
0000101
0000110
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 56 of 61
PRACTICAL 4.2
struct node
{
int vertex;
struct node *next;
};
struct Graph
{
int totalVertices;
int *visited;
struct node **adjLists;
};
graph->visited[vertex] = 1;
printf("%d -> ", vertex);
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 57 of 61
int i;
for (i = 0; i < vertices; i++)
{
graph->adjLists[i] = NULL;
graph->visited[i] = 0;
}
return graph;
}
int main()
{
struct Graph *graph = createGraph(8);
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 58 of 61
addEdge(graph, 1, 5);
addEdge(graph, 1, 2);
addEdge(graph, 1, 3);
addEdge(graph, 3, 6);
addEdge(graph, 2, 7);
addEdge(graph, 2, 4);
return 0;
}
OUTPUT
The Adjacency List of the Graph is:
1 => 3, 2, 5,
2 => 4, 7, 1,
3 => 6, 1,
4 => 2,
5 => 1,
6 => 3,
7 => 2,
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 59 of 61
PRACTICAL 5.1
#define d 256
if (j == M)
printf("Pattern found at index %d \n", i);
}
if (i < N - M)
{
t = (d * (t - text[i] * h) + text[i + M]) % q;
if (t < 0)
t = (t + q);
}
}
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 60 of 61
int main()
{
char text[] = "ABABDABACDABABCABAB";
char pattern[] = "ABABCABAB";
int n = strlen(text);
printf("Data string is: ");
for (int i = 0; i < n; i++)
{
printf("%c", text[i]);
i++;
}
int m = strlen(pattern);
printf("\nPattern is: ");
for (int i = 0; i < m; i++)
{
printf("%c", text[i]);
i++;
}
printf("\n");
int q = 101;
search(pattern, text, q);
return 0;
}
OUTPUT
Data string is: AADBCAACBB
Pattern is: AADBC
Pattern found at index 10
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat
Page 61 of 61
NOTE:
SUBMIT YOUR LAB-MANUAL TILL PAGE NO. 60. NOT INCLUDE CURRENT PAGE
(PAGE NO. 61). THIS PAGE IS ONLY FOR THEORY REFERENCE OF GIVEN PROBLEM
STATEMENT.
Analysis and Design of Algorithm (3150703) 3Y/5th Sem - 210090107068 CKPCET, Surat