1、选取一个基准值(选取间的最左边)
2、对区间内的元素进行partition。partition的结果是比基准值小的放在左边,比基准值大的放在右边。
3、分别对左右区间分别进行1.2部操作。
4、结束终止条件——当区间所剩元素值小于等于1即可。
import java.util.Arrays;
public class QuickSort1 {
public static void quickSort(long array[]){
quickSortInternal(array,0,array.length-1);
}
private static void quickSortInternal(long[] array, int lowIndex, int highIndex) {
int size = highIndex - lowIndex + 1;
if (size <= 1) {
return;
}
// partition 过程中隐含着选择基准值的过程
// 返回最终基准值所在下标
int pivotIndex = partition(array, lowIndex, highIndex);
// 左区间: [lowIndex, pivotIndex - 1]
// 对左区间按照相同方式处理
quickSortInternal(array, lowIndex, pivotIndex - 1);
// 右区间: [pivotIndex + 1, highIndex]
// 对右区间按照相同方式处理
quickSortInternal(array, pivotIndex + 1, highIndex);
}
private static int partition(long array[],int lowIndex,int highIndex){
//Hover方法
int leftIndex=lowIndex;
int rightIndex=highIndex;
long pivot=array[leftIndex];
//左右不相遇 继续
while (leftIndex<rightIndex){
//右边先开始
while (pivot<=array[rightIndex] && leftIndex<rightIndex){
rightIndex--;
}
//左边
while (pivot>=array[leftIndex] && leftIndex<rightIndex){
leftIndex++;
}
swap(array,rightIndex,leftIndex);
}
swap(array,lowIndex,leftIndex);
return leftIndex;
}
private static void swap(long array[],int index1,int index2){
long t=array[index1];
array[index1]=array[index2];
array[index2]=t;
}
public static void main(String[] args) {
long[]array={4,9,1,2,7,3,8,5,6,0};
System.out.println(Arrays.toString(array));
quickSort(array);
System.out.println(Arrays.toString(array));
}
}
快排的partition过程有三种方法
其他两种分别是:
1、挖坑法
这种方法相似于Hover方法,其代码部分
//挖坑方法
private static int partition2(long[]array,int lowIndex,int highIndex){
int leftIndex=lowIndex;
int rightIndex=highIndex;
long pivot=array[lowIndex];
while (rightIndex!=leftIndex){
while (array[rightIndex]>=pivot && rightIndex!=leftIndex){
rightIndex--;
}
array [leftIndex]= array[rightIndex];
while (array[leftIndex]<=pivot && rightIndex!=leftIndex){
leftIndex++;
}
array[rightIndex]=array[leftIndex];
}
array[leftIndex]=pivot;
return leftIndex;
}
2、第三种方法
private static int partition3 (long[]array,int lowIndex,int highIndex){
//开始时 分界线与index 在同一位置
//if array[index]<基准值 swap(分界线,index)index++,分界线++
//if array[index]>基准值index++
//array[分界线]>基准值 同时array[分-1]<基准值
//Finally swap(分界线-1,lowIndex)
int index=lowIndex+1;
int f=lowIndex+1;
long pivot=array[lowIndex];
while (index<=highIndex){
if (array[index]<=pivot){
Util.swap(array,f,index);
index++;
f++;
}else{
index++;
}
}
Util.swap(array,f-1,lowIndex);
return f-1;
}
时间复杂度:
最好/平均:O(n*log(n))
最坏:O(n^2)
空间复杂度:
最好/平均:O(log(n))
最坏:O(n)