一、快速排序的基本思想:
1、在集合中找一个数作为基准数;
2、集合分为三部分:左分区、基准数、右分区,其中左分区的数都小于等于基准数,右分区的数都大于等于基准数;
3、分别对左分区、右分区执行第2步的操作。
如例子:
0, 1, 2, 3, 4, 5
S = [2, 7, 3, 6, 5, 1]
以left = 0, right = 5,基准数base = S[left],
a. 从S5开始,从右往左搜索,搜索到小于等于base的数S[right],则S[left] = S[right],那么位置right需要用一个大于等于base的数据来填补;
b. 从S0开始,从左往右搜索,搜索到大于等于base的数S[left],则S[right] = S[left];
c. left = left - 1, right = right -1 ,循环执行a,b步骤,直到 left 和 right相等的时候,设置S[left] = base,
就可以分出集合的左分区[0, ..., left -1] , 基准数, 右分区[right + 1, ..., n];
d. 对左分区[0, ..., left - 1]和右分区[right + 1, ..., n]分别执行a, b, c步骤。
时间复杂度O(nlogn)
二、a, b, c步骤的过程:
0.
1.
2.
3.
4.
5.
6. S[left] = base
则集合分成了[1], [2], [3, 6, 5, 7]。
接着对左分区[1]和右分区[3, 6, 5, 7]使用a,b,c步骤排序。
三、快速排序的java实现
public class QuickSort {
public static int partition(int[] ints, int left, int right){
int base = ints[left];
while(left < right){
while(left < right && ints[right] >= base){
right--;
}
ints[left] = ints[right];
while(left < right && ints[left] <= base){
left++;
}
ints[right] = ints[left];
}
ints[left] = base;
return left;
}
public static void sort(int[] ints, int left, int right){
if(left < right){
int mid = partition(ints, left, right);
sort(ints, left, mid - 1);
sort(ints, mid + 1, right);
}
}
public static void main(String[] args){
int[] ints = {2, 7, 3, 6, 5, 1};
System.out.println(Arrays.toString(ints));
sort(ints, 0, ints.length - 1);
System.out.println(Arrays.toString(ints));
}
}
..