Java Reference
In-Depth Information
Let us program this algorithm. For this program, as well as the other programs in this
chapter, we will use a utility method to generate an array with random entries. We
place it into a class ArrayUtil so that we don't have to repeat the code in every
example. To show the array, we call the static toString method of the Arrays
class in the Java library and print the resulting string.
This algorithm will sort any array of integers. If speed were not an issue, or if there
simply were no better sorting method available, we could stop the discussion of
sorting right here. As the next section shows, however, this algorithm, while entirely
correct, shows disappointing performance when run on a large data set.
Advanced Topic 14.1 discusses insertion sort, another simple (and similarly
inefficient) sorting algorithm.
ch14/selsort/SelectionSorter.java
1 /**
2 This class sorts an array, using the selection sort
3 algorithm.
4 */
5 public class SelectionSorter
6 {
7 /**
8 Constructs a selection sorter.
9 @param anArray the array to sort
10 */
11 public SelectionSorter( int [] anArray)
12 {
13 a = anArray;
14 }
15
16 /**
17 Sorts the array managed by this selection sorter.
18 */
19 public void sort()
20 {
21 for ( int i = 0 ; i < a.length - 1 ; i++)
22 {
23 int minPos = minimumPosition (i);
629
Search WWH ::




Custom Search