UNB/ CS/ David Bremner/ teaching/ cs1083/ java/ SelectionSort.java
public class SelectionSort<T extends Comparable<T>> {
    /**
      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 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 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"};
        SelectionSort<String> stringSorter=new SelectionSort<String>();
        stringSorter.sort(names);
        for (String name : names) {
            System.out.println(name);
        }
        SelectionSort<Integer> integerSorter=new SelectionSort<Integer>();
        Integer [] numbers = { 8, 4, 5, 2, 9, 1, -3, 0, 1, 2, 3 };
        integerSorter.sort(numbers);
        for (Integer number : numbers) {
            System.out.println(number);
        }

        SelectionSort<IntPair> pairSorter=new SelectionSort<IntPair>();
        IntPair [] pairs = { new IntPair(8, 4), new IntPair(5, 2),
                               new IntPair(9, 1), new IntPair(-3, 0), new IntPair(1, 2) };
        pairSorter.sort(pairs);
        for (IntPair pair : pairs) {
            System.out.println(pair);
        }

    }

}

//