排序算法之归并排序

#-*-coding:utf-8 -*-

import random

def merge_sorted(alist):
    n = len(alist)
    if n <= 1:
        return alist
    mid = n //2
    left = merge_sorted(alist[:mid])
    right = merge_sorted(alist[mid:])
    left_pointer,right_pointer = 0, 0
    result = []
    while left_pointer < len(left) and right_pointer < len(right):
        if left[left_pointer] <= right[right_pointer]:
            result.append(left[left_pointer])
            left_pointer += 1
        else:
            result.append(right[right_pointer])
            right_pointer += 1
    result += right[right_pointer:]
    result += left[left_pointer:]
    return result

if __name__ == '__main__':
    alist = [random.randint(1,100) for _ in range(30)]
    print(alist)
    alist = merge_sorted(alist)
    print(alist)

使用Python编写的二路归并排序,测试数据是30个1到100之间的整数

上一篇:Python算法(基础)----选择排序


下一篇:我的第十九篇博客---JavaScript基本操作