please i have a question about the Iterative implementation of Binary Search
This is the function i create in c:
int BinarySearch(int arr[], int l, int r, int x)
{
while(l <= r) {
int mid = l + (r - l) / 2;
if(arr[mid] == x)
return mid;
if(arr[mid] > x)
r = mid - 1;
else
l = mid + 1;
}
return -1;
}
This is my main function :
int main()
{
int arr[] = {1,2,3,5,16,15,20};
int n = sizeof(arr) / sizeof(arr[0]);
int x = 16;
int result = BinarySearch(arr, 0, n-1, x);
(result == -1)
// WE CALL THIS ternary operator.
? printf("Element is not present in array")
: printf("Element is present at index %d", result);
return 0;
}
The question is: when i search 16 the function return -1.
If you see the number 16 is on the list any help please ??