首页 > 代码库 > Insertion sort

Insertion sort

Input: A sequence of n numbers [a1,a2,...,an]

Output: a permutation (reordering) [a1‘,a2‘,...,an‘] of the input sequence such that a1‘ <=a2‘ <= ... <= an‘.

array = [2,4,5,22,6,34,2,5,1,3,6,9,7,8]
print array
def insertSort(array):
    for i in xrange(1,len(array)):
        # key as a temp room for a certain element in a certain step
        key = array[i] 
        j  = i - 1
        while j >=0 and array[j] > key:
            array[j+1]  = array[j]
            j = j - 1
        array[j+1] = key # loop still running till last step, so j = j - 1
        print array
    return array

insertSort(array)
# output

[2, 4, 5, 22, 6, 34, 2, 5, 1, 3, 6, 9, 7, 8]
[2, 4, 5, 22, 6, 34, 2, 5, 1, 3, 6, 9, 7, 8]
[2, 4, 5, 22, 6, 34, 2, 5, 1, 3, 6, 9, 7, 8]
[2, 4, 5, 22, 6, 34, 2, 5, 1, 3, 6, 9, 7, 8]
[2, 4, 5, 6, 22, 34, 2, 5, 1, 3, 6, 9, 7, 8]
[2, 4, 5, 6, 22, 34, 2, 5, 1, 3, 6, 9, 7, 8]
[2, 2, 4, 5, 6, 22, 34, 5, 1, 3, 6, 9, 7, 8]
[2, 2, 4, 5, 5, 6, 22, 34, 1, 3, 6, 9, 7, 8]
[1, 2, 2, 4, 5, 5, 6, 22, 34, 3, 6, 9, 7, 8]
[1, 2, 2, 3, 4, 5, 5, 6, 22, 34, 6, 9, 7, 8]
[1, 2, 2, 3, 4, 5, 5, 6, 6, 22, 34, 9, 7, 8]
[1, 2, 2, 3, 4, 5, 5, 6, 6, 9, 22, 34, 7, 8]
[1, 2, 2, 3, 4, 5, 5, 6, 6, 7, 9, 22, 34, 8]
[1, 2, 2, 3, 4, 5, 5, 6, 6, 7, 8, 9, 22, 34]

Here, we use loop invariants to help us understand why an algorithms is correct:

Initialization: It is true prior to the first iteration of the loop;

Maintenance: If it is true before an iteration of the loop, it remains true before the next iteration

Termination: When the loop terminates, the invariant gives us a useful property that helps show that the algorithm is correct.

This is the first alogorithm, and its idea behind is simple and naive: for aj, we just compare it with the element just before it ( change, if a(j-1) >a(j) and then exchange index, else stop and go to sort next element(a(j+1)); loop till to all the elements done~

 

Insertion sort