• 技术文章 >Python技术 >Python基础教程

    python快速排序算法的使用

    小妮浅浅小妮浅浅2021-10-14 10:21:13原创3932

    1、选择列表中最后一个元素最基准数N,小于N的放前,大于等于N的放后。

    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

    def move_num(my_list, low, high):

        N = my_list[high]  # 确定基数N

        move = low - 1  # 从左边减1开始

        for i in range(low, high):

            if my_list[i] <= N:

                move += 1  # 记录最近一个交换值的下标

                my_list[move], my_list[i] = my_list[i], my_list[move]  # 大的放后面,小的放move处

        my_list[move + 1], my_list[high] = my_list[high], my_list[move + 1]  # 最后一次,把N值放到move+1处

        return move + 1

      

      

    def quick_sort(my_list, low, high):

        n = len(my_list)

        if n == 1:

            return my_list

        if low < high:  # low==high停止排序

            N = move_num(my_list, low, high)  # 一次比较排序

            quick_sort(my_list, low, N - 1)  # 递归前一部分排序

            quick_sort(my_list, N + 1, high)  # 递归后一部分排序

        return my_list

      

      

    if __name__ == "__main__":

        my_list = [8, 0, 4, 3, 2, 1]

        print("排序前的数组:", my_list)

        print("排序后的数组:", quick_sort(my_list, 0, len(my_list) - 1))

    以上就是python快速排序算法的使用,希望对大家有所帮助。更多Python学习指路:python基础教程

    本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

    专题推荐:python快速排序
    上一篇:python中requests如何优化接口调用 下一篇:python中PCA的处理过程

    相关文章推荐

    • python中pdb的中断控制• python中pdb有哪些调试命令• python标识符的使用注意• python字符串的基础操作• python列表的基本用法• Python集合有什么特点• Python字典的特点• python uiautomator2的点击操作• python socket的连接步骤• python使用VS接收数据• python中echo服务器的介绍• python中requests如何优化接口调用

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网