
public class InsertionSort
{
    public static void main(String[] args)
    {
        double[] myList = {6, 5 , 3 , 1, 8 , 7, 2, 4};

        // Print list[] before sorting
        for ( int i = 0; i < myList.length; i++)
            System.out.print(myList[i]+ " ");
        System.out.println();

        InsertionSort.insertionSort(myList);

        // Print list[] after sorting
        for ( int i = 0; i < myList.length; i++)
            System.out.print(myList[i]+ " ");
        System.out.println();
    }

    public static void insertionSort(double[] list) 
    {
        for (int i = 1 ; i < list.length; i++) 
        {
            double currentElement = list[i];  // Save list[i] in currentElement

            // Find the correct position of currentElement
            int k;
            for (k = i - 1; k >= 0; k--) 
                if ( list[k] > currentElement )
                   list[k + 1] = list[k];     // Move list[k] one spot to right
                else
                   break;                     // Found the correct location

            list[k+1] = currentElement; // Put currElem in its correct location
        }
    } 
}
