在做數(shù)組查詢的過程中,我們有時候會遇到一些問題,下面就跟隨作者一起解答這些問題。
Arrays 類的 binarySearch() 方法,可使用二分搜索法來搜尋指定數(shù)組,以獲得指定對象。該方法返回要搜索元素的索引值。 binarySearch()方法提供了多種重載形式,用于滿足各種類型數(shù)組的查找需要。 binarySearch()方法有兩種參數(shù)類型。
(1)binarySearch(Object[] a.Object key) 其中a 代表要所搜的數(shù)組,key 表示要搜索的值。如果key 包含在數(shù)組中,則返回搜索值的索引;否則返回-1或“-”(插入點)。插入點是搜索鍵將要插入數(shù)組的那一點,即第一個大于此鍵的元素索引。這里為什么有 index 的值為負數(shù),大家一定要注意理解。
例1:查詢數(shù)組元素,實例代碼如下:
1
2
3
|
int arr[] = new int [] { 4 , 25 , 10 }; //創(chuàng)建并初始化數(shù)組 Arrays.sort(arr); //將數(shù)組進行排序 int index = Arrays.binarySearch(arr, 0 , 1 , 8 ); |
上面的代碼中變量 index 的值是元素“8”在索引0~1內(nèi)的索引位置。由于在指定的范圍內(nèi)并不存在元素“8”,Index的值是“-”。如果對數(shù)組進行排序,元素“8”應該在25的前面,因此插入點應該是元素25的索引值2,所以index 的值為-2。
例2:實現(xiàn)查找元素 4 在數(shù)組中的索引位置。代碼:
1
2
3
4
5
6
7
8
9
10
|
import java.util.Arrays; public class Example { public static void main(String[] args) { int ia[] = new int [] { 3 , 8 , 9 , 4 , 1 }; Arrays.sort(ia); int index = Arrays.binarySearch(ia, 4 ); System.out.println( "4 的索引位置是:" +index); } } |
運行結果為:4 的索引位置是:2
(2) binarySearch(Object[].a,int fromIndex,int toIndex,Object key) 該方法在指定的范圍內(nèi)檢索某一元素。a:要進行檢索的數(shù)組;fromIndex:指定范圍的開始處索引(包含);toIndex:指定范圍的結束處索引(不包含);key:要搜索的元素。在使用該方法前同樣要對數(shù)組進行排序,來獲得準確的索引值。
例3:實現(xiàn)查找元素“77”在指定范圍的數(shù)組str 中的索引位置。代碼如下:
1
2
3
4
5
6
7
8
9
10
|
import java.util.Arrays; public class Pakel { public static void main(String[] args) { String str[] = new String[] { "99" , "88" , "77" , "66" }; Arrays.sort(str); int index = Arrays.binarySearch(str, 0 , 2 , "77" ); System.out.println(index); } } |
運行結果為:1
注意:如果指定的范圍大于或等于數(shù)組的長度,則會報出 ArrayIndexOutOfBoundsException 異常。
如有疑問請留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!