https://blog.youkuaiyun.com/Yexiaofen/article/details/78018204
package leetcode.sort;
import java.util.Arrays;
/*
https://blog.youkuaiyun.com/Yexiaofen/article/details/78018204
*/
public class QuickSort {
public static void main(String[] args) {
int[] a = {1, 2, 4, 5, 7, 4, 5, 3, 9, 0};
System.out.println(Arrays.toString(a));
quickSort(a, 0, a.length - 1);
System.out.println(Arrays.toString(a));
}
private static void quickSort(int[] a, int low, int high) {
if (a == null || a.length == 0) {
return;
}
//1、递归出口
if (low > high) {
return;
}
//2, 存
int i = low;
int j = high;
//int k = low;
//3,key
int key = a[low];
//4,完成一趟排序
while (i < j) {
// M:必须先找到j,也就是这个while循环必须在下面的while循环的前面?
//4.1 ,从右往左找到第一个小于key的数
while (i < j && a[j] > key) {
j--;
}
//M:a[i] <a[k],必须有 = 号
// 4.2 从左往右找到第一个大于key的数
while (i < j && a[i] <= key) {
i++;
}
//4.3 交换
if (i < j) {
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
}
// 4.4,调整key的位置,即调整哨兵的位置
int tmp = a[i];
a[i] = a[low];
a[low] = tmp;
//5, 对key左边的数快排
quickSort(a, low, i - 1);
//6, 对key右边的数快排
quickSort(a, i + 1, high);
}
}
快速排序
最新推荐文章于 2023-03-27 15:34:41 发布