1. 程式人生 > >JAVA之陣列查詢binarySearch()方法詳解

JAVA之陣列查詢binarySearch()方法詳解

binarySearch()方法提供了多種過載形式,用於滿足各種型別陣列的查詢需要,binarySearch()有兩種引數型別

注:此法為二分搜尋法,故查詢前需要用sort()方法將陣列排序,如果陣列沒有排序,則結果是不確定的,另外

如果陣列中含有多個指定值的元素,則無法保證找到的是哪一個。

⑴.binarySearch(object[ ], object key);

如果key在陣列中,則返回搜尋值的索引;否則返回-1或者”-“(插入點)。插入點是索引鍵將要插入陣列的那一點,即第一個大於該鍵的元素索引。

import java.util.Arrays;
public class IntFunction
{
    public
static void main (String []args) { int a[] = new int[] {1, 3, 4, 6, 8, 9}; int x1 = Arrays.binarySearch(a, 5); int x2 = Arrays.binarySearch(a, 4); int x3 = Arrays.binarySearch(a, 0); int x4 = Arrays.binarySearch(a, 10); System.out.println("x1:" + x1 + ", x2:"
+ x2); System.out.println("x3:" + x3 + ", x4:" + x4); } } /*輸出結果: x1:-4, x2:2 x3:-1, x4:-7 */

1.不存在時由1開始計數;
2.存在時由0開始計數。

⑵.binarySearch(object[ ], int fromIndex, int endIndex, object key);

如果要搜尋的元素key在指定的範圍內,則返回搜尋鍵的索引;否則返回-1或者”-“(插入點)。

eg:

1.該搜尋鍵在範圍內,但不在陣列中,由1開始計數;

2.該搜尋鍵在範圍內,且在陣列中,由0開始計數;

3.該搜尋鍵不在範圍內,且小於範圍內元素,由1開始計數;

4.該搜尋鍵不在範圍內,且大於範圍內元素,返回-(endIndex + 1);(特列)

import java.util.Arrays;
public class IntFunction
{
    public static void main (String []args)
    {
        int a[] = new int[] {1, 3, 4, 6, 8, 9};
        int x1 = Arrays.binarySearch(a, 1, 4, 5);
        int x2 = Arrays.binarySearch(a, 1, 4, 4);
        int x3 = Arrays.binarySearch(a, 1, 4, 2);
        int x4 = Arrays.binarySearch(a, 1, 3, 10);
        System.out.println("x1:" + x1 + ", x2:" + x2);
        System.out.println("x3:" + x3 + ", x4:" + x4);
    }
}
/*輸出結果:
x1:-4, x2:2
x3:-2, x4:-4
*/