Java集合中二分查找算法实现


Java集合中二分查找算法实现

Arrays.binarySearch实现了对有序数组特定区间的二分查找,虽然我们觉得很简单,但是阅读源码的确能看到实现这些库的优秀技巧,总是在追求完美和高效。
值得学习的地方有:
(1)边界检查;
(2)求中位数的时候使用位移操作,而不是 x/2;
(3)如果查找的元素不在数组中,通过返回值昭示了应该插入的位置,而不是直接返回-1;

public static int binarySearch(int[] a, int fromIndex, int toIndex,
                                   int key) {
        rangeCheck(a.length, fromIndex, toIndex);
        return binarySearch0(a, fromIndex, toIndex, key);
    }

    // Like public version, but without range checks.
    private static int binarySearch0(int[] a, int fromIndex, int toIndex,
                                     int key) {
        int low = fromIndex;
        int high = toIndex - 1;

        while (low <= high) {
            int mid = (low + high) >>> 1;
            int midVal = a[mid];

            if (midVal < key)
                low = mid + 1;
            else if (midVal > key)
                high = mid - 1;
            else
                return mid; // key found
        }
        return -(low + 1);  // key not found.
    }
 
同样在Collections里面同样有类似的辅助函数,不过是利用迭代器取得特定位置的元素。
public static <T>
    int binarySearch(List<? extends Comparable<? super T>> list, T key) {
        if (list instanceof RandomAccess || list.size()< BINARYSEARCH_THRESHOLD)
            return Collections. indexedBinarySearch(list, key);
        else
            return Collections. iteratorBinarySearch(list, key);
    }


private static <T>
    int indexedBinarySearch(List<? extends Comparable<? super T>> list, T key ) {
        int low = 0;
        int high = list.size()-1;

        while (low <= high) {
            int mid = ( low + high) >>> 1;
            Comparable<? super T> midVal = list.get( mid);
            int cmp = midVal.compareTo( key);

            if ( cmp < 0)
                low = mid + 1;
            else if ( cmp > 0)
                high = mid - 1;
            else
                return mid; // key found
        }
        return -(low + 1);  // key not found
    }

    private static <T>
    int iteratorBinarySearch(List<? extends Comparable<? super T>> list, T key )
    {
        int low = 0;
        int high = list.size()-1;
        ListIterator<? extends Comparable<? super T>> i = list.listIterator();

        while (low <= high) {
            int mid = ( low + high) >>> 1;
            Comparable<? super T> midVal = get(i , mid );
            int cmp = midVal.compareTo( key);

            if ( cmp < 0)
                low = mid + 1;
            else if ( cmp > 0)
                high = mid - 1;
            else
                return mid; // key found
        }
        return -(low + 1);  // key not found
    }

 /**
     * Gets the ith element from the given list by repositioning the specified
     * list listIterator.
     */
    private static <T> T get(ListIterator<? extends T> i, int index) {
        T obj = null;
        int pos = i.nextIndex();
        if (pos <= index) {
            do {
                obj = i.next();//链表移动
            } while ( pos++ < index);
        } else {
            do {
                obj = i.previous();
            } while (-- pos > index);
        }
        return obj;
    }


    




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 下面是一个Java二分查找排序代码实现: ```java public class BinarySearch { public static int binarySearch(int[] arr, int key) { int low = 0; int high = arr.length - 1; while (low <= high) { int mid = (low + high) / 2; if (arr[mid] == key) { return mid; } else if (arr[mid] < key) { low = mid + 1; } else { high = mid - 1; } } return -1; } public static void main(String[] args) { int[] arr = {2, 5, 7, 8, 10, 12}; int key = 8; int index = binarySearch(arr, key); if (index == -1) { System.out.println("元素未找到!"); } else { System.out.println("元素在数组的位置为:" + index); } } } ``` 这里 `binarySearch` 方法实现二分查找算法,它接受一个已经排好序的数组 `arr` 和要查找的关键字 `key` 作为参数。函数返回关键字在数组的索引位置,如果未找到则返回 -1。 在 `main` 函数,我们定义了一个数组 `arr` 和一个要查找的关键字 `key`,然后调用 `binarySearch` 方法来查找关键字在数组的位置。如果找到了,就输出它在数组的位置,否则输出 "元素未找到!"。 ### 回答2: 二分查找(Binary Search)也叫折半查找,是一种高效的查找算法。它的前提是待查找集合必须是有序的。下面是用Java写一个二分查找排序的代码示例: ```java public class BinarySearch { // 二分查找算法 public static int binarySearch(int[] array, int target) { int low = 0; int high = array.length - 1; while (low <= high) { int mid = (low + high) / 2; if (array[mid] == target) { return mid; // 找到目标元素,返回索引 } else if (array[mid] < target) { low = mid + 1; // 目标元素在右半部分,更新low } else { high = mid - 1; // 目标元素在左半部分,更新high } } return -1; // 未找到目标元素,返回-1 } public static void main(String[] args) { int[] array = { 1, 3, 5, 7, 9, 11 }; // 有序数组 int target = 7; // 目标元素 int index = binarySearch(array, target); if (index != -1) { System.out.println("目标元素" + target + "在数组的索引为" + index); } else { System.out.println("目标元素" + target + "未在数组找到"); } } } ``` 以上代码定义了一个名为`BinarySearch`的类,其包含了一个静态方法`binarySearch`来实现二分查找算法。在`main`方法,创建了一个有序数组`array`,并指定要查找的目标元素为7。通过调用`binarySearch`方法,返回目标元素在数组的索引。最后根据返回的索引结果输出查找结果。 以上就是一个用Java实现二分查找算法的例子,通过该算法可以高效地查找有序数组的元素。 ### 回答3: 二分查找(Binary Search)是一种查找算法,思路是将有序数组分成两部分,通过每次查找间元素与目标值比较的方式来不断缩小查找范围,最终找到目标值或确定其不存在。 以下是用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) / 2; if (arr[mid] == target) { return mid; } else if (arr[mid] < target) { left = mid + 1; } else { right = mid - 1; } } return -1; } public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5, 6}; int target = 4; int index = binarySearch(arr, target); if (index != -1) { System.out.println("目标值 " + target + " 的索引为 " + index); } else { System.out.println("目标值 " + target + " 不存在于数组"); } } } ``` 在上述代码,binarySearch方法使用了迭代的方式来实现二分查找。初始时,left指向数组的第一个元素,right指向数组的最后一个元素。通过计算间元素的索引mid,将查找范围不断缩小。如果间元素等于目标值,则返回该元素的索引;如果间元素小于目标值,则在右侧继续查找;如果间元素大于目标值,则在左侧继续查找。重复这个过程直到找到目标值或确定其不存在。 在主方法,创建了一个有序数组arr和目标值target,并调用binarySearch方法来查找目标值在数组的索引。如果返回的索引不为-1,则表示目标值存在于数组,打印输出目标值和其对应的索引;否则,表示目标值不存在于数组,打印输出该信息。 以上就是用Java实现二分查找排序的代码。该算法的时间复杂度为O(log n),其n为数组的长度。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值