温馨提示×

java折半查找法怎么实现

小亿
77
2023-11-06 18:09:53
栏目: 编程语言

折半查找法(二分查找法)是一种查找有序数组中特定元素的算法。以下是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。

0