In a general binary search algorithm (for example Java), we use the floor instead of selecting the middle element Division of roof:
Public static zero binary search (int [] array, int lower bot, upper inc, int key) {int comparisonCount = 0; // Calculation of the number of comparisons (optional), while (lower bundle <= upper bound) {final integer = (bottom side + upper bound) / 2; ++ comparisonCount; If (array [position] == key) {System.out.println ("number array was found in subscript" + position + '.'); System.out.println ("binary search" "comparison found the number after comparison" comparison "comparison"); Return; } If (array [position]> key) // if the number is> gt; Key, .. {// decrease position by one top position = position - 1; } And {bottom = position + 1; // Other, increase in one's position}} System.out.println ("Sorry, the number is not in this array." Compare + "comparison" in binary search.); } The formula for the position
here uses the integer division, which is rounded down (i.e. goes down from 3.5 to 3). My professor said that this would cause a bug due to rounding options. If so, what is it? Why is it necessary that the price is rounded rather than the top?
Say that your lower bound zero to be searched in only one element sequence, and the upper bound Because the boundary represents an half open border
If the lower limit is zero and the upper bound is one, and you evaluate the expression
ex> (ceiling (+ bottom-bound upper bound) 2)
You get one, which is a valid index of the lone element in this sequence no Is. The only valid index is zero, which will be more traditional expression
(floor (+ less-bound upper-bound) 2)
will be generated. / P>
If you have three elements, then the middle element is clearly an index, think again
(roof (+ 0 3) 2)
is equal to two, which is an indicator of the last element, not the middle element.
We can also ask further if the choice of such a poor one middle element will still give the right answer. The algorithm still wanders in the right direction towards the right element (or the place where an element will be absent from the sequence), but the algorithm will fail when it is believed that only one element decreases again, because it will be accidentally left Select an index from the element.
Comments
Post a Comment