Java Reference
In-Depth Information
EXAMPLE:
(continued)
The definition of the method
sort
, included in a class, is given in Display 6.11.
sort
uses the method
indexOfSmallest
to find the index of the smallest element in the
unsorted end of the array, and then it does an interchange to move this next smallest
element down into the sorted part of the array.
The method
interchange
, shown in Display 6.11, is used to interchange the
values of indexed variables. For example, the following call will interchange the values
of
a[0]
and
a[4]
:
interchange(0, 4, a);
A sample use of the
sort
method is given in Display 6.12.
Display 6.10
Selection Sort
Unsorted array
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
8
6
11
17
3
15
5
19
28
12
8
6
11
17
3
15
5
19
28
12
3
6
11
17
8
15
5
19
28
12
3
6
11
17
8
15
5
19
28
12
3
5
11
17
8
15
6
19
28
12
.
.
.
3
5
6
8
11
12
15
17
19
28