15-排序4_归并排序

  • 阅读: 169
  • 更新: 2022-06-11

难度:

1. 题目描述

2. 关键点

  • 先分割,再合并

3. 代码实现

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import random


def sort_merge(lst):
    """归并排序"""
    if len(lst) < 2:
        return lst
    mid = len(lst) // 2
    left = sort_merge(lst[:mid])
    right = sort_merge(lst[mid:])

    i = j = 0
    lst2 = []
    while i < len(left) and j < len(right):
        if left[i] < right[j]:
            lst2.append(left[i])
            i += 1
        else:
            lst2.append(right[j])
            j += 1

    while i < len(left):
        lst2.append(left[i])
        i += 1

    while j < len(right):
        lst2.append(right[j])
        j += 1

    return lst2


lst = [random.randint(0, 10) for i in range(10)]
print(lst)
lst2 = sort_merge(lst)
print(lst2)

4. 运行示例

1
2
[6, 1, 0, 9, 3, 7, 1, 5, 8, 10]
[0, 1, 1, 3, 5, 6, 7, 8, 9, 10]

5. 进阶思考

  1. 优化示例代码

=== 全文完 ===


欢迎加入QQ群:778391413

京公网安备 11011302003970号 京ICP备2022012301号-1