I've made a program to find the missing element (if there's one) in a sequential list:
Program criteria:
Returns
-1
if a list is sequential, otherwise the missing element in a non-sequential list is returned.To perform binary search, we need a key to half the problem size. Here the key is to find the distance between the index (
low
,high
) and their corresponding values.Compilation procedure:
gcc -Wall -g testList.c -o testList ./testList
#include<stdio.h>
int bSearch(int array[], int low, int high){
int mid = (low + high) / 2;
if(high == low + 1){
if(array[high] > array[low] +1){
return array[low] +1;
}else{
return -1;
}
}
if(array[mid] - array[low] == mid - low){
return bSearch(array, mid, high);
}else if(array[mid] - array[low] > mid - low){
return bSearch(array, low, mid);
}else{
return -1;
}
}
int main(void){
int array [] = {22, 23, 24, 25, 26, 27, 28, 30};
int upperBound = (sizeof(array)/sizeof(array[0]))-1;
printf("%d\n", bSearch(array, 0, upperBound));
return 0;
}
My questions:
Why does removing the
else{}
case cause the compiler to give a warning for it?Can the base case look more elegant?
For code elegance and optimization, can this code be improved?
1 Answer 1
Why does removing the
else{}
case cause the compiler to give a warning for it?
The compiler will indeed issue a warning if a value-returning function doesn't return a value for every path. Ignoring this warning could then cause undefined behavior.
If you intend for bSearch()
to return -1
on failure, then you can put just one return -1;
at the very end of the function and remove the else
s that return -1
.
-
\$\begingroup\$ My point is, What is the chance that you get to very end? Do you think there is a chance? Give me a case where we can get to very end \$\endgroup\$overexchange– overexchange2016年12月26日 22:08:08 +00:00Commented Dec 26, 2016 at 22:08
-
\$\begingroup\$ @overexchange: What I'm saying is that it's a possible alternative for having those
else
s. Otherwise, you can keep what you already have. \$\endgroup\$Jamal– Jamal2016年12月26日 22:09:36 +00:00Commented Dec 26, 2016 at 22:09 -
2\$\begingroup\$ Even if there is no way to get to the very end, you can't prove that to the compiler. \$\endgroup\$Denis– Denis2016年12月26日 22:10:35 +00:00Commented Dec 26, 2016 at 22:10
else{}
will cause error because not all method paths return value. \$\endgroup\$else
are you asking about? Posting sample code without theelse
would help clarify the question. \$\endgroup\$else
working withelse if
\$\endgroup\$