Java Reference
In-Depth Information
Self-Test Exercises
20. How would you need to change the method
sort
in Display 6.11 so that it can sort
an array of values of type
double
into decreasing order, instead of increasing order?
21. If an array of
int
values has a value that occurs twice (like
b[0] == 42
and
b[7]
== 42
) and you sort the array using the method
SelectionSort.sort
, will there
be one or two copies of the repeated value after the array is sorted?
Display 6.11
Selection Sort Class
(part 1 of 2)
1
public class
SelectionSort
2{
3
/**
4
Precondition: numberUsed <= a.length;
5
The first numberUsed indexed variables have values.
6
Action: Sorts a so that a[0] <= a[1] <= ... <= a[numberUsed - 1].
7
*/
8
public static void
sort(
double
[] a,
int
numberUsed)
9
{
10
int
index, indexOfNextSmallest;
11
for
(index = 0; index < numberUsed
−
1; index++)
12
{
//Place the correct value in a[index]:
13
indexOfNextSmallest = indexOfSmallest(index, a, numberUsed);
14
interchange(index,indexOfNextSmallest, a);
15
//a[0] <= a[1] <=...<= a[index] and these are the smallest
16
//of the original array elements. The remaining positions
17
//contain the rest of the original array elements.
18
}
19
}
20
/**
21
Returns the index of the smallest value among
22
a[startIndex], a[startIndex+1], ... a[numberUsed - 1]
23
*/
24
private static int
indexOfSmallest(
int
startIndex,
25
double
[] a,
int
numberUsed)
26
{
27
double
min = a[startIndex];
28
int
indexOfMin = startIndex;
29
int
index;
30
for
(index = startIndex + 1; index < numberUsed; index++)
31
if
(a[index] < min)
32
{
33
min = a[index];
34
indexOfMin = index;
35
//min is smallest of a[startIndex] through a[index]
36
}