好吧,让我们做一些测试,好吗?
首先,让我们搜索数组中的每个数字。我们得到:
binarySearch(i,array,0,array.length)密码
1 was found at position 0 after 3 comparisons
2 was found at position 1 after 4 comparisons
3 was found at position 2 after 2 comparisons
4 was found at position 3 after 3 comparisons
5 was found at position 4 after 4 comparisons
6 was found at position 5 after 1 comparisons
7 was found at position 6 after 3 comparisons
8 was found at position 7 after 4 comparisons
9 was found at position 8 after 2 comparisons
10 was found at position 9 after 3 comparisons
Average: 2.9 comparisons
二进制搜索(i,数组,0,array.length-1)密码
1 was found at position 0 after 3 comparisons
2 was found at position 1 after 2 comparisons
3 was found at position 2 after 3 comparisons
4 was found at position 3 after 4 comparisons
5 was found at position 4 after 1 comparisons
6 was found at position 5 after 3 comparisons
7 was found at position 6 after 4 comparisons
8 was found at position 7 after 2 comparisons
9 was found at position 8 after 3 comparisons
10 was found at position 9 after 4 comparisons
Average: 2.9 comparisons
As you can see, variances do appear, but the average remains constant.
Now let s test for bigger numbers:
100000 items
binarySearch(i, array, 0, array.length);
Average: 15.68946 comparisons
binarySearch(i, array, 0, array.length - 1);
Average: 15.68946 comparisons
200000 items
binarySearch(i, array, 0, array.length);
Average: 16.689375 comparisons
binarySearch(i, array, 0, array.length - 1);
Average: 16.689375 comparisons
500000 items
binarySearch(i, array, 0, array.length);
Average: 17.951464 comparisons
binarySearch(i, array, 0, array.length - 1);
Average: 17.951464 comparisons
Hence, on average it doesn t go either way. For the sake of convention I would advise using the exclusive upper bound version: binarySearch(i,array,0,array.length)密码