[英]How to use binary search of a sorted list and then count the comparisons
我試圖使用我的排序列表,並通過二進制搜索實現它。 然后,我想計算找到關鍵字所需的比較次數。 我的代碼是:
public class BinarySearch {
private static int comparisions = 0;
public static void main(String[] args) {
int [] list = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
int i = BinarySearch.BinSearch(list, 20);
System.out.println(comparisions);
}
public static int BinSearch(int[] list, int key) {
int low = 0;
int high = list.length - 1;
int mid = (high + low) / 2;
if (key < list[mid]) {
high = mid - 1;
comparisions++;
} else if (key == list[mid]) {
return mid;
comparisions++;
} else {
low = mid + 1;
comparisions++;
}
return -1;
}
}
到目前為止,無論鍵是多少,它只給我1作為比較。
您的代碼缺少搜索的循環部分,可以使用遞歸或使用while
循環來完成循環。 在這兩種情況下,您都必須問自己是否是否只想知道計數或實際返回比較計數。 由於您的方法現在返回索引,因此無法輕松同時返回比較計數。 為此,您需要返回兩個整數的數組或自定義class IndexAndComparisonCount { ... }
。
如果您使用遞歸方法,則每次進行比較時都需要遞增,並且在執行遞歸調用時,您需要獲取該遞歸調用的返回值,並增加compareCount,將調用計數返回1:
if (... < ...) {
IndexAndComparisonCount ret = BinSearch(...);
ret.comparisonCount += 1;
return ret;
} else if (... > ...) {
IndexAndComparisonCount ret = BinSearch(...);
ret.comparisonCount += 2; // since you did compare twice already
return ret;
} else {
return new IndexAndComparisonCount(mid, 2); // you compared twice as well
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.