public class SelectionSort
{
// This class should not be instantiated.
private SelectionSort()
{
}
// ascending order
public static void sort(Comparable[]
a) {
int N
= a.length ;
for (int i
= 0; i < N; i++) {
int min
= i;
for (int j
= i + 1; j < N; j++) {
if (less(a[j],
a[min]))
min = j;
}
exch(a, i, min);
assert isSorted(a,
0, i);
}
assert isSorted(a);
}
/***********************************************************************
* Helper sorting functions
***********************************************************************/
// is v < w ?
private static boolean less(Comparable v, Comparable w)
{
return (v.compareTo(w) <
0);
}
// exchange a[i] and a[j]
private static void exch(Object[]
a, int i, int j)
{
Object swap = a[i];
a[i] = a[j];
a[j] = swap;
}
/***********************************************************************
* Check if array is sorted - useful
for debugging
***********************************************************************/
// is the array a[] sorted?
private static boolean isSorted(Comparable []
a) {
return isSorted(a,
0, a. length - 1);
}
// is the array sorted from a[lo]
to a[ hi]
private static boolean isSorted(Comparable []
a, int lo, int hi)
{
for (int i
= lo + 1; i <= hi; i++)
if (less(a[i],
a[i - 1]))
return false ;
return true ;
}
// print array to standard output
private static void show(Comparable[]
a) {
for (int i
= 0; i < a. length; i++) {
System. out .print(a[i]
+ " " );
}
}
public static void main(String[]
args) {
Integer[] a = { 10, 45, 0, 8, 7, -34, 20 };
SelectionSort. sort(a);
show(a);
}
}