使用 Arrays.binarySearch() ,若發生 "怪怪" 的問題,請先檢查一下,陣列內的元素是否已先做過排序。
根據 Java API 的說明文件,使用 "binarySearch" 方法前,須對陣列先行 "排序" 。 (Ref: The array must be sorted prior to making this call......)
所以,陣列內各元素的值,若未先排序,就直接做 "搜尋" ,很容易就發生 "意外" 囉!
********************** [ Begin ] **********************
binarySearch
public static int binarySearch(int[] a,
int key)
Searches the specified array of ints for the specified value using the binary search algorithm. The array must be sorted (as by the sort(int[]) method) prior to making this call. If it is not sorted, the results are undefined. If the array contains multiple elements with the specified value, there is no guarantee which one will be found.
Parameters:
a - the array to be searched
key - the value to be searched for
Returns:
index of the search key, if it is contained in the array; otherwise, (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the array: the index of the first element greater than the key, or a.length if all elements in the array are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found.
********************** [ End ] **********************
以下用程式碼來示範 Arrays.binarySearch() "錯誤及正確" 的作法。
/********************************************************************
示範程式碼
********************************************************************/
import java.util.Arrays;
public class Array_binarySearch_VV {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("[陣列未先排序,就做搜尋]\n");
CanNotWork();
System.out.println("===========================\n");
System.out.println("[陣列已先排序,再做搜尋]\n");
sortBeforeSearch();
}
/*
* 有問題的寫法
*/
static void CanNotWork() {
int i = 0;
int iSearch = 6;
int iNumbers[] = { 3, 4, 10, 12, 6, 15 };
// 排序前陣列內各元素的值
System.out.println("排序前陣列內各元素的值:");
System.out.println(
Arrays.toString(iNumbers)
);
// 執行 binarySearch,結果找不到
System.out.println("\n搜尋 [" + iSearch + "] 在陣列中的位置?");
i = Arrays.binarySearch(iNumbers,iSearch);
System.out.println("搜尋的結果值:" + i);
}
/*
* 正確的寫法
*/
static void sortBeforeSearch() {
int i = 0;
int iSearch = 6;
int iNumbers[] = { 3, 4, 10, 12, 6, 15 };
// 排序前陣列內各元素的值
System.out.println("排序前陣列內各元素的值:");
System.out.println(
Arrays.toString(iNumbers)
);
// 執行 sort
Arrays.sort(iNumbers);
// 排序後陣列內各元素的值
System.out.println("排序後陣列內各元素的值:");
System.out.println(
Arrays.toString(iNumbers)
);
// 執行 binarySearch,結果找得到
System.out.println("\n搜尋 [" + iSearch + "] 在陣列中的位置?");
i = Arrays.binarySearch(iNumbers,iSearch);
System.out.println("搜尋的結果值:" + i);
}
}
沒有留言:
張貼留言