[碩.Love Python] InsertionSort(插入排序)

def insertionSort(a):
    for i in xrange(1, len(a)):
        t = a[i]
        for j in xrange(i, 0, -1):
            if a[j-1] <= t:
                break
            a[j] = a[j-1]
        else:
            j = 0
        a[j] = t

def binaryInsertionSort(a):
    for i in xrange(1, len(a)):
        l, r, t = 0, i - 1, a[i]
        while l <= r:
            m = (l + r) / 2
            if t < a[m]:
                r = m - 1
            else:
                l = m + 1

        for j in xrange(i - 1, l - 1, -1):
            a[j+1] = a[j]

        a[l] = t

if __name__ == '__main__':
    from random import shuffle
    data = range(100)

    shuffle(data)
    print data
    insertionSort(data)
    print data

    shuffle(data)
    print data
    binaryInsertionSort(data)
    print data



劉碩老師Python精品課程:

Python高級編程技巧實戰》:

http://coding.imooc.com/class/62.html

 

Python算法實戰視頻課程》:

http://study.163.com/course/courseMain.htm?courseId=1003617013

 

Python科學計算—NumPy實戰課程》:

http://edu.51cto.com/course/course_id-5046.html

 

熊貓TV直播間:

http://www.panda.tv/671023


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章