Java Reference
In-Depth Information
In the case of an array, the range is equal to the highest and lowest number
possible: the length of the array and zero. Then, the “guess,” or search data, is
compared with the middle of that range. If the search data is lower than the
middle element in the array, the middle element becomes the new high for
future guesses. Alternately, if the search data is higher than the middle element
in the array, the middle element becomes the new low. Guesses continue to
reduce the array to be searched by one-half until the number is found.
Figure 7-33 displays a flowchart for a binary search.
A
Key =
mid-point
data?
Yes
No
Display
data number
START
END
Set the
search key
Key <
mid-point
data?
No
Yes
Make data above
mid-point new list
start: S = M +1
Make data below
mid-point new list
end: E = M +1
Mark start
of list: S
Mark end
of list: E
B
B
Mark mid-point
of list: M
M = INT( (S + E) / 2)
A
FIGURE 7-33
Searching for a DVD
The search() method is shown in Figure 7-34. For this particular prototype,
it is a linear search. Recall that the actionPerformed() method sent the search()
method two pieces of information: the search field and the array to search. The
 
Search WWH ::




Custom Search