[Home]Insertion sort

HomePage | Recent Changes | Preferences

Showing revision 7
Insertion sort is a sort algorithm very similar to bubble sort; the two even compare and exchange exactly the same pairs of elements, although in a different chronological order.

The algorithm is as follows:

def insertionsort(array):
    # Remove elements from start, extending result part of array.
    for removed_index in range(1, len(array)):
        removed_value = array[removed_index]
        # Search result part of array from top for index at which to insert.
        insert_index = removed_index
        while insert_index > 0 and array[insert_index - 1] > removed_value:
            # Move entry up to make room to insert value below.
            array[insert_index] = array[insert_index - 1]
            insert_index = insert_index - 1
        # Insert removed value at correct location in sorted result.
        array[insert_index] = removed_value

In bubble sort, after N passes through the array, the N largest elements have bubbled to the top. (Or the N smallest elements have bubbled to the bottom, depending on which way you do it.) In insertion sort, after N passes through the array, you have a run of N sorted elements at the bottom of the array. Each pass inserts another element into the sorted run. So with bubble sort, each pass takes less time than the previous one, but with insertion sort, each pass takes more time than the previous one.

Insertion sort (and bubble sort) take O(n2) time in the average, best, and worst cases, which makes them impractical for sorting large numbers of elements; however, their inner loops are very fast, which often makes them the fastest algorithms around for sorting small numbers of elements, typically less than 10 or so. Quicksort works by dividing the array to be sorted into smaller runs to be sorted separately; highly optimized implementations of Quicksort often use insertion or bubble sort to sort these runs once they get small enough.

More sophisticated versions of insertion sort can be smart enough to figure out how much of their data is already in order, and can therefore grow their sorted region by more than one item on each pass; these versions of insertion sort will finish in one pass if the whole array is already sorted.

/Talk


HomePage | Recent Changes | Preferences
This page is read-only | View other revisions | View current revision
Edited December 16, 2001 8:17 am by Carey Evans (diff)
Search: