当前位置:网站首页>十大排序之快速排序
十大排序之快速排序
2022-07-25 23:36:00 【花开不识君】
交换法
交换法快速排序的步骤
1、找到一个分界点,让分界点左边的值小于分界点,右边的值大于等于分界点。
2、对做左边这样做。
3、对右边在这样做。
核心代码
# 非完整代码
private static int partition2(int[] arr, int left, int right) {
int i = left, j = right;
int pivot = arr[left];
while (i < j) {
while (i < j && arr[j] >= pivot) {
j--;
}
while (i < j && arr[i] <= pivot) {
i++;
}
if (i < j) {
swap(arr, i, j);
}
}
swap(arr, left, i);
return i;
}
Q&A
为什么是从后往前走,能不能换一下位置?
1、因为我们选择的标兵是在左侧,所以我们要从右侧开始遍历
那为什么因为我们选择的标兵是在左侧,就要从右边开始?
进一步的分析,我们最终需要将标兵把i==j停下来的位置的值做交换,所以停下来的位置,一定要是比标兵更小的值,否则就不满足,标兵左边的值小于标兵的前提。假定如果我们从左开始,那么就有最终在比标兵大的地方停下来,导致最终发生交换的时候违背了前面说的原则。而从右边开始我们能够保证一定是遇到比标兵小的值或者回到标兵的位置才停下来。
2、如果你希望从左边开始,那么标兵选择最右边即可。
边栏推荐
- [QNX Hypervisor 2.2用户手册]9.7 generate
- Serialize common default values and column parameters
- 【MUDUO】EventLoop事件循环
- Optimize the browsing experience of yandere/konachan site with user scripts
- Discuz atmosphere game style template / imitation lol hero League game DZ game template GBK
- Docker installation redis-5.0.12 (remote access)
- Implementation of date class
- Wrote a little webapi knowledge points from 0 to 1
- Loading process such as reflection
- 利用用户脚本优化 Yandere/Konachan 站点浏览体验
猜你喜欢

学习探索-波浪

Dynamic memory management

数组中重复的数字

R language installation tutorial | graphic introduction is super detailed

Data broker understanding

行云管家V6.5.1/2/3系列版本发布:数据库OpenAPI能力持续强化

Generating random number random learning uniform_ int_ distribution,uniform_ real_ distribution

图的遍历-DFS,BFS(代码详解)

生成随机数random学习之uniform_int_distribution,uniform_real_distribution
![[Database Foundation] summary of MySQL Foundation](/img/89/e22c232b0183eaae35a9f45a40ff36.jpg)
[Database Foundation] summary of MySQL Foundation
随机推荐
R language installation tutorial | graphic introduction is super detailed
Which securities firm is the best and safest for beginners to open an account
Static agent + dynamic agent
[Muduo] EventLoop event cycle
redis-基本数据类型(String/list/Set/Hash/Zset)
Recursion of function (use recursion to find the factorial of 1-N) (use recursion to find Fibonacci sequence) (use recursion to traverse data)
XXE&XML-外部实体注入-利用和绕过
Classes and objects (2) (6 default member functions)
Inheritance (the child constructor inherits the attributes in the parent constructor)
意向不到的Dubug妙招
What is a physical firewall? What's the effect?
Why are there many snapshot tables in the BI system?
Summary of kotlin common knowledge points
Dynamic memory management
在应用中使用 Jetpack 库
Qpprogressbar for QT style (QSS) application
Deep and shallow copies
chown: changing ownership of ‘/var/lib/mysql/‘: Operation not permitted
LeetCode 0136. 只出现一次的数字:异或
[JUC] concurrent keyword volatile