I wrote this shortcode to find element x location in a sorted array (from high to low) with complexity O(log n). n and arr represent the edges of the array.
However, it doesn't seem to work properly. Any suggestions?
int ex2_1(int *arr, int n, int key)
{
if (n == 0)
return -1;
if (arr[n / 2] == key)
return n / 2;
if (arr[n / 2] > key)
return ex2_1(arr + n / 2 + 1, n - n / 2 - 1, key);
return ex2_1(arr, n / 2, key);
}
for int arr[] = { 9, 7, 7, 5, 3, 3, 3, 1 };, int n = 8 and int key = 3, I get 4 when I should get 5.