public class StaticSelectionSort {
/**
Finds the smallest element in
an array range.
@param a the array to search
@param from the first position
in a to compare
@return the position of the
smallest element in the range
a[from]...a[a.length - 1]
*/
public static <T extends Comparable<T>> int minimumPosition(T [] a,
int from) {
int minPos = from;
for (int i = from + 1; i < a.length; i++){
if (a[i].compareTo(a[minPos]) <0)
minPos = i;
}
return minPos;
}
/**
Sorts an array.
@param a the array to sort
*/
public static <T extends Comparable<T>> void sort(T [] a)
{
for (int n = 0; n < a.length - 1; n++) {
int minPos = minimumPosition(a, n);
if (minPos != n){
// swap
T temp=a[n];
a[n]=a[minPos];
a[minPos]=temp;
}
}
}
public static void main(String [] args){
String[] names = {"Harry", "Tom", "Moe", "Curly"};
StaticSelectionSort.sort(names);
for (String name : names) {
System.out.println(name);
}
Integer [] numbers = { 8, 4, 5, 2, 9, 1, -3, 0, 1, 2, 3 };
StaticSelectionSort.sort(numbers);
for (Integer number : numbers) {
System.out.println(number);
}
IntPair [] pairs = { new IntPair(8, 4), new IntPair(5, 2),
new IntPair(9, 1), new IntPair(-3, 0), new IntPair(1, 2) };
StaticSelectionSort.sort(pairs);
for (IntPair pair : pairs) {
System.out.println(pair);
}
}
}
//