https://blog.csdn.net/nrsc272420199/article/details/82587933
快速排序法介绍
快速排序(Quicksort)是对冒泡排序的一种改进。快速排序,说白了就是给基准数据找其正确索引位置的过程.
基本思想是
1.先从数列中取出第一个数作为基准数。
2.分区过程,将比这个数大的数全放到它的右边,小于或等于它的数全放到它的左边。
3.再对左右区间重复第二步,直到各区间只有一个数。
图解:
a、假设最开始的基准数据为数组第一个元素-9,则首先用一个临时变量去存储基准数据,即temp=-9;然后分别从数组的两端扫描数组,设两个指示标志:low指向起始位置,high指向末尾.
low:0 | 1 | 2 | 3 | high:4 |
---|---|---|---|---|
-9 | 78 | 0 | 23 | -88 |
b、首先从后半部分开始,如果扫描到的值大于基准数据就让high减1,如果发现有元素比该基准数据的值小(如上图中-88<=temp),则arr[low]=arr[high] ,结果如下:
low:0 | 1 | 2 | 3 | high:4 |
---|---|---|---|---|
-88 | 78 | 0 | 23 | -88 |
c、然后开始从前往后扫描,如果扫描到的值小于基准数据就让low加1,如果发现有元素大于基准数据的值(如上图78=>temp),arr[high]=arr[low],指针移动并且数据交换后的结果如下:
0 | low:1 | 2 | 3 | high:4 |
---|---|---|---|---|
-88 | 78 | 0 | 23 | 78 |
d、然后再开始从后往前遍历,直到low=high结束循环,此时low或high的下标就是基准数据-9在该数组中的正确索引位置.如下图所示.
0 | high:low:1 | 2 | 3 | 4 |
---|---|---|---|---|
-88 | 78 | 0 | 23 | 78 |
e、此时low=high,arr[low]=temp,就为-9找到了正确的位置
0 | high:low:1 | 2 | 3 | 4 |
---|---|---|---|---|
-88 | -9 | 0 | 23 | 78 |
f、然后采用递归的方式分别对前半部分和后半部分进行快速排序abcde,当前半部分和后半部分均有序时该数组就自然有序了。
代码实现
package com.liang.sort;
import java.util.Arrays;
public class QuickSort {
public static void main(String[] args) {
int[] arr= {-9,78,0,23,-567};
quickSort(arr,0,arr.length-1);
System.out.println(Arrays.toString(arr));
}
public static void quickSort(int[] arr,int low,int high) {
if(low<high) {
// 找寻基准数据的正确索引
int index=getIndex(arr, low, high);
//左递归
quickSort(arr, low, index - 1);
//右递归
quickSort(arr, index + 1, high);
}
}
public static int getIndex(int[] arr,int low,int high) {
int temp=arr[low];//基准数据
while(low<high) {
// 当队尾的元素大于等于基准数据时,向前挪动high指针
while(low<high && arr[high]>=temp) {
high--;
}
// 如果队尾元素小于temp了,需要将其赋值给low
arr[low]=arr[high];
// 当队首元素小于等于tmp时,向前挪动low指针
while(low<high && arr[low]<=temp) {
low++;
}
// 当队首元素大于temp时,需要将其赋值给high
arr[high]=arr[low];
}
//跳出循环,此时low=high,此时的low或high就是temp的正确索引位置
arr[low]=temp;
return low;
}
}