java實現的二分法查詢

metrowilliam發表於2011-11-03
package com.gui.erfen;

public class erfenSearch {

/**
* 二分查詢
*/
public static void main(String[] args) {
int[] a = new int[] { 3, 11, 34, 56, 72, 88, 90, 110 };
int oneTarget = 72;
int twoTarget = 50;
int oneResult = buggyBinarySearch(a, oneTarget);
int twoResult = buggyBinarySearch(a, twoTarget);
System.out.println("要查詢的元素" + oneTarget + "在陣列中的下標為:" + oneResult);
System.out.println("要查詢的元素" + twoTarget + "在陣列中的下標為:" + twoResult
+ (twoResult == -1 ? ",該元素在陣列中不存在" : ""));
}

public static int buggyBinarySearch(int[] a, int target) {
// 進行二分法查詢的前提是數字已經排好序的,並且升序。
int low = 0;
int high = a.length - 1;

while (low <= high) {
int mid = (low + high) / 2;// 存在經典的bug
int midVal = a[mid];

if (midVal < target)
low = mid + 1;
else if (midVal > target)
high = mid - 1;
else
return mid;
}
return -1;
}
}

相關文章