Assignment01 21103085 Atul Kumar Gupta ADA
Assignment01 21103085 Atul Kumar Gupta ADA
Assignment01 21103085 Atul Kumar Gupta ADA
OUTPUT:
2:-Optimize the above searching algorithm to perform searching for the same elements in
O(log(n)) average time complexity by comparing search key to the middle of the list and
recursively decreasing search space size to one half.
CODE:
int binarysearch1(int arr[], int st, int en, int tar, int val){
if(st<=en){
int mid=(st+en)/2;
if(arr[mid]==tar){
val=mid;
return binarysearch1(arr,st,mid-1,tar,val);
}
else if(arr[mid]>tar){
return binarysearch1(arr,st,mid-1,tar,val);
}
else{
return binarysearch1(arr,mid+1,en,tar,val);
}
}
else{
return val;
}
}
int binarysearch2(int arr[], int st, int en, int tar, int val){
if(st<=en){
int mid=(st+en)/2;
if(arr[mid]==tar){
val=mid;
return binarysearch2(arr,mid+1,en,tar,val);
}
else if(arr[mid]>tar){
return binarysearch2(arr,st,mid-1,tar,val);
}
else{
return binarysearch2(arr,mid+1,en,tar,val);
}
}
else{
return val;
}
}
OUTPUT:
CODE:
void selectionsort(int arr[], int size){
int count=0;
int iter=0;
for(int i=0;i<size-1;i++){
int minel=arr[i];
int mindex=i;
for(int j=i+1;j<size;j++){
count++;
if(arr[j]<minel){
mindex=j;
minel=arr[j];
}
}
int temp=arr[i];
arr[i]=arr[mindex];
arr[mindex]=temp;
iter++;
}
cout<<"No. of iterations: "<<iter<<endl;
cout<<"No. of comparisons: "<<count<<endl;
OUPTUT:
2;-Perform bubble sort on the same list and analyze the change in time complexity and
number of comparisons required.
CODE:
void bubblesort(int v[], int size){
int count=0;
for(int i=0;i<size-1;i++){
for(int j=0;j<size-1-i;j++){
count++;
if(v[j]>v[j+1]){
int temp=v[j];
v[j]=v[j+1];
v[j+1]=temp;
}
}
}
cout<<"No. of comparisons: "<<count<<endl;
}
OUTPUT:
3:-Implement Insertion sort algorithm to sort the above list and analyze the change in time
complexity and number of comparisons required.
CODE:
void insertionsort(int v[], int size){
int count=0;
for(int i=1;i<size;i++){
int j=i-1;
count++;
while(j>=0 and v[j]>v[j+1]){
count++;
int temp = v[j];
v[j] = v[j+1];
v[j+1]=temp;
j--;
}
}
cout<<"No. of comparisons: "<<count<<endl;
}
OUTPUT:
4:-Given two sorted sub-halves of the list 7, 8, 18, 27, 56 and 1, 4, 9, 31, 81 implement the
process of merging two sorted lists in linear time.
CODE:
void merge(int arr1[], int arr2[], int mergearr[], int s1, int s2, int s3){
int k=0;
int i=0;
int j=0;
while(k<s3){
if(i<s1 and j<s2){
if(arr1[i]<=arr2[j]){
mergearr[k]=arr1[i];
i++;
}
else{
mergearr[k]=arr2[j];
j++;
}
}
else if(i<s1){
mergearr[k]=arr1[i];
i++;
}
else if(j<s2){
mergearr[k]=arr2[j];
j++;
}
k++;
}
}
OUTPUT:
OUTPUT: