简书 賈小強
转载请注明原创出处,谢谢!
package com.lab1.test3;
public class BinarySearch1 {
public static void main(String[] args) {
int[] a = { 1, 2, 3, 4, 5 };
int key = 3;
System.out.println(BinarySearch1.indexOf(key, a));
}
private static int indexOf(int key, int[] a) {
int lo = 0;
int hi = a.length - 1;
while (lo <= hi) {
int mid = hi = lo + (hi - lo) / 2;
if (key < a[mid]) {
hi = mid - 1;
} else if (key > a[mid]) {
lo = mid + 1;
} else {
return mid;
}
}
return -1;
}
}
输出
2
Happy learning !!