本文介紹了二分搜索條件的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我總是對二進制搜索算法的條件感到困惑,它花費了我在編程比賽中的大量時間。我的問題是什么時候使用這些條件?
1.while (low < high)
2.while (high - low > 1)
3.while (low <= high)
low
=解決方案集中的最低值。
high
=解決方案集中的最大值。
推薦答案
while (low < high)
在搜索范圍[low, high)
時使用。更新high
時,請使用high = mid
。更新low
時,請使用low = mid + 1
。while (high - low > 1)
在搜索范圍(low, high)
時使用。更新high
時,請使用high = mid
。更新low
時,請使用low = mid
。while (low <= high)
在搜索范圍[low, high]
時使用。更新high
時,請使用high = mid - 1
。更新low
時,請使用low = mid + 1
。
代碼如下:
public class BinarySearch {
public static void main(String[] args) {
Integer[] nums = { 4, 9, 12, 18, 20, 26, 28, 29, 55 };
for (int i = 0; i < nums.length; ++i) {
System.out.println(binarySearch1(nums, nums[i]));
System.out.println(binarySearch2(nums, nums[i]));
System.out.println(binarySearch3(nums, nums[i]));
}
}
public static <T extends Comparable<T>> int binarySearch1(T[] array, T value) {
final int NOT_FOUND = -1;
int low = 0;
int high = array.length;
while (low < high) {
int mid = low + (high - low) / 2;
int comparison = array[mid].compareTo(value);
if (comparison == 0) {
return mid;
} else if (comparison > 0) {
high = mid;
} else {
low = mid + 1;
}
}
return NOT_FOUND;
}
public static <T extends Comparable<T>> int binarySearch2(T[] array, T value) {
final int NOT_FOUND = -1;
int low = -1;
int high = array.length;
while (high - low > 1) {
int mid = low + (high - low) / 2;
int comparison = array[mid].compareTo(value);
if (comparison == 0) {
return mid;
} else if (comparison > 0) {
high = mid;
} else {
low = mid;
}
}
return NOT_FOUND;
}
public static <T extends Comparable<T>> int binarySearch3(T[] array, T value) {
final int NOT_FOUND = -1;
int low = 0;
int high = array.length - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
int comparison = array[mid].compareTo(value);
if (comparison == 0) {
return mid;
} else if (comparison > 0) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return NOT_FOUND;
}
}
這篇關于二分搜索條件的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,