博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
数据结构(python) —— 【08排序: 快速排序】
阅读量:3945 次
发布时间:2019-05-24

本文共 1646 字,大约阅读时间需要 5 分钟。

快速排序

    昨天说完了Low B三人组的插入排序,今天来说说NB三人组的快速排序。

1. 思路

  1. 取一个元素p(第一个元素), 使元素P归位
  2. 列表被p分为两部分, 左边都比p小, 右边都比p大
  3. 递归完成排序

这里我用自己做的GIF来简单演示下列表中一个数的归位的部分过程(由于大小限制,这里只展示了部分过程,全过程视频请前往资源下载,是免费的哦: ):

快速排序这里整个列表刚开始都是无序表,那我们就取无序列表的第一个元素进行归位.

2. 代码

def partition(li, left, right):    """    归位函数    :param li: 需要归位的无序列表    :param left: 左边开始的位置    :param right: 右边开始的位置    :return:     """    temp = li[left]    while left < right:        while left < right and li[right] >= temp:   # 从右边找比temp小的数            right -= 1     # 往左走一步        li[left] = li[right]   # 把右边的比temp小的值放到左边空位        while left < right and li[left] <= temp:  # 从左边找比temp大的数            left += 1      # 往右走一步        li[right] = li[left]  # 把左边的比temp大的值放到右边空位    li[left] = temp           # 把temp归位    return leftdef quick_sort(li, left, right):    """    使用归位函数进行递归的函数    :param li: 需要归位的无序列表    :param left: 左边开始的位置    :param right: 右边开始的位置    :return:     """    if left < right:        mid = partition(li, left, right)        quick_sort(li, left, mid-1)        quick_sort(li, mid+1, right)li = [5, 7, 4, 6, 3, 1, 2, 9, 8]quick_sort(li, 0, len(li)-1)print(li)

结果为:

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

3. 时间复杂度:

快速排序的时间复杂度: O(nlog(n))

比如列表有16个数,一共有log(n)层,每层的复杂度是n
最坏情况,时间复杂度为O(n^2)

转载地址:http://mfiwi.baihongyu.com/

你可能感兴趣的文章
4.2.2 - Logical and/or Operators
查看>>
Lesson 4 Part 2 Softmax Regression
查看>>
文章中运用到的数学公式
查看>>
Projective Dynamics: Fusing Constraint Projections for Fast Simulation
查看>>
从2D恢复出3D的数据
查看>>
glm 中 数据类型 与 原始数据(c++ 数组)之间的转换
查看>>
Derivatives of scalars, vector functions and matrices
查看>>
the jacobian matrix and the gradient matrix
查看>>
VS2010 将背景设为保护色
查看>>
ubutun里面用命令行安装软件
查看>>
ubuntu 常用命令
查看>>
SQLite Tutorial 4 : How to export SQLite file into CSV or Excel file
查看>>
Optimizate objective function in matrix
查看>>
Convert polygon faces to triangles or quadrangles
查看>>
read obj in matlab
查看>>
find out the neighbour matrix of a mesh
查看>>
Operators and special characters in matlab
查看>>
As-Conformal-As-Possible Surface Registration
查看>>
qmake Variable Reference
查看>>
Lesson 2 Gradient Desent
查看>>