import java.util.ArrayList;

/**
 * Class for sort methods; main method to test sorts
 */
public class SortTest {

    /**
     * Sorts data in ascending order using selection sort. Elements must implement Comparable<E>
     *
     * @param data the ArrayList<E> to sort 
     */
    public static <E extends Comparable<E>> void selectionSort(ArrayList<E> data) {
        int numUnsorted = data.size();
        int index; // general index
        int max;   // index of largest value
        while (numUnsorted > 0) {
            // determine index of maximum value in unsorted portion
            max = 0;
            for (index = 1; index < numUnsorted; index++) {
                if (data.get(max).compareTo(data.get(index)) < 0) {
                    max = index;
                }
            }
            swap(data, max, numUnsorted - 1);
            numUnsorted--;
        }
    }

    private static <E> void swap(ArrayList<E> data, int i, int j) {
        E temp = data.get(i);
        data.set(i, data.get(j));
        data.set(j, temp);
    }

    public static void main(String[] args) {
        ArrayList<Integer> nums = new ArrayList<>();
        nums.add(5);
        nums.add(2);
        nums.add(8);
        nums.add(1);
        nums.add(9);
        nums.add(3);

        System.out.println("Before: " + nums);
        selectionSort(nums);
        System.out.println("After:  " + nums);

        ArrayList<String> words = new ArrayList<>();
        words.add("banana");
        words.add("apple");
        words.add("cherry");

        System.out.println("Before: " + words);
        selectionSort(words);
        System.out.println("After:  " + words);
    }
}
