I am trying to create a recursive binary search function in C. I think I have it, but when I try to compile, I get the error "expected primary-expression before ']' token" for both recursive calls. Does anyone know why this is occurring?
My function:
int binSearch(int val, int a[], int size)
{
int mid;
mid=(size)/2;
if(val==a[mid]) return a[mid];
else if(val<a[mid]) {
return binSearch(val, a[], (size-mid));
}
else if(val>a[mid]) {
return binSearch(val, a[], size);
}
else return(-1);
}
Where a[] is the sorted array, size is the size of the array, and val is the value being searched for.
a, nota[]. Or you could usebsearchfrom the standard library.binSearch(int val, int a[], int lo, int hi), so that you can recurse and search the correct sub-range of the array. Just passing a single number means that you'll always be searching0..size, even if the value can only be found in the upper half of the array.