Java Reference
In-Depth Information
The solution can be described as follows:
for (int i = 0; i < list.length - 1; i++) {
select the smallest element in list[i..list.length-1];
swap the smallest with list[i], if necessary;
// list[i] is in its correct position.
// The next iteration applies on list[i+1..list.length-1]
}
Listing 7.8 implements the solution.
L
ISTING
7.8
SelectionSort.java
1
public class
SelectionSort {
2
/** The method for sorting the numbers */
3
public static void
selectionSort(
double
[] list) {
4
for
(
int
i =
0
; i < list.length -
1
; i++) {
5
// Find the minimum in the list[i..list.length-1]
6
double
currentMin = list[i];
7
int
currentMinIndex = i;
8
9
for
(
int
j = i +
1
; j < list.length; j++) {
10
if
(currentMin > list[j]) {
11 currentMin = list[j];
12 currentMinIndex = j;
13 }
14 }
15
16
// Swap list[i] with list[currentMinIndex] if necessary
17
if
(currentMinIndex != i) {
18 list[currentMinIndex] = list[i];
19 list[i] = currentMin;
20 }
21 }
22 }
23 }
select
swap
The
selectionSort(double[] list)
method sorts any array of
double
elements. The
method is implemented with a nested
for
loop. The outer loop (with the loop control vari-
able
i
) (line 4) is iterated in order to find the smallest element in the list, which ranges from
list[i]
to
list[list.length-1]
, and exchange it with
list[i]
.
The variable
i
is initially
0
. After each iteration of the outer loop,
list[i]
is in the right
place. Eventually, all the elements are put in the right place; therefore, the whole list is sorted.
To understand this method better, trace it with the following statements:
double
[] list = {
1
,
9
,
4.5
,
6.6
,
5.7
,
-4.5
};
SelectionSort.selectionSort(list);
7.24
✓
✓
Use Figure 7.11 as an example to show how to apply the selection-sort approach to
sort {
3.4
,
5
,
3
,
3.5
,
2.2
,
1.9
,
2
}.
Check
Point
7.25
How do you modify the
selectionSort
method in Listing 7.8 to sort numbers in
decreasing order?
The
java.util.Arrays
class contains useful methods for common array operations
such as sorting and searching.
Key
Point
Search WWH ::
Custom Search