java - 二分查找算法包含一行我不明白的内容,有人可以帮我解释一下吗?

标签 java binary-search

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/

相关文章:

java - 如何将 SQL 查询转换为 Lambda 或 Stream (Java 8)?

java - 将 Random 对象作为参数传递时出现问题

java - Maven不下载依赖项: "The repository system is offline"

java - Twitter 连接的最佳 Java 示例

java - 循环内二分查找的时间复杂度

c - c中删除二叉树根节点的迭代方法

python - 使用递归的函数的二进制搜索根

java - Arrays.binarySearch() 如何在不排序的情况下工作

java - 什么时候接口(interface)中的方法被 'both'覆盖并实现?

javascript - javascript中重复的数组中的子字符串二分搜索