15-排序5_快速排序

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

难度:

1. 题目描述

2. 关键点

  • 以基准值为基准将序列划分为两个子序列

3. 代码实现

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
import random


def sort_quick(lst):
    """快速排序"""
    if len(lst) <= 1:
        return lst
    m = lst[0]
    left = [x for x in lst if x < m]
    middle = [x for x in lst if x == m]
    right = [x for x in lst if x > m]
    return sort_quick(left) + middle + sort_quick(right)


lst = [random.randint(0, 10) for i in range(10)]
print(lst)
lst2 = sort_quick(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