Java Reference
In-Depth Information
retrieval. For example, banks sort transactions by check number or date, and
telephone directories sort telephone numbers by last name and first name.
Teachers sort exam grades from highest to lowest to look for patterns in learning.
Many different computer algorithms for sorting have been implemented
over the years, and some have proven more efficient than others. A sorting algo-
rithm looks at pairs of elements to determine if they are in order. If they are not
in order, the pair must be interchanged. The algorithm traverses the array, check-
ing pairs, until a complete pass yields no interchange. This is a tedious task by
hand but one well-suited for Java. A popular method of sorting is the bubble
sort , so named because when a pair of elements is examined, the interchanged
value moves, or bubbles up, to the top of the array.
Another method of sorting is the selection sort , in which the entire array is
searched for its lowest-value element. That element then is positioned at the
beginning of the array. The process is repeated for the remaining elements; the
lowest of that group then is placed in the second position. Each search examines
one fewer element than the previous and continues to place elements in order
until no elements remain.
An insertion sort , well-suited for small arrays, creates a new array and
inserts the values in order. A merge sort takes two previously sorted arrays of
the same data type and sorts them into one list.
Sorting the Classics on DVD Collection
Figure 7-30 displays the sort algorithm that will be used in the Classics
on DVD program. The array to be sorted is passed as a temporary array to the
sort() method in line 260. A loop then passes through the array, beginning
in line 263, for the same number of times as there are elements in the array
(length - 1).
259
//method to sort arrays
260
public void sort ( String tempArray [])
261
{
262
//loop to control number of passes
263
for ( int pass = 1; pass < tempArray.length; pass++ )
264
{
265
for ( int element = 0; element < tempArray.length - 1; element++ )
266
if ( tempArray [ element ] .compareTo ( tempArray [ element + 1 ]) >0 )
267
{
268
swap ( title, element, element + 1 ) ;
269
swap ( studio, element, element + 1 ) ;
270
swap ( year, element, element + 1 ) ;
271
}
272
}
273
addTextToTextPane () ;
274
}
275
276
//method to swap two elements of an array
277
public void swap ( String swapArray [] , int first, int second )
278
{
279
String hold; //temporary holding area for swap
280
hold = swapArray [ first ] ;
281
swapArray [ first ] = swapArray [ second ] ;
282
swapArray [ second ] = hold;
283
}
284
FIGURE 7-30
Search WWH ::




Custom Search