1、快速排序的思想
快速排序就是给基准数据找在数组中正确位置的过程,一旦基准位置的正确位置找到,那基准位置左右两边经过同样的步骤递归也可以有序,最终整体数组有序。
整体可以理解为三个步骤:
1、先从队尾开始向前扫描且当low < high时,如果arr[high] > tmp ,则high – ,如果arr[high] < tmp ,则将high的值赋给low, 即arr[low] = arr[high] ,赋值后必转换扫描方向,即从队首向队尾扫描 ;
2、从队首向队尾扫描时且当low < high, 如果arr[low] < tmp , 则low ++ , 如果arr[low] > tmp ,则将low的值赋给high, 即arr[high] = arr[low] ,赋值后必转换扫描方向,即从队尾想队首扫描 ;
3、不断重复步骤1和2 ,直到low = high时,low或high的位置就是该基准数据在数组中的正确索引位置。
2、快速排序的引用图解
3、JAVA代码实现
package Sort;
/**
* Created by grant on 2019/11/22.
* 快速排序的本质就是把比基准数大的都放到基准数的右边,比基准数小的都放在基准数左边,之后基准数左边和右边进行递归再次快速排序,
* 左右部分均有序,即完成排序。
* 1、先从队尾开始向前扫描且当low < high时,如果arr[high] > tmp ,则high -- ,如果arr[high] < tmp ,则将high的值赋给low,
* 即arr[low] = arr[high] ,赋值后必转换扫描方向,即从队首向队尾扫描
* 2、从队首向队尾扫描时且当low < high, 如果arr[low] < tmp , 则low ++ , 如果arr[low] > tmp ,则将low的值赋给high,
* 即arr[high] = arr[low] ,赋值后必转换扫描方向,即从队尾想队首扫描
* 3、不断重复步骤1和2 ,直到low = high时,low或high的位置就是该基准数据在数组中的正确索引位置。
*/
public class QuickSort {
public static void main(String[] args) {
int arr[] = { 49, 38, 65, 97, 23, 22, 76, 1, 5, 8, 2, 0, -1, 22};
quickSort(arr,0,arr.length -1);
for (int i : arr) {
System.out.println(i);
}
}
public static void quickSort(int[] arr,int low,int high){
if(low < high){
//寻找基准数据的正确索引位置
int index = getIndex(arr,low,high);
//找到基准数据的索引位置后再递归的对基准数据左边和右边的进行相同操作使左右也有序。
quickSort(arr,0,index -1);
quickSort(arr,index +1,high);
}
}
private static int getIndex(int[] arr, int low, int high) {
//一般取队首第一个元素作为基准元素,即
int tmp = arr[low];
while (low < high){
while (low < high && arr[high] >= tmp){
high --;
}
//如果队尾元素也就是arr[high]>tmp了,就把high的值赋给low,转变扫描方向
arr[low] = arr[high];
//赋完值都会改变扫描方向
//当队首元素小于基准元素了,也就是arr[low]<tmp,则继续向后扫描
while (low < high && arr[low] <= tmp){
low ++;
}
//如果队首元素大于基准元素tmp 也就是arr[low] > tmp,就把low的值赋给high,转变扫描方向
arr[high] = arr[low];
}
//high和low相等时,跳出循环,此时low或high为tmp基准元素的正确索引位置
//所以将基准值赋给正确位置arr[low]
arr[low] = tmp;
return low;//将基准值的索引位置返回
}
}
-1
0
1
2
5
8
22
22
23
38
49
65
76
97
Process finished with exit code 0