package sort;

/**
 * Selection Sort Algorithm
 * @author Winston Prakash
 */
public class SelectionSort<E extends Comparable<E>> {
    
    private transient E[] dataArray;
    private transient E[] sortedArray;
    int dataSize;
    /** Creates a new instance of MergeSort */
    public SelectionSort(E[] data) {
        dataArray = data;
        sortedArray = (E[]) new Comparable[data.length];
        System.arraycopy(data, 0, sortedArray, 0, data.length);
        dataSize = sortedArray.length;
    }
    
    /**
     * Scan the inner array (right side) and find the minimum value compared to the
     * current index of the sorted outer array (left side & loop invariant)and swap that 
     * value with current index value 
     */
    void sort() {
        for (int out = 0; out < dataSize - 1; out++){
            int min = out;
            for (int in = out + 1;  in < dataSize; in++){
                if (sortedArray[in].compareTo(sortedArray[min]) < 0){
                   min = in;
                }
            }
            swap(out, min);
        }
    }
    
    private void swap(int i, int j) {
        E temp = sortedArray[i];
        sortedArray[i] = sortedArray[j];
        sortedArray[j] = temp;
    }
    
    public void displayData(){
        System.out.println("\nArray sorting using Selection Sort Algorithm");
        System.out.println("\nUnsorted Array");
        for (int i =0; i< dataArray.length; i++){
            System.out.print(dataArray[i] + "  ");
        }
        System.out.println("\nSorted Array");
        for (int i =0; i< sortedArray.length; i++){
            System.out.print(sortedArray[i] + "  ");
        }
        System.out.println();
    }
}