我一直在利用我的大学时间通过编码算法练习 Java。我编码的算法之一是二进制搜索:
public class BinarySearch {
private static int list[] = {3, 6, 7, 8, 9, 10};
public static void main(String[] args) {
BinarySearch b = new BinarySearch();
b.binarySearch(list);
}
public void binarySearch(int[] args) {
System.out.println("Binary search.");
int upperBound = args.length;
int lowerBound = 1;
int midpoint = (upperBound + lowerBound) / 2;
int difference = upperBound - lowerBound;
int search = 7;
for (int i = 0; i < args.length; i++) {
if (search < args[midpoint - 1] && difference != 1) {
upperBound = midpoint - 1;
midpoint = upperBound / 2;
} else if (search > args[midpoint - 1] && difference != 1) {
lowerBound = midpoint + 1;
midpoint = (lowerBound + upperBound) / 2;
} else if (search == args[midpoint - 1]) {
midpoint = midpoint - 1;
System.out.println("We found " + search + " at position " + midpoint + " in the list.");
i = args.length;
} else {
System.out.println("We couldn't find " + search + " in the list.");
i = args.length;
}
}
}
}
我真的希望能够编写一个更清洁、更高效的二进制搜索算法,替代我编写的代码。我已经看到了如何使用递归的示例,例如在使用我理解的数字进行阶乘时。但是,在编写这种复杂的东西时,我对如何利用它来发挥自己的优势感到困惑。因此我的问题是在编写二进制搜索算法时如何应用递归。如果您对我有任何提示来完善我的递归技能,即使它必须是与二进制搜索无关的东西,请随时发布。