1.快速排序,就是首先找一个基准,记作A,并且将数组中小于A的元素全部排在A的左边,
并且将数组中比A大的元素全部排在A的右边 (文中提到的“小于”,“大于”可以自行定义)
经过这样的排序,我们不用保证在A的左边和右边的元素维持着一种顺序,只要全满足小于A
和大于A即可。(这是我们下一步要进行的工作)
2.将A左边的元素,以及A右边的元素视作两个新的数组,执行1的操作,直到不可再划分
贴上快排的函数代码,自己写的,目前还没发现错误,用idea测试了一下.有错误再来改,但是快排
的实现(递归,循环,还有1中的找元素方式)不止一种方式。我采用的是递归方式
public static void quickSort(int[] array, int low, int high) {
if (low >= high) return; //给递归设置退出条件
int l = low, h = high;
int tmp = array[low];//以数组第一个数作为基准
while (l < h) {
while (l < h && array[h] > tmp) h--;//在数组右部分,找到比基准数小的元素
array[l] = array[h];//将此元素赋值给l指针指向的元素
while (l < h && array[l] < tmp) l++;//在数组左部分,找到比基准数大的元素
array[h] = array[l];
}
//跳出while循环时,l==h
array[l]=tmp;//调整基准数的位置
quickSort(array, low, l - 1);
quickSort(array, l + 1, high);
}
经过leetcode题目测试,发现这种方法不管正确与否,但是耗时比较长,经过分析,推荐使用下列代码
public static void fastSort(int[] nums, int low, int high) {
if (low >= high) return;
int i = low, j = high, t = 0;
int tmp = nums[low];
while (i < j) {
while (i < j && nums[j] >= tmp) j--;
while (i < j && nums[i] <= tmp) i++;
if (i < j) {
t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
}
nums[low] = nums[i];
nums[i] = tmp;
fastSort(nums, low, i - 1);
fastSort(nums, i + 1, high);
}