本人水平有限难免出现明显错误欢迎指出
快速排序是十大排序之一 其性能高效 java中一句Arrays.sort(int[] nums) 在这里稍微说一下实现
快速排序是对插入排序的一种优化
插入排序是遍历数组 把大数组变成小数组 小数组有序 并且让小数组逐渐变成有序的大数组
时间复杂度 O(nlog(n))
实现 在数组中选择一个数作为标志位` `
逻辑上把它放到最中间
2 让其他元素小于它的放到它的左边 3 大于它的放到它的右边
4 一直这样直到子数组的中间是本身的最右或最左
单指针实现
public int[] sortArray(int[] nums) {
quickSort(nums, 0, nums.length - 1);
return nums;
}
public void quickSort(int[] nums, int start, int end) {
//递归实现
if (start < end) {
int port = port(nums, start, end);
System.out.println();
quickSort(nums, start, port - 1);
quickSort(nums, port + 1, end);
}
}
public int port(int[] nums, int start, int end) {
// int[] a = {4, 2, 5, 3, 6};
// 排序的标志位
int pivot = nums[start];
//从标志位的下一位开始遍历 如果不加一 刚开始标志位 应该会等于 nums[low]
int low = start + 1;
int height = end;
while (low <= height) {
//小于标志位的说明正确 大于标志位往右边放
if (nums[low] <= pivot) {
low++;
} else {
swap(nums, low, height);
height--;
}
}
// 把标志位放到中间
swap(nums, start, height);
return height;
}
```
public void swap(int[] nums, int a, int b) {
int temp = nums[a];
nums[a] = nums[b];
nums[b] = temp;
}
双指针
public int[] sortArray2(int[] nums) {
quickSort2(nums, 0, nums.length - 1);
return nums;
}
public void quickSort2(int[] nums, int start, int end) {
if (start < end) {
int port = port2(nums, start, end);
System.out.println();
quickSort2(nums, start, port - 1);
quickSort2(nums, port + 1, end);
}
}
public int port2(int[] nums, int start, int end) {
//
int pivot = nums[start];
int low = start + 1;
int height = end;
while (low <= height) {
//把左边大于标志位和(右边小于标志位的(可能) // 右边有可能全大于) 交换
while (nums[start] <= pivot && low <= height) low++;
while (nums[end] > pivot && low <= height) height--;
// 亲测 没有if数组越界
if (low < height)
swap(nums, low, height);
}
swap(nums, start, height);
return height;
}
public void swap(int[] nums, int a, int b) {
int temp = nums[a];
nums[a] = nums[b];
nums[b] = temp;
}
最后 馨提示 本代码 在leetcode 排序数组中提交超时 嗯 并且leetcode 官方给的快排也超时了.
参考
[](https://www.bilibili.com/video/BV1VU4y1b7cG?p=34)