[英]Prolem with binary search algorithm
最近,我研究了算法,但是發現一個可怕的問題,我無法通過鏈接中的BinarySearch算法找到數字: http : //algs4.cs.princeton.edu/11model/BinarySearch.java.html
public class BinaryFind {
public static int indexOf(int[] a, int key) {
int lo = 0;
int hi = a.length - 1;
while (lo <= hi) {
// Key is in a[lo..hi] or not present.
int mid = lo + (hi - lo) / 2;
if (key < a[mid]) hi = mid - 1;
else if (key > a[mid]) lo = mid + 1;
else return mid;
}
return -1;
}
public static void main(String[] args) {
int[] a = {1, 4, 56, 4, 3, 7, 8, 2, 66, 45};
System.out.print(indexOf(a, 7));
}
}
為什么我找不到數字7?
結果:
要搜索的數組必須進行排序以使用二進制搜索。
嘗試這個:
public static void main(String[] args) {
int[] a = {1, 4, 56, 4, 3, 7, 8, 2, 66, 45};
// sort the array
for (int i = a.length - 1; i > 0; i--) {
for (int j = 0; j < i; j++) {
if (a[j] > a[j + 1]) {
int t = a[j];
a[j] = a[j + 1];
a[j + 1] = t;
}
}
}
System.out.print(indexOf(a, 7));
}
將此行添加到indexOf(..)方法的頂部。
Arrays.sort(a);
這將對您的輸入數組進行排序,然后您可以繼續查找索引。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.