1.1.22
题目里有这样一句话:“打印出它的参数lo和hi并按照递归的深度缩进”
我的理解:首先明确每调用一次递归就打印一次lo和hi,
对于后半句话我认为应该是随着递归的深度加深,
每次打印参数前的空白缩进需要加长。
下面是代码:
import edu.princeton.cs.algs4.*;
public class Main {
public static void main(String[] args) {
int [] test = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int location = rank(9,test);
System.out.print("The key is located in " + location);
}//close main
public static int rank(int key, int [] a){
int count = 0;
return rank(key, a, 0, a.length,count);
}//method binary search
public static int rank(int key, int[] a, int lo, int hi, int count){
int mid = (int) (hi + lo) /2;
count++;
for (int i = 0;i < count-1; i++) System.out.print(" ");
System.out.println("lo: "+lo+" hi: "+hi);
if(lo > hi) return -1;
if(a[mid] < key) return rank(key,a,mid,hi,count);
if(a[mid] > key) return rank(key,a,lo,mid,count);
return mid;
}
}
输出:
lo: 0 hi: 11
lo: 5 hi: 11
lo: 8 hi: 11
The key is located in 9
解析:
按照题目的提示(为递归方法添加一个参数来保存递归的深度),所以我为递归方法添加了整型变量count,每次调用都加1。
然后将count用于打印参数前进行空白打印。