Seven iterations is the maximum required to find a number in a set of one hundred. This is because it is somewhere between six and seven, and you need to use the higher of these two values to make sure it is detected.log2100
- , . , , ( , //<<here //<<):
while ((array[position] != key) && (lowerbound <= upperbound)) {
System.out.print(String.format(
"Step %d, lo=%2d, hi=%2d, mid=%2d, [mid]=%4d, ",
comparisonCount, lowerbound, upperbound,
position, array[position]));
comparisonCount++;
if (array[position] > key) {
upperbound = position - 1;
System.out.println(String.format(
"too high, hi:=%2d", upperbound));
} else {
lowerbound = position + 1;
System.out.println(String.format(
"too low, lo:=%2d", lowerbound));
}
position = (lowerbound + upperbound) / 2;
}
if (lowerbound <= upperbound) {
System.out.println(String.format(
"Step %d, lo=%2d, hi=%2d, mid=%2d, [mid]=%4d, found!",
comparisonCount, lowerbound, upperbound,
position, array[position]));
System.out.println("The number " + key +
" was found in array.");
System.out.println("The binary search found the number after "
+ comparisonCount + " comparisons.");
}
, 3049, :
Step 1: lo= 0, hi=99, mid=49, [mid]=3049, found!
3067 :
Step 1: lo= 0, hi=99, mid=49, [mid]=3049, too low, lo:=50
Step 2: lo=50, hi=99, mid=74, [mid]=3074, too high, hi:=73
Step 3: lo=50, hi=73, mid=61, [mid]=3061, too low, lo:=62
Step 4: lo=62, hi=73, mid=67, [mid]=3067, found!
, . , 3099:
Step 1, lo= 0, hi=99, mid=49, [mid]=3049, too low, lo:=50
Step 2, lo=50, hi=99, mid=74, [mid]=3074, too low, lo:=75
Step 3, lo=75, hi=99, mid=87, [mid]=3087, too low, lo:=88
Step 4, lo=88, hi=99, mid=93, [mid]=3093, too low, lo:=94
Step 5, lo=94, hi=99, mid=96, [mid]=3096, too low, lo:=97
Step 6, lo=97, hi=99, mid=98, [mid]=3098, too low, lo:=99
Step 7, lo=99, hi=99, mid=99, [mid]=3099, found!