Java Reference
In-Depth Information
The first element of the temporary array is compared with the second
element in line 266. If an interchange or swap is necessary, the sort() method
calls the swap() method with three arguments: the array, the first element, and
the second element. The swap() method uses the variable, hold, to temporarily
house the first element while the second element is assigned to the first element's
location. The hold variable then is transferred into the second element's position
(line 282), completing the swap.
As part of the sort routine, Java compares the current array member with the
previous array member. Line 266 uses a method named compareTo(), which Java
utilizes as a comparison operator. The compareTo() method returns a value less
than zero when the String object inside its parenthetical argument is less than the
given string; a value of zero when the strings are equal; and a value greater than
zero when the String object is greater than the given string. It is the comparison
operator's return value that indicates whether the two names, and their corre-
sponding fields, should be swapped. Line 266 compares two elements of the array.
If compareTo() returns a value greater than zero, then a swap should be made.
The following step enters code for the sort() and swap() methods.
To Code the sort() and swap() Methods
1. Enter the code shown in Figure 7-30 on the previous page.
TextPad displays the code for the sort() and swap() methods (Figure 7-31).
sort()
method
swap()
method
FIGURE 7-31
Searching an Array
Searching an array involves accepting a search argument from the user and
then comparing it with elements in the array. You learned that if an array is
short, performing a linear search — or looking through the list one by one —
might be appropriate. A linear search is necessary when the data is not in order.
Figure 7-32 displays a flowchart for a linear search.
 
Search WWH ::




Custom Search