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.
You need to just pass in a
, not a[]
. Like this:
return binSearch(val, a, size);
*
#include<stdio.h>
main()
{
int arr[20],start,end,middle,n,i,item;
printf("How many elements you want to enter in the array : ");
scanf("%d",&n);
for(i=0; i < n; i++)
{
printf("Enter element %d : ",i+1);
scanf("%d",&arr[i]);
}
printf("Enter the element to be searched : ");
scanf("%d",&item);
start=0;
end=n-1;
middle=(start+end)/2;
while(item != arr[middle] && start <= end)
{
if(item > arr[middle])
start=middle+1;
else
end=middle-1;
middle=(start+end)/2;
}
if(item==arr[middle])
printf("%d found at position %d\n",item,middle+1);
if(start>end)
printf("%d not found in array\n",item);
}
*
Your code has a critical bug. When writing such algorithms, you should spend some time to list test cases. To test comprehensively, I'd write a couple loops that would check all the following combinations:
Here's some sample code for a test harness, just to get you started...
int inputs[] = { 10, 20, 30, 40 };
for (int size = 0; size < 4; ++size)
for (int i = 0; i <= size; ++i)
{
assert(binSearch(inputs[i], inputs, size) == (i == 0 ? -1 : i));
assert(binSearch(inputs[i] - 5, inputs, size) == -1);
assert(binSearch(inputs[i] + 5, inputs, size) == -1);
}
Even if you work through a couple such cases in your head you're likely to find the bug.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.