Java Reference
In-Depth Information
54
System.out.println();
55
}
56
57
public static void
main(String[] args)
58
{
59
SecureRandom generator =
new
SecureRandom();
60
61
int
[] data =
new
int
[
10
];
// create array
62
63
for
(
int
i =
0
; i < data.length; i++)
// populate array
64
data[i] =
10
+ generator.nextInt(
90
);
65
66
System.out.printf(
"Unsorted array:%n%s%n%n",
67
Arrays.toString(data));
// display array
68
selectionSort(data);
// sort array
69
70
System.out.printf(
"Sorted array:%n%s%n%n",
71
Arrays.toString(data));
// display array
72
}
73
}
// end class SelectionSortTest
Unsorted array:
[40, 60, 59, 46, 98, 82, 23, 51, 31, 36]
after pass 1: 23 60 59 46 98 82 40* 51 31 36
--
after pass 2: 23 31 59 46 98 82 40 51 60* 36
-- --
after pass 3: 23 31 36 46 98 82 40 51 60 59*
-- -- --
after pass 4: 23 31 36 40 98 82 46* 51 60 59
-- -- -- --
after pass 5: 23 31 36 40 46 82 98* 51 60 59
-- -- -- -- --
after pass 6: 23 31 36 40 46 51 98 82* 60 59
-- -- -- -- -- --
after pass 7: 23 31 36 40 46 51 59 82 60 98*
-- -- -- -- -- -- --
after pass 8: 23 31 36 40 46 51 59 60 82* 98
-- -- -- -- -- -- -- --
after pass 9: 23 31 36 40 46 51 59 60 82* 98
-- -- -- -- -- -- -- -- --
Sorted array:
[23, 31, 36, 40, 46, 51, 59, 60, 82, 98]
Fig. 19.4
|
Sorting an array with selection sort. (Part 2 of 2.)
Methods
selectionSort
and
swap
Lines 9-24 declare the
selectionSort
method. Lines 12-23 loop
data.length
-
1
times.
Line 14 declares and initializes (to the current index
i
) the variable
smallest
, which stores
the index of the smallest element in the remaining array. Lines 17-19 loop over the re-
maining elements in the array. For each of these elements, line 18 compares its value to
the value of the smallest element. If the current element is smaller than the smallest ele-
ment, line 19 assigns the current element's index to
smallest
. When this loop finishes,