public static int binarySearch(int[] numbers, int target) {
int min = 0;
int max = numbers.length – 1;
while (min <= max) {
int mid = (max + min) / 2;
if (numbers[mid] == target) {
return mid; // found it!
} else if (numbers[mid] < target) {
min = mid + 1; // too small
} else {
// numbers[mid] > target max = mid – 1; // too large
}
}
// not found
return –1;
}
为什么数组减1?
最佳答案
我真的不确定你所说的“一行”指的是什么,所以我只会解释每一行。
public static int binarySearch(int[] numbers, int target) {
int min = 0; //sets the starting search point for the binary search because array slots
//start at 0.
int max = numbers.length – 1; //sets the maximum length for the binary search.
while (min <= max) { //ensures that the binary search completes itself.
int mid = (max + min) / 2; //every loop, binarySearch finds the exact middle
if (numbers[mid] == target) { //if the middle number of the array is the target number....
return mid; // found it! //returns the slot value where mid target was found
else if (numbers[mid] < target) { //if the middle number is less than
//the target number
min = mid + 1; // too small //value of the minimum is equal to the middle value
//plus one. This will essentially cut the array "in half," making the sorting process
//much quicker.
} else {
// numbers[mid] > target max = mid – 1; // too large //does the opposite of what
}
}
// not found
return –1; //no slot value found for the target number.
}
我希望这有帮助。
关于java - 二分查找算法包含一行我不明白的内容,有人可以帮我解释一下吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49784931/