封裝成類:
package com.roc.algorithms.search;
/**
* 二分法查找
*
* @author imroc
*/
public class BinarySearch {
/**
* @param a 升序排列的數(shù)組
* @param k 待查找的整數(shù)
* @return 如果查到有就返回對應角標衩藤,沒有就返回-1
*/
public static int search(int[] a, int k) {
int lo = 0, hi = a.length - 1;
while (lo <= hi) {
int m = (lo + hi) >> 1;
if (a[m] < k) {
lo = m + 1;
} else if (a[m] > k) {
hi = m - 1;
} else {
return m;
}
}
return -1;
}
}
測試:
int[] a = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
System.out.println(BinarySearch.search(a, 6));
輸出:
6