Back to course sections
    Mark As Completed Discussion

    Insertion Sort

    Insertion sort is another marvelous sorting algorithm, one that's pretty simple to understand and easy to implement.

    The idea is similar to bubble sort. Think of your input array as being made of a sorted left half and an unsorted right half.

    One by one, insert an item in its correct place in the sorted half. Insertion is done by comparing the item with successive items before it, and swapping them if needed. To reiterate the steps:

    1. Maintain a sorted left sub-array and an unsorted right sub-array.
    2. Insert the first key from the unsorted part into its correct place in the sorted half.

    The entire pseudo-code that accomplishes the sort is provided here:

    SNIPPET
    1Routine: insertionSort
    2Input: Unsorted array X of size n
    3
    41. totalSorted = 1
    52. while totalSorted <= (n-1)
    6    {
    7        // insert the item at index position totalSorted into top half
    8        // by successive comparison with items before it
    9        b. i = totalSorted
    10        c. while(i > 0 and X[i-1]>X[i])
    11        {
    12            i. swap(X[i-1], X[i])
    13            ii. i--
    14        }
    15        totalSorted++
    16    }
    JAVASCRIPT
    OUTPUT
    :001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment