Ada Lab New
Ada Lab New
Ada Lab New
PRACTICAL:1
Aim : Implementation and Time analysis of sorting algorithms. Bubble sort,
Selection sort, Insertion sort, Merge sort and Quicksort.
Bubble sort
Algorithm :
Begin BubbleSort(list)
For all elements of list
If list[i] > list[i+1]
Swap(list[i], list[i+1])
End if
End for
Return list
End BubbleSort
Analysis of algorithm :
(C-code)
#include<stdio.h>
#include<time.h>
#include<stdlib.h> void main()
{
int a[30000],i,j,number,index;
clock_t t; double
time_taken;
clrscr();
t=clock(); for(i=0;i<30000;i++)
{
a[i]=rand();
}
1
for(i=0;i<30000-1;i++)
{
for(j=0;j<30000-i-1;j++)
{
if(a[j]>a[j+1])
{
int temp=a[j];
a[j]=a[j+1]; a[j+1]=temp;
}
}
}
for(i=0;i<30000;i++)
{
printf(“%d\t”,a[i]);
}
t=clock()-t;
time_taken=((double)t)/clocks_per_sec; printf(“\ntime
taken:%f”,time_taken);
getch();
}
Output -
2
1. Best case analysis : The best case for the bubble sort algorithm is when the array is
already sorted in ascending order. For the best case , there will be no need of
swapping. The basic comparison operation will be executed for n times .
Therefore the Time complexity will be Ω(n)
3. Worst case analysis : When the array is sorted in reverse in descending order.
O(n^2)
C – Program :
#include<stdio.h>
int main()
{
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);
bubblesort(arr, n); printf(“sorted array:
\n”); printarray(arr, n); return 0;
}
void printarray(int arr[], int size)
{ int i; for (i=0; i < size;
i++) printf(“%d “, arr[i]);
printf(“\n”);
}
void bubblesort(int arr[], int n)
{ int i, j; for (i = 0; i < n-1; i++)
for (j = 0; j < n-i-1; j++) if (arr[j] >
arr[j+1]) swap(&arr[j],
&arr[j+1]);
}
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
4
Output :
Selection sort
Algorithm :
Analysis of algorithm :
➔ Input = n
According to the algorithm , there will be n-1 comparisons in pass1 , n-2 comparisons
in pass2 , n-3 comparison in pass3 and so on . (At n-1th pass comp =1)
Total comparisons = 1+2+3+…+(n-1)
= n(n-1)/2
Time complexity for selection sort will be :
1. Best case :
5
Ω(n^2)
2. Average case : θ(n^2)
3. Worst case :
O(n^2)
C – Program :
#include <stdio.h>
#include<time.h>
#include<stdlib.h> int main()
{ int arr[] , i ;
clock_t t; double
time_taken;
for(i=0;i<30000;i++)
{
a[i]=rand();
}
t=clock();
int n = sizeof(arr)/sizeof(arr[0]);
selectionSort(arr, n); printf("Sorted array: \n");
printArray(arr, n);
t=clock()-t;
time_taken=((double)t)/CLOCKS_PER_SEC; print("\n time
taken : %f ", time_taken);
return 0;
}
void swap(int *xp, int *yp)
{
int temp = *xp; *xp =
*yp;
*yp = temp;
}
6
void selectionSort(int arr[], int n)
{
int i, j, min_idx;
// Swap the found minimum element with the first element swap(&arr[min_idx],
&arr[i]);
}
}
/* Function to print an array */ void
printArray(int arr[], int size)
{ int i;
for (i=0; i < size; i++)
printf("\n");
7
output for 3 cases:
8
Insertion sort
Algorithm :
INSERTION-SORT. (A)
for j = 2 to A.length key =
A[j]
// Insert A[j] into the sorted sequence A[1…. j – 1].
i = j -1
while i>0 and A[i] > key
A[i+1] = A[i]
i = i -1
A[i+1] = key
Analysis of algorithm :
Input = n
According to the algorithm , there will be n-1 comparisons in pass1 , n-2 comparisons
in pass2 , n-3 comparison in pass3 and so on . (At n-1th pass comp =1)
Total comparisons = 1+2+3+…+(n-1)
= n(n-1)/2
Time complexity :
1. Best case :
The insertion sort algorithm has a best-case time complexity of Ω(n) for the
already sorted array because here, only the outer loop is running n times, and the
inner loop is kept still.
9
2. Average case :
The average-case time complexity for the insertion sort algorithm is θ(n^2), which
is incurred when the existing elements are in jumbled order, i.e., neither in the
ascending order nor in the descending order.
3. Worst case :
The worst-case time complexity is also O(n2), which occurs when we sort the
ascending order of an array into the descending order.
In this algorithm, every individual element is compared with the rest of the
elements, due to which n-1 comparisons are made for every nth element.
time_taken=((double)t)/CLOCKS_PER_SEC; printf("\nTime
taken:%f",time_taken);
}
11
C – Program :
#include<stdio.h> void main
()
{
int i,j, k,temp;
int a[] = { 4,6,7,3,10,12,22,14}; printf("\n sorted
elements...\n"); for(k=1; k<8; k++)
{
temp = a[k]; j=
k-1;
while(j>=0 && temp <= a[j])
{
a[j+1] = a[j];
j = j-1;
}
a[j+1] = temp;
}
for(i=0;i<8;i++)
{
printf("\t %d",a[i]);
}
}
Output :
12
Merge sort
Algorithm :
Algorithm MergeSort (int A[0…n-1], low, high) //Input: Array A of
unsorted elements ,low as beginning
//pointer of array A and high //as end pointer of array A.
//Output:sorted array A[0….n-1] if
(low<high) then
{
mid (low+high)/2 //split the list at mid MergeSort(A,low,mid) //first
sublist
MergeSort(A,mid+1,high) //second sublist
Combine(A,low,mid,high) //merging of two sublist
}
Algorithm Combine(A[0…n-1],low,mid,high)
{
k low; //k as index foe array temp i low; //i as index for left
sublist of array A j mid+1 //j as index for right sublist of array A
while (i <=mid and j<=high)do
{
if(A[i]<=A[j])then
13
{
//copy that smaller element to temp array
temp[k]A[j]
jj+1 kk+1
}
}
//copy remaining elements of left sublist to temp while(i <= mid) do
{
temp[k] A[i] i i+1 k
k+1
}
//copy remaining elements of right sublist to temp while (j <= high) do
{
temp[k] A[j]
j j+1 k k+1
}
Analysis of algorithm :
Let 𝑻(𝒏) be the time taken by this algorithm to sort an array of 𝑛 elements.
Separating 𝑇 into 𝑈 & 𝑉 takes linear time; 𝑚𝑒𝑟𝑔𝑒(𝑈, 𝑉, 𝑇) also takes linear time.
𝑇(𝑛)=𝑇(𝑛/2)+ 𝑇(𝑛/2)+𝑔(𝑛) where 𝑔(𝑛)∈θ(𝑛).
𝑇(𝑛)=2𝑡(𝑛/2)+ θ(𝑛)________________(1)
Here , 𝒕(𝒏) = 𝒂𝒕(𝒏/𝒃) + 𝒇(𝒏)
According to the master’s theorem :
a=2 b, b=2 , k=1 k=nlogba = 1
14
C- Program for Analysis :
#include <stdio.h> #include<conio.h>
#include<time.h>
void mergeSort(int [], int, int, int); void
devidation(int [],int, int); main()
{ int a[50];
int i,n; clock_t
t;
double time_taken;
t=clock();
printf("how many numbers would you like to enter:"); scanf("%d", &n);
printf("Enter %d Elements:\n",n); for(i = 0; i < n;
i++)
{
scanf("%d", &a[i]);
}
devidation(a, 0, n - 1); printf("sorted
elements are:\n"); for(i = 0;i < n; i++)
{
printf("%d ",a[i]);
}
t=clock()-t;
time_taken=((double)t)/CLOCKS_PER_SEC; printf("\nTime
taken:%f",time_taken);
}
void devidation(int a[],int low,int high)
{ int mid;
if(low < high)
{
mid = (low + high) / 2;
15
devidation(a, low, mid); devidation (a,
mid + 1, high); mergeSort(a, low, mid,
high);
}
}
void mergeSort(int a[],int low,int mid,int high)
{
int i, m, j, l, temp[50]; l=
low; i = low; m = mid + 1;
while ((l <= mid) && (m <= high))
{
if (a[l] <= a[m])
{
temp[i] = a[l]; l++;
}
else
{
temp[i] = a[m]; m++;
}
i++; }
if (l >
mid)
{
for (j = m; j <= high; j++)
{
temp[i] = a[j];
i++; } }
else
{
for (j = l; j <= mid; j++)
{
16
temp[i] = a[j];
i++; } }
for (j = low; j <= high; j++)
{
a[j] = temp[j];
}
}
Output for 3 cases :
C – Program :
#include <stdio.h>
#include <stdlib.h>
// Merges two subarrays of arr[].
// First subarray is arr[l..m] // Second subarray is
arr[m+1..r] void merge(int arr[], int l, int m, int r)
{
17
int i, j, k; int n1 = m
- l + 1; int n2 = r - m;
int L[n1], R[n2];
/* Copy data to temp arrays L[] and R[] */
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; //
Initial index of first subarray j = 0; // Initial index of
second subarray k = l; // Initial index of merged
subarray 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++;
}
}
}
int main()
{
int arr[] = { 12, 11, 13, 5, 6, 7 }; int arr_size =
sizeof(arr) / sizeof(arr[0]); printf("Given array is
\n"); printArray(arr, arr_size); mergeSort(arr, 0,
arr_size - 1); printf("\nSorted array is \n");
printArray(arr, arr_size); return 0;
}
Quick sort
Algorithm :
Procedure: quicksort(T[i,…,j])
{Sorts subarray T[i,…,j] into ascending order} if j – i is
sufficiently small then insert (T[i,…,j]) else
pivot(T[i,…,j],l)
quicksort(T[i,…,l - 1]) quicksort(T[l+1,…,j]
19
Analysis of algorithm :
1. Worst Case
2. Best Case
• Occurs when partition produces sub-problems each of size n/2. • Recurrence
equation: 𝑇(𝑛) = 2𝑇 (𝑛) + θ(𝑛)
2
As per Master’s Theorem :
∴ 𝑻(𝒏) = 𝜽(𝒏𝒍𝒐𝒈𝒏)
3. Average Case :
• Average case running time is much closer to the best case.
• If suppose the partitioning algorithm produces a 9:1 proportional split the
recurrence will be,
𝑇(𝑛) = 𝑇(9𝑛/10) + 𝑇(𝑛/10) + θ(𝑛)
𝑻(𝒏) = 𝜽(𝒏𝒍𝒐𝒈𝒏)
20
(C code for analysis)
#include<stdio.h>
#include<conio.h>
#include<time.h> void
quiksort(int,int,int); int a[25];
main()
{ int i, n;
clock_t t;
double time_taken; t=clock();
printf(“\nhow many elements would you like to enter?: “); scanf(“%d”,&n);
printf(“\nenter %d elements: “, n);
for(i=0;i<n;i++) scanf(“%d”,&a[i]);
quicksort(a,0,n-1);
printf(“\n sorted elements are: “);
for(i=0;i<n;i++) printf(“ %d”,a[i]);
t=clock()-t;
time_taken=((double)t)/clocks_per_sec;
printf(“\ntime taken:%f”,time_taken);
}
if(first<last){
keyval=first;
i=first; j=last;
while(i<j){
while(a[i]<=a[keyval]&&i<last)
i++;
while(a[j]>a[keyval])
21
j--;
if(i<j){
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
temp=a[keyval];
a[keyval]=a[j]; a[j]=temp;
quicksort(a,first,j-1);
quicksort(a,j+1,last);
}
}
C – Program :
22
#include <stdio.h> void quicksort (int
[], int, int); int main()
{ int list[50];
int size, i;
printf("Enter the number of elements: "); scanf("%d", &size);
printf("Enter the elements to be sorted:\n"); for (i = 0; i < size;
i++)
{
scanf("%d", &list[i]);
}
quicksort(list, 0, size - 1); printf("After applying
quick sort\n"); for (i = 0; i < size; i++)
{
printf("%d ", list[i]);
}
printf("\n"); return 0;
}
void quicksort(int list[], int low, int high)
{
int pivot, i, j, temp; if
(low < high)
{
pivot = low;
i = low; j = high;
while (i < j)
{
while (list[i] <= list[pivot] && i <= high)
{
i++;
}
while (list[j] > list[pivot] && j >= low)
23
{
j--; }
if (i < j)
{ temp =
list[i]; list[i] =
list[j]; list[j] =
temp;
}
}
temp = list[j]; list[j] =
list[pivot]; list[pivot] = temp;
quicksort(list, low, j - 1);
quicksort(list, j + 1, high);
}
}
Output :
24
PRACTICAL:2
AIM : Implementation and Time analysis of linear and binary search algorithm.
Time Analysis :
C – code :
#include<stdio.h>
#include<conio.h> #include<time.h>
#include<stdlib.h>
void main()
{
25
clock_t t;
int a[30000],i,j,number,index=-1; double
time_taken; clrscr();
printf("Enter a number you want to search");
scanf("%d",&number); t=clock(); for(i=0;i<30000;i++)
{
a[i]=i;
}
for(i=0;i<30000;i++)
{
for( j=0;j<i;j++)
{
if(a[i]==number)
{
index=i;
break;
}
}
}
t=clock()-t;
time_taken= ((double)t)/CLOCKS_PER_SEC;
26
Binary Search Algorithm :
Procedure binary_search A ← sorted array n ← size of array x ← value to be searched
27
Set lowerBound = 1
Set upperBound = n
if A[midPoint] < x
set lowerBound = midPoint + 1
if A[midPoint] > x
set upperBound = midPoint - 1
if A[midPoint] = x
EXIT: x found at location midPoint end while
end procedure
Time Analysis :
➔ According to the algorithm – basic operation is comparison of key value with array
elements .
The n elements are devided in half means into n/2 elements in each part. Same for the
half arrays.
Let 𝑡(𝑛) be the time required for a call on the Binary search function ,
The recurrence equation is given as,
𝒕(𝒏)=𝒕(𝒏/𝟐)+𝜽(𝟏)
C – Code :
#include <stdio.h> #include<conio.h>
#include<time.h>
void main()
{
int i, f, l, mid,value, a[30000]; clock_t t;
double time_taken; t=clock();
for (i = 0; i < 30000; i++) a[i]=i;
printf("Enter Value to Find\n"); scanf("%d", &value);
f = 0;
l = 30000 - 1; mid =
(f+l)/2;
while (f <= l)
{
if (value > a[mid]) f = mid
+ 1; else if (a[mid] == value)
{
printf("%d found at location %d.\n", value, mid+1); break;
} else l
= mid - 1;
mid = (f + l)/2;
} if (f >
l)
printf("Not found! %d isn't present in the list.\n", value); t=clock()-t;
time_taken=((double)t)/CLOCKS_PER_SEC; printf("\nTime
taken:%f",time_taken);
}
29
30
Time Complexity Analysis (Best , Average & Worst Case) For sorting and Searching
Algorithms :
1 . Bubble Sort 4 5 8
31
PRACTICAL:4
Aim : Implementation and time analysis of Factorial program using iterative and
recursive method.
Iterative Method :
C – Program –
void main()
{
int num = 8;
printf("Factorial of %d is %d", num, factorial(num)); getch();
}
Output :
Time analysis :-
In the iterative method , there are n iterations inside the for loop. So the time
complexity will be O(n).
32
Recursive Method :
C – program –
#include<stdio.h> int
fact(int); int main()
{
int num;
printf("Enter the number :"); scanf("%d" ,&num);
if(num<0)
{
printf(“ invalid input ");
}
printf("Factorial of %d is %d", num, fact(num)); return 0;
}
int fact(int num)
{
if(num==0)
{
return 1;
}
else
{
return(num*fact(num-1)); //recursive call
}
}
Output :
Time analysis :-
For recursive method –
T(n) = T(n — 1) + 3 T(0) = 1 T(n) = T(n-1) + 3 = T(n-2) + 6 = T(n-3)
+ 9 = T(n-4) + 12 = ... = T(n-k) + 3k
As we know T(0) = 1 we need to find the value of k for which n
– k = 0, k = n T(n) = T(0) + 3n , k = n = 1 + 3n
That gives us a time complexity of O(n)
33
34
PRACTICAL:7
Aim: Implementation of making a change problem using dynamic programming
35
PRACTICAL:5
Aim: Implementation of a knapsack problem using dynamic programming.
#include<stdio.h>
#include<conio.h>
int w[10],p[10],v[10][10],n,i,j,cap,x[10]= {0};
int max(int i,int j) {
return ((i>j)?i:j);
}
int knap(int i,int j) {
int value;
if(v[i][j]<0) {
if(j<w[i])
value=knap(i-1,j); else
value=max(knap(i-1,j),p[i]+knap(i-1,j-w[i]));
v[i][j]=value;
}
return(v[i][j]);
}
void main() {
int profit,count=0;
clrscr();
printf("\nEnter the number of elements\n");
scanf("%d",&n);
printf("Enter the profit and weights of the elements\n");
for (i=1;i<=n;i++) {
printf("For item no %d\n",i);
scanf("%d%d",&p[i],&w[i]);
}
printf("\nEnter the capacity \n");
scanf("%d",&cap);
36
for (i=0;i<=n;i++)
for (j=0;j<=cap;j++)
if((i==0)||(j==0))
v[i][j]=0; else
v[i][j]=-1;
profit=knap(n,cap);
i=n;
j=cap;
while(j!=0&&i!=0) {
if(v[i][j]!=v[i-1][j]) {
x[i]=1;
j=j-w[i];
i--;
} else
i--;
}
printf("Items included are\n");
printf("Sl.no\tweight\tprofit\n");
for (i=1;i<=n;i++)
if(x[i])
printf("%d\t%d\t%d\n",++count,w[i],p[i]);
printf("Total profit = %d\n",profit);
getch();
}
37