java折半查找法怎么实现

32次阅读
没有评论

共计 803 个字符,预计需要花费 3 分钟才能阅读完成。

折半查找法(二分查找法)是一种查找有序数组中特定元素的算法。以下是 Java 实现折半查找法的示例代码:

public class BinarySearch {public static int binarySearch(int[] arr, int target) {int left = 0;
        int right = arr.length - 1;

        while (left <= right) {int mid = left + (right - left) / 2;

            if (arr[mid] == target) {return mid;
            }

            if (arr[mid] < target) {left = mid + 1;
            } else {right = mid - 1;
            }
        }

        return -1;
    }

    public static void main(String[] args) {int[] arr = {1, 3, 5, 7, 9, 11};
        int target = 7;
        int index = binarySearch(arr, target);

        if (index != -1) {System.out.println(" 元素 " + target + " 在数组中的索引位置为 " + index);
        } else {System.out.println(" 元素 " + target + " 不在数组中 ");
        }
    }
}

在上述代码中,binarySearch 方法接受一个有序数组 arr 和目标元素 target 作为参数,返回目标元素在数组中的索引位置,如果目标元素不在数组中,则返回 -1。

该方法通过设定左边界 left 和右边界 right 来定义查找的范围,然后在循环中计算中间位置 mid,并通过与目标元素的比较来缩小查找范围。如果中间元素等于目标元素,就返回中间位置;如果中间元素小于目标元素,说明目标元素在右半部分,将左边界移动到 mid+1;如果中间元素大于目标元素,说明目标元素在左半部分,将右边界移动到 mid-1。最终,如果找到目标元素,则返回其索引位置,否则返回 -1。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-13发表,共计803字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)