UNB/ CS/ David Bremner/ teaching/ old/ cs1083/ java/ BubbleSort.java
public class BubbleSort<T extends Comparable<T>>{

/**
   Swaps two elements in an array.
   @param  a    the array with the elements
   to swap
   @param  i    the index of one of the elements
   @param  j    the index of the other element
   @return
*/
    public void swap(T[] a,
                     int i, int j){
        T temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }

    /**
       Sorts an array.
       @param a the array to sort
    */
    public void sort(T[] a){
        boolean finished=false;
        while(!finished){
            finished=true; // assume last pass
            for (int i=0; i<a.length-1; i++){
                if (a[i].compareTo(a[i+1]) > 0){
                    swap(a,i,i+1);
                    finished=false;
                }
            }

        }
    }

    public static void main(String [] args){

        String[] names = {"Harry", "Tom", "Moe", "Curly"};
        BubbleSort<String> stringSorter=new BubbleSort<String>();
        stringSorter.sort(names);
        for (String name : names) {
            System.out.println(name);
        }
        BubbleSort<Integer> integerSorter=new BubbleSort<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);
        }
        BubbleSort<IntPair> pairSorter=new BubbleSort<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);
        }

        BubbleSort<Student> studentSorter= new BubbleSort<>();
        Student[] students = { new Student(1, "bob"),
                               new Student(5, "marvin the paranoid android"),
                               new Student(-9, "difficult person"),
                               new Student(0, "quiet person")};

        studentSorter.sort(students);
        for (Student student : students) {
            System.out.println(student);
        }

        IdStudent[] idStudents = { new IdStudent(1, "bob"),
                               new IdStudent(5, "marvin the paranoid android"),
                               new IdStudent(-9, "difficult person"),
                               new IdStudent(0, "quiet person")};

        studentSorter.sort(idStudents);
        for (IdStudent student : idStudents) {
            System.out.println(student);
        }


    }
}