[英]Binary Search implementation via java
請參閱下面的Java源代碼以進行二進制搜索
public class Main {
public static void main(String[] args) {
int[] x = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
int y = binarySearch(x, 11);
System.out.println(y);
}
public static int binarySearch(int[] arr, int value) {
int searchedIndex = -1;
int first = 0;
int last = arr.length - 1;
int mid;
while (first <= last) {
mid = (first + last) / 2;
if (arr[mid] == value) {
searchedIndex = mid;
break;
} else {
if (value < arr[mid]) {
last = mid - 1;
} else {
first = mid + 1;
}
}
}
return searchedIndex;
}
}
int last = arr.length-1是否為-1強制性。 我覺得代碼可以正常工作last = arr.length-1 。 如果是強制性的,請解釋原因。
數組已經有一個方法binarySearch,您可以使用:
int[] x = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
int r = Arrays.binarySearch(x, 11);
在一種非常特殊的情況下,需要-1
:當您搜索的值大於數組中的最大值時。 例如,使用
int y = binarySearch(x, 50);
將拋出ArrayOutOfBounds異常。 這是因為mid
最終將等於last
,並且如果沒有-1
, last
將超過數組的末尾。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.