快速排序(Quick Sort)使用分治法策略。
它的基本思想是:选择一个基准数,通过一趟排序将要排序的数据分割成独立的两部分;其中一部分的所有数据都比另外一部分的所有数据都要小。然后,再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列。
快速排序流程:
(1) 从数列中挑出一个基准值。
(2) 将所有比基准值小的摆放在基准前面,所有比基准值大的摆在基准的后面(相同的数可以到任一边);在这个分区退出之后,该基准就处于数列的中间位置。
(3) 递归地把"基准值前面的子数列"和"基准值后面的子数列"进行排序。
示例代码

package paixu; /** * * @author 臭屁豬 * @date 2016/12/8 */ public class QuickSort { /* * 快速排序 * * 参数说明: a -- 待排序的数组 l -- 数组的左边界(例如,从起始位置开始排序,则l=0) r -- * 数组的右边界(例如,排序截至到数组末'尾,则r=a.length-1) */ public static void quickSort(int[] a, int l, int r) { if (l < r) { int i, j, x; i = l; j = r; x = a[i]; while (i < j) { while (i < j && a[j] > x)// 如果右边的数一直大于x,就一直循环,直到小于x j--; // 从右向左找第一个小于x的数 if (i < j)// 小于x跳出循环后 ,如果符合条件,交换位置 看是否i==j,如果相等(表示这一轮已经循环完毕) a[i++] = a[j]; while (i < j && a[i] < x) i++; // 从左向右找第一个大于x的数 if (i < j) a[j--] = a[i]; } a[i] = x; for (int k : a) { System.out.print(k + " "); } System.out.println(); quickSort(a, l, i - 1); /* 递归调用 */ quickSort(a, i + 1, r); /* 递归调用 */ } } public static void main(String[] args) { int i; int a[] = { 30, 40, 60, 10, 20, 50 }; System.out.printf("before sort:"); for (i = 0; i < a.length; i++) System.out.printf("%d ", a[i]); System.out.printf(" "); quickSort(a, 0, a.length - 1); System.out.printf("after sort:"); for (i = 0; i < a.length; i++) System.out.printf("%d ", a[i]); System.out.printf(" "); } }