博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
快速排序
阅读量:7000 次
发布时间:2019-06-27

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

快排的核心思想

在数组中随机选取一个元素 p,一次排序后使得p前面的元素都比p小,p后面的元素都比p大。

然后再将p前面和后面的元素分别进行刚才同样的排序。如此反复执行,最后将得到一个有序的数组。

算法解释

假设有数组 6 5 7 2 3 9 1

如果每次都选取第一个元素 为 p,

第一次排序

排序元素 6 5 7 2 3 9 1

选取 p = 3
排序后要求 2 1 3 5 6 9 7
3前面的顺序不重要 重要的是 3前面的元素都比3小,后面的都比3 大

第二次排序

排序元素 2 1 选取 p = 2 排序后要求 1 2

2前面的元素都比2小,后面的都比2 大

第三次排序

排序元素 5 6 9 7 选取 p = 5 排序后要求 5 6 9 7

5前面的元素都比5小,后面的都比5 大

第四次排序

排序元素 1 选取 p = 1 排序后要求 1

1前面的元素都比1小,后面的都比1 大

第 ... 次排序
单次排序

只需要排序后 使得 p前面的元素都比p小,后面的都比p大。设置两个指针 p_start 指向数组头部,p_end指向数组尾部。从尾部开始向前找到一个比p小的元素,再从头开始找一个比p大的元素,然后交换他们两个的位置。如此反复,最后总会有一个时刻 p_start = p_end,这个位置就是p应该在的位置。

代码实现 python

def sort(datas, start_index, end_index):    pivot = datas[start_index]    while start_index < end_index:        while datas[end_index] > pivot and start_index < end_index:            end_index -= 1        while datas[start_index] <= pivot and start_index < end_index:            start_index += 1        if start_index < end_index:            temp = datas[start_index]            datas[start_index] = datas[end_index]            datas[end_index] = temp    datas[start_index] = pivot    return start_index复制代码

全部实现

datas1 = [1, 2, 4, 6, 3, 1, 3, 43, 547, 123, 436, 57, 98, 976, 543, 2112, 378988, 7654321, 32]def sort(datas, start_index, end_index):    pivot = datas[start_index]    while start_index < end_index:        while datas[end_index] > pivot and start_index < end_index:            end_index -= 1        while datas[start_index] <= pivot and start_index < end_index:            start_index += 1        if start_index < end_index:            temp = datas[start_index]            datas[start_index] = datas[end_index]            datas[end_index] = temp    datas[start_index] = pivot    return start_indexdef quicSort(datas, start_index, end_index):    if start_index < end_index:        mid_index = sort(datas, start_index, end_index)        quicSort(datas, start_index, mid_index - 1)        quicSort(datas, mid_index + 1, end_index)quicSort(datas1, 0, len(datas1) - 1)print(datas1)复制代码

转载于:https://juejin.im/post/5c7b8cc4518825153f784f03

你可能感兴趣的文章
rman备份OBSOLETE和EXPIRED参数来历及区别
查看>>
NewLife.Redis基础教程
查看>>
BlockingQueue(阻塞队列)详解
查看>>
Hystrix快速入门
查看>>
十大励志电影
查看>>
在Sql语句中使用正则表达式来查找你所要的字符
查看>>
18种最实用的网站推广方法大全
查看>>
浅谈C/C++中的typedef和#define
查看>>
浅谈C/C++中的指针和数组(一)
查看>>
这该死的数字化生活
查看>>
matlab练习程序(圆柱投影)
查看>>
需要谨记的产品设计原则
查看>>
checkbox实现单选多选
查看>>
billing是如何的拆分的?
查看>>
Lua 迭代器与closure
查看>>
mybatis_helloworld(2)_源码
查看>>
完整部署CentOS7.2+OpenStack+kvm 云平台环境(3)--为虚拟机指定固定ip
查看>>
BLE 广播数据解析
查看>>
Oracle用户密码过期和用户被锁解决方法【转】
查看>>
Android 解决Android的TextView和EditText换行问题
查看>>