Arrays.binarySearch用法


int[] a = new int[]{128,129};
       int pos = Arrays.binarySearch(a,128);
       System.out.println("Pos="+pos);
       pos =  Arrays.binarySearch(a,129);
       System.out.println("Pos="+pos);
      
       int[] b = new int[]{129,128};
        pos = Arrays.binarySearch(b,128);
       System.out.println("Pos="+pos);
       pos =  Arrays.binarySearch(b,129);
       System.out.println("Pos="+pos);
執行結果爲:
Pos=0
Pos=1
Pos=-1
Pos=0

使用二進制搜索算法來搜索指定的 int 型數組,以獲得指定的值。必須在進行此調用之前對數組進行排序(sort 方法)。如果沒有對數組進行排序,則結果是不明確的。如果數組包含多個帶有指定值的元素,則無法保證找到的是哪一個。


binarySearch()方法提供了多種重載形式,用於滿足各種類型數組的查找需要,binarySearch()有兩種參數類型


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


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


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


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


eg:




package Number;
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);(特列)


eg:




package Number;
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
*/



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章