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