I’m trying to make a divide and conquer version of binary search, but one that divides the array to two subarrays and search similar to merging in merge sort, the reason I want to do that becuase I want to use it in cilk, but I have to make it that way.
Here is the code I wrote, which seems to have something wrong with it as its returning -1 to valid key values.
#include <stdio.h>
#include "BinarySearch.h"
int main () {
int a[] = {0,1,2,3,4,5,6,7,8,9};
int index = binarySearch(a, 0, 9, 7);
printf("%i", index);
return 0;
}
int binarySearch (int* A, int first, int last, int key) {
if (last < first)
return -1;
else {
int mid = (last + first) / 2;
if (A[mid] == key)
return mid;
int x, y;
x = binarySearch(A, first, mid - 1, key);
y = binarySearch(A, mid + 1, last, key);
if (x == -1 && y == -1)
return -1;
else if (x == -1 && y != -1)
return y;
else
return x;
}
}
It’s simple,
99doesn’t exist in your array. The result is correct. You probably just messed up the parameters – the first one is the array, the next two represent the range of the search, the fourth one is what you’re looking for. A correct call would be:Also, this
is useless, you can simply use
aas arrays decay to pointers:Also – a binary search takes into account the fact that the array is sorted. If your key is lower than the middle value, why bother searching to the right – it’s guaranteed you won’t find it there.
What you’re doing is
O(n), as opposed to aO(log(n))binary search solution.