I've been trying to learn how the binary search works, so I searched for a code and tried to understand what each line does. There is this one line that I don't understand. The line with the "return -1". I don't understand what that means. Can someone explain what happens in that line of code?
#include<stdio.h>
int binarySearch(int array[], int size, int searchValue){
int low = 0;
int high = size - 1;
while(low<=high){// is the array exhausted?
int mid = (low + high) / 2; //If not, find the middle index
if(searchValue == array[mid]){
return mid;
}
else if(searchValue > array[mid]){
low = mid + 1;
}
else{
high = mid - 1;
}
}
return -1;
}
int main(){
int array[] = {1,2,3,4,5,6,7};
int searchNum;
printf("Enter an integer:");
scanf("%d", &searchNum);
int result = binarySearch(array,7,searchNum);
if(result>=0){
printf("Found!");
}
else{
printf("Not found!");
}
getch();
}
在数组中执行二进制搜索,并且数组的位置从0开始。因此,如果返回-1,则意味着该位置不在数组中或无法找到。
The while
loop is performed and contains a return statement, if the item you are looking for is in the array, then the return in the while
loop will return the index of the item. The return -1
statement that follows returns to the caller if the item is not found, ie if high>low
, -1 is used to indicate that it is in the array as an index of -1 is outside the bounds of any array. Without the return -1
statement then there would be a compile time error saying that the return statement is missing
When you perform your check
if(result>=0) {
printf("Found!");
} else {
printf("Not found!");
}
If the binary search method finds the item and returns the index(which will be >-1) then "Found! will be printed to the console, else if the binary search method returns a value <0, ie -1 then the item has not been found in the array, and thus Not Found! is printed to the console, your if statement alone can give your binary search a good explantation!
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.