Java Reference
In-Depth Information
Display 6.11
Selection Sort Class
(part 2 of 2)
37
return
indexOfMin;
38
}
/**
Precondition: i and j are legal indices for the array a.
Postcondition: Values of a[i] and a[j] have been interchanged.
*/
private static void
interchange(
int
i,
int
j,
double
[] a)
{
double
temp;
temp = a[i];
a[i] = a[j];
a[j] = temp;
//original value of a[i]
}
Display 6.12
Demonstration of the
SelectionSort
Class
1
public class
SelectionSortDemo
2{
3
public static void
main(String[] args)
4
{
5
double
[] b = {7.7, 5.5, 11, 3, 16, 4.4, 20, 14, 13, 42};
6
System.out.println("Array contents before sorting:");
7
int
i;
8
for
(i = 0; i < b.length; i++)
9
System.out.print(b[i] + " ");
10
System.out.println();
11
12
SelectionSort.sort(b, b.length);
13 System.out.println("Sorted array values:");
14
for
(i = 0; i < b.length; i++)
15 System.out.print(b[i] + " ");
16 System.out.println();
17 }
18 }
Sample Dialogue
Array contents before sorting:
7.7 5.5 11.0 3.0 16.0 4.4 20.0 14.0 13.0 42.0
Sorted array values:
3.0 4.4 5.5 7.7 11.0 13.0 14.0 16.0 20.0 42.0