Suppose that in addition to being sorted, the entries of A are distinct integers. Design an efficient algorithm for finding an index i such that A[i]=i or indicating that no such index exists.
We can apply binary search technique for this too as we are aware that array is sorted and have distinct elements.
Below is the working code in C
#include<stdio.h>
int bsearch(int a[],int size)
{
int low=0;
int up=size-1;
int mid;
while(low <= up) {
mid=(low+up)/2;
if(a[mid]==mid)
return mid;
else if(a[mid]<mid)
low = mid+1;
else
up = mid-1;
}
return -1;
}
int main()
{
int arr[10]={-1,0,2,4,6,8,10,12,14,15};
int pos;
pos=bsearch(arr,10);
if(pos == -1)
printf("element for a[i] == i is not found\n");
else
printf("element for a[i] == i is at location %d\n",pos+1);
return 0;
}
We can apply binary search technique for this too as we are aware that array is sorted and have distinct elements.
Below is the working code in C
#include<stdio.h>
int bsearch(int a[],int size)
{
int low=0;
int up=size-1;
int mid;
while(low <= up) {
mid=(low+up)/2;
if(a[mid]==mid)
return mid;
else if(a[mid]<mid)
low = mid+1;
else
up = mid-1;
}
return -1;
}
int main()
{
int arr[10]={-1,0,2,4,6,8,10,12,14,15};
int pos;
pos=bsearch(arr,10);
if(pos == -1)
printf("element for a[i] == i is not found\n");
else
printf("element for a[i] == i is at location %d\n",pos+1);
return 0;
}
No comments:
Post a Comment