博客
关于我
python算法与数据结构(17)快速排序
阅读量:547 次
发布时间:2019-03-09

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

快速排序

也是分治法。很多标准语言的排序方法,最优的算法复杂度比较好。
原理:定一个主元,左边指针从左往右,右边指针从右往左,把与主元小的元素,把主元函数和这个元素调换位置。
方案1 :缺点需要额外内存空间

def quicksort(array):    if len(array) < 2:        return array    else:        pivot_index = 0        pivot = array[pivot_index]        less_port = [i for i in array[pivot_index+1:] if i <=pivot]        great_port = [i for i in array[pivot_index+1:] if i > pivot]        return quicksort(less_port) + [pivot] + quicksort(great_port)def test_quicksort():    import random    seq = list(range(10))    random.shuffle(seq)    assert quicksort(seq) == sorted(seq)

方案二:

"""方案2"""def portition(array, beg, end):    pivot_index = beg    pivot = array[pivot_index]    left = pivot_index + 1    right = end - 1    while True:        while left <= right and array[left] < pivot:            left += 1        while right >= left and array[right] >= pivot:            right -= 1        if left > right:            break        else:            array[left], array[right] = array[right], array[left]    array[pivot_index], array[right] = array[right], array[pivot_index]    return rightdef test_portition():    l = [4, 1, 2, 8]    assert portition(l, 0, len(l)) == 2    l = [1, 2, 3, 4]    assert portition(l, 0, len(l)) == 0    l = [4, 3, 2, 1]    assert portition(l, 0, len(l)) == 3
def quicksort_inplace(array, beg, end):    if beg < end:        pivot = portition(array, beg, end)        quicksort_inplace(array, beg, pivot)        quicksort_inplace(array, pivot+1, end)def test_quicksort_inplace():    import random    seq = list(range(10))    random.shuffle(seq)    print(seq)    quicksort_inplace(seq, 0, len(seq))    print(seq)

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

你可能感兴趣的文章
MTTR、MTBF、MTTF的大白话理解
查看>>
mt_rand
查看>>
mysql /*! 50100 ... */ 条件编译
查看>>
mudbox卸载/完美解决安装失败/如何彻底卸载清除干净mudbox各种残留注册表和文件的方法...
查看>>
mysql 1264_关于mysql 出现 1264 Out of range value for column 错误的解决办法
查看>>
mysql 1593_Linux高可用(HA)之MySQL主从复制中出现1593错误码的低级错误
查看>>
mysql 5.6 修改端口_mysql5.6.24怎么修改端口号
查看>>
MySQL 8.0 恢复孤立文件每表ibd文件
查看>>
MySQL 8.0开始Group by不再排序
查看>>
mysql ansi nulls_SET ANSI_NULLS ON SET QUOTED_IDENTIFIER ON 什么意思
查看>>
multi swiper bug solution
查看>>
MySQL Binlog 日志监听与 Spring 集成实战
查看>>
MySQL binlog三种模式
查看>>
multi-angle cosine and sines
查看>>
Mysql Can't connect to MySQL server
查看>>
mysql case when 乱码_Mysql CASE WHEN 用法
查看>>
Multicast1
查看>>
MySQL Cluster 7.0.36 发布
查看>>
Multimodal Unsupervised Image-to-Image Translation多通道无监督图像翻译
查看>>
MySQL Cluster与MGR集群实战
查看>>