您应该返回已经找到的值位置,而不是返回布尔值。递归解决方案是可以的,但是对于非常大的列表,找到结果将是一个问题。尝试实现基于循环的解决方案,而不是使用循环。我创建了一个小演示,它将帮助您理解它:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SourceCodeProgram {
private List<Integer> integers = new ArrayList<Integer>();
public static void main(String argv[]) throws Exception {
SourceCodeProgram test = new SourceCodeProgram();
test.addIntegerToSortedListVerbose(10);
test.addIntegerToSortedListVerbose(2);
test.addIntegerToSortedListVerbose(11);
test.addIntegerToSortedListVerbose(-1);
test.addIntegerToSortedListVerbose(7);
test.addIntegerToSortedListVerbose(9);
test.addIntegerToSortedListVerbose(2);
test.addIntegerToSortedListVerbose(5);
test.addIntegerToSortedListVerbose(1);
test.addIntegerToSortedListVerbose(0);
}
private void addIntegerToSortedListVerbose(Integer value) {
int searchResult = binarySearch(integers, value);
System.out.println("Value: " + value + ". Position = " + searchResult);
integers.add(searchResult, value);
System.out.println(Arrays.toString(integers.toArray()));
}
private int binarySearch(List<Integer> list, Integer value) {
int low = 0;
int high = list.size() - 1;
while (low <= high) {
int mid = (low + high) / 2;
Integer midVal = list.get(mid);
int cmp = midVal.compareTo(value);
if (cmp < 0)
low = mid + 1;
else if (cmp > 0)
high = mid - 1;
else
return mid;
}
return low;
}
}
程序打印:
Value: 10. Position = 0
[10]
Value: 2. Position = 0
[2, 10]
Value: 11. Position = 2
[2, 10, 11]
Value: -1. Position = 0
[-1, 2, 10, 11]
Value: 7. Position = 2
[-1, 2, 7, 10, 11]
Value: 9. Position = 3
[-1, 2, 7, 9, 10, 11]
Value: 2. Position = 1
[-1, 2, 2, 7, 9, 10, 11]
Value: 5. Position = 3
[-1, 2, 2, 5, 7, 9, 10, 11]
Value: 1. Position = 1
[-1, 1, 2, 2, 5, 7, 9, 10, 11]
Value: 0. Position = 1
[-1, 0, 1, 2, 2, 5, 7, 9, 10, 11]