一、思路分析
快速排序(QuickSort)是对冒泡排序的一种改进。基本思想是:通过一趟排序将要排序的数据分成独立的两部分,左部分所有数据都小于右部分所有数据,然后再按照这种方法分别对这两部分进行快速排序,直到整体都是一个有序的序列。
二、图解
上述图片是一次使用pivot(中轴值)待排序序列分割成两部分的图解,接下来需要对两边的待排序序列分别使用快速排序,最终整个序列就会变成有序序列。
三、代码
package com.recorsion;
import java.util.Arrays;
public class QuickSort {
public static void main(String[] args) {
int[] arr = { -9, 10, 0, 23, -20, 40 };
quickSort(arr, 0, arr.length - 1);
System.out.println(Arrays.toString(arr));
}
/**
* 快速排序
* @param arr 数组
* @param startIndex 对[startIndex, endIndex]中的数据排序
* @param endIndex
*/
public static void quickSort(int[] arr, int startIndex, int endIndex) {
// 当待排序序列有数据时,才能排序
if (startIndex < endIndex) {
// 记录下待排序序列的开始索引和结束索引
int left = startIndex;
int right = endIndex;
// 将待排序序列的第一个值作为中轴值,小于该值的数据放在其左边,大于该值的数据放在其右边
int pivot = arr[left];
while (left < right) {
// 先从待排序右边查找小于中轴值的数据
while (left < right && arr[right] >= pivot) {
right--;
}
// 满足条件说明找到第一个小于pivot的数据,将其放在左边
if (left < right) {
arr[left] = arr[right];
left++;
}
// 然后从左边查找一个大于中轴值的数据
while (left < right && arr[left] <= pivot) {
left++;
}
// 满足条件说明找到一个大于pivot的数据,将其放在右边
if (left < right) {
arr[right] = arr[left];
right--;
}
}
// 最后循环结束时,left=right,将pivot的值放在left的位置
// 此时就将待排序序列分成两部分了,小于pivot的在左边,大于pivot的在右边
arr[left] = pivot;
// 递归将上面分成的两部分分别使用快速排序
quickSort(arr, startIndex, left - 1);
quickSort(arr, left + 1, endIndex);
}
}
public static void quickSort1(int[] arr, int start, int end) {
int left = start;
int right = end;
int pivot = arr[(left + right) / 2];
}
}