12.10 递归版本
也可以用递归方法实现二分法查找。为此可编写一个将 low 和 high 作为参数的方法,并将第 3 步和第 4 步转换为递归调用。代码类似于下面这样:
public static int binarySearch(Card[] cards, Card target,int low, int high) {if (high < low) {return -1;}int mid = (low + high) / 2; // 第1步int comp = cards[mid].compareTo(target);if (comp == 0) { // 第2步return mid;} else if (comp < 0) { // 第3步return binarySearch(cards, target, mid + 1, high);} else { // 第4步return binarySearch(cards, target, low, mid - 1);}}
这里没有用 while 循环,而是用了一条 if 语句来终止递归。如果 high 小于 low,它们之间就不可能有 Card 对象,因此指定的 Card 对象肯定不在数组中。
编写递归程序时的两种常见错误是:忘记包含基线条件;编写的递归调用导致基线条件根本不可能满足。这两种错误都会导致无限递归,进而引发 StackOverflowException 异常。
