I am writing a binary search algorithm, maybe a curve, but don't judge, please, this is not the question.

int binarySearch(int a[], int value, int start, int end) { int rHalf = (end - start) / 2 + start; int lHalf = rHalf + 1; printf("\n\n%d-%d %d-%d\n", start, rHalf, lHalf, end); if (start == rHalf && value == a[start]) { printf("start == rHalf = %d, value = %d\n", start, a[start]); return start; } else if (end == lHalf && value == a[end]) { printf("end == lHalf = %d, value = %d\n", end, a[end]); return end; } else if (value <= a[rHalf]) { binarySearch(a,value,start,rHalf); } else if (value >= a[lHalf]) { binarySearch(a,value,lHalf,end); } return -1; } 

The type of the return value int , int actually return and return.

But for some reason, even in the case when one of the first two switches works, the function returns -1 , if I remove the last line, I get a warning at the compilation stage and the function returns 0 as a result of one of the first two switches.

Basically, I write in Java and there the function returns control to the code immediately after the return command, here, as I understand it, even after an explicit call to return , the function continues to the deadline.

I would like to know why this is happening and how it can be circumvented?

UPDATE

Obviously I asked the question vaguely.

I generate an array using rand() - length and components, sort it and run the search. It looks like this:

 init(); printArr(array, size); mergesort(array, 1, size); printArr(array, size); int searchValue = rand() % MAX_VALUE; printf("\nSearch value = %d\n", searchValue); printf("\nSearch value = %d\n", searchValue); printf("\nindex = %d\n", binarySearch(array, searchValue, 0, size)); 

I think the code does not need comments, everything is pretty transparent. The fact is that as a result of the execution, I see the following in the console:

 end == lHalf = 10, value = 55 

The second switch is triggered - respectively, the return end must be executed, which means I should see index = 10 in the console, but this is displayed:

 index = -1 

that is, control is not transferred to the code after the return end , but after return -1 .

  • you have a warning because the compiler assumes that someday none of the iphs will work - strangeqargo
  • No, after return immediately exit. - pavel
  • "... here, as I understood ...". You misunderstood. And about the main question - put a breakpoint and see what, from where and where. The situation will become clearer. - s8am 6:26 pm

1 answer 1

 } else if (value <= a[rHalf]) { binarySearch(a,value,start,rHalf); 

Here you recursively call binarySearch , but do not return its value , but return -1, since execution continues after this call.

Write

 return binarySearch(a,value,start,rHalf); 
  • Thank you very much, the most obvious mistakes always elude one) - iamthevoid