package sort;

/**
 * Sort the array using bubble sort algorithm
 * @author Winston Prakash
 */
public class BubbleSort<E extends Comparable<E>>  {
    private transient E[] dataArray;
    private transient E[] sortedArray;
    int dataSize;
    
    /** Creates a new instance of BubbleSort */
    public BubbleSort(E[] data) {
        dataArray = data;
        sortedArray = (E[]) new Comparable[data.length];
        System.arraycopy(data, 0, sortedArray, 0, data.length);
        dataSize = sortedArray.length;
    }
    
    /**
     * Bubble up highest value in the inner array (left hand array) and place 
     * them at the outer array (right side) in a decreasing order from the 
     * end of the outer array (loop invariant, already sorted).  
     */
    public void sort(){
        for (int out = dataSize - 1; out > 1; out--){
            for (int in = 0;  in < out; in++){
                if (sortedArray[in + 1].compareTo(sortedArray[in]) < 0){
                    swap(in, in + 1);
                }
            }
        }
    }
    
    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 Bubble 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();
    }
}