码迷,mamicode.com
首页 > 其他好文 > 详细

Insertion sort

时间:2017-05-17 00:51:09      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:oop   put   running   its   ret   style   help   dex   cert   

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

标签:oop   put   running   its   ret   style   help   dex   cert   

原文地址:http://www.cnblogs.com/vpegasus/p/Insertion_algorithm.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!