1. 程式人生 > >python實現歸併排序演算法

python實現歸併排序演算法

前面我們講了歸併排序演算法,接下來我們來python程式碼實現唄,如下

#!/usr/bin/python
# -*- coding: utf-8 -*-
#歸併排序

def _last_merge_sort(list1, list2):
    i, j = (0, 0)
    temp = []
    while i < len(list1) and j <len(list2):
        if list1[i] <= list2[j]:
            temp.append(list1[i])
            i += 1
        else:
            temp.append(list2[j])
            j += 1

    if i == len(list1):#說明list1遍歷完了,只剩下list2後面一點(有可能剩一個,有可能剩很多),因為是排序好的,所以追加即可
        for k in list2[j:]:
            temp.append(k)
    else:
        for k in list1[i:]:
            temp.append(k)
    print "===================="+str(temp)
    return temp

def _merge_sort(the_list):
    print the_list
    if len(the_list) == 1:
        return the_list
    else:
        mid = len(the_list)/2
        left = _merge_sort(the_list[:mid])
        right = _merge_sort(the_list[mid:])
        return _last_merge_sort(left, right)

if __name__ == '__main__':
    the_list = [8, 4, 5, 7, 1, 3, 6, 2,8]
    print _merge_sort(the_list)

執行,結果如下

[8, 4, 5, 7, 1, 3, 6, 2, 8]
[8, 4, 5, 7]
[8, 4]
[8]
[4]
====================[4, 8]
[5, 7]
[5]
[7]
====================[5, 7]
====================[4, 5, 7, 8]
[1, 3, 6, 2, 8]
[1, 3]
[1]
[3]
====================[1, 3]
[6, 2, 8]
[6]
[2, 8]
[2]
[8]
====================[2, 8]
====================[2, 6, 8]
====================[1, 2, 3, 6, 8]
====================[1, 2, 3, 4, 5, 6, 7, 8, 8]
[1, 2, 3, 4, 5, 6, 7, 8, 8]

符合預期