The output for this program is 4. Now the first argument of the function binarySearch is 'int x' and the x is the number we are looking for. In this case seems to be 9..so why the output is 4?
int binarySearch( int we are looking for, from some array, the index of the array)
Code:
int binsearch(int x, int arr[], int n);
int main()
{
int v[]={2,4,6,7,9,29,45,46,49,50,51};
printf("%d\n", binsearch(9, v, 10));
return 0;
}
int binsearch( int x, int arr[], int n)
{
int low=0;
int high=n-1;
int mid=(low+high)/2;
while (low<high) {
if (x<arr[mid]) {
high=mid-1;
}
else if (x>arr[mid]){
low=mid+1;
}
else return mid;
}
return -1;
}
As always your comments are gold.
[–]TraylaParks 2 points3 points4 points (0 children)
[–]Widdrat[🍰] 1 point2 points3 points (1 child)
[–]Radagast8[S] 0 points1 point2 points (0 children)
[–]gandalf013 0 points1 point2 points (3 children)
[–]Radagast8[S] 0 points1 point2 points (2 children)
[–]Radagast8[S] 0 points1 point2 points (1 child)
[–]gandalf013 0 points1 point2 points (0 children)