Binary Search -- A Fundamental Algorithm
Binary search is a clever though common sense way to search an ordered set of items. Queries are made, called probes, asking whether the desired item is smaller or larger. If the probe is chosen in the middle of the sequence, 1/2 of the possibilities must be eliminated with any answer. Now the details... |
Reminder … Algorithm vs Program
The process just described on the title slide -- suitably embellished -- is the binary search algorithm … the idea given abstractly | |
A program for binary search -- your goal -- will encode the algorithm for a specific situation, in a specific language, with specific assumptions |
Understanding the problem … | |||
Inputs: The end points, (lo, hi), of an ordered sequence | |||
Answers to an series of questions | |||
Outputs: A selected item | |||
How the inputs are transformed to the outputs: | |||
A series of questions is posed of the form | |||
“Is the desired item after item x?” | |||
so that the xth item is chosen to be midway in the interval | |||
If the reply is yes, the new interval (next after x, hi) | |||
If the reply is no, the new interval is (lo, x) | |||
The output is the item when the interval contains only a single item |
Analyzing Properties Of Solution
End points … inclusive | |
Before/after questions … stay with one form | |
Probing odd-length and even-length intervals (\) | |
New interval’s endpoints … one is kept, one changes | |
Termination … when is it over? |
A complication in searching for a birthday in a given sign is that the signs span parts of two months | |
Not to worry … logically extend the starting month |
The size of the interval is: (52 - 21) = 31 | |
The midpoint of the interval is: 31 \ 2 = 15 | |
The probe, low end + midpoint: 21 + 15 = 36 | |
What day is June 36? | |
What information is needed by the guess procedure? |
Using Binary Search In Day Finder
Inherit the initial configuration from Zodiac | |
The guess Procedure asks one | |
probe at a time ... | |
When is Guess called? |
Where do the initial values come from? | |||
After the Zodiac computation, loEnd and hiEnd can be set | |||
When are these values used? | |||
In the guess procedure to compute the midPt for the guess | |||
How are these values updated? | |||
In the yes and no button event handlers | |||
In the case of “yes,” which end moves? | |||
loEnd = midPt + 1 | |||
In the case of “no”, which end moves? | |||
hiEnd = midPt | |||
Why are the two setting not “opposite” one another? | |||
When the does the questioning terminate? | |||
When the end points are equal |