使用1.1.64节中的rank()递归方法重新实现BinaraySearch并跟踪该方法的调用。每当该方法被调用时,打印出它的参数lo和hi并接照递归的深度缩进。提示:为递归方法添加一个参数来保存递归的深度。
代码:
public class Main {
public static int rank(int[] a, int t, int lo, int hi, int depth){
while (lo <= hi){
for (int i = 0; i < depth; i ++){
System.out.print(" ");
}
System.out.println(lo+","+hi);
int mid = lo + (hi-lo)/2;
if (a[mid] < t){
lo = mid+1;
}else if (a[mid]>t){
hi = mid-1;
}else{
return mid;
}
depth++;
}
return -1;
}
public static void rank(int[] a, int key){
int index = rank(a,key, 0, a.length-1, 0);
if (index == -1){
System.out.println("没有找到");
}else{
System.out.println("序号为:"+index);
}
}
public static void main(String[] args) {
int[] a = { 1, 2, 3, 4, 6, 7, 8, 9, 12 };
int key = 5;
rank(a, key);
}
}
结果
0,8
0,3
2,3
3,3
没有找到
知识点–二分查找