代码:
1 public static void quickSort(int[] arr) {
2 if (arr == null || arr.length < 2) {
3 return;
4 }
5 quickSort(arr, 0, arr.length - 1);
6 }
7
8 public static void quickSort(int[] arr, int l, int r) {
9 if (l < r) {
10 swap(arr, l + (int) (Math.random() * (r - l + 1)), r);
11 int[] p = partition(arr, l, r);
12 quickSort(arr, l, p[0] - 1);
13 quickSort(arr, p[1] + 1, r);
14 }
15 }
16
17 public static int[] partition(int[] arr, int l, int r) {
18 int less = l - 1;
19 int more = r;
20 while (l < more) {
21 if (arr[l] < arr[r]) {
22 swap(arr, ++less, l++);
23 } else if (arr[l] > arr[r]) {
24 swap(arr, --more, l);
25 } else {
26 l++;
27 }
28 }
29 swap(arr, more, r);
30 return new int[] { less + 1, more };
31 }
32
33 public static void swap(int[] arr, int i, int j) {
34 int tmp = arr[i];
35 arr[i] = arr[j];
36 arr[j] = tmp;
37
理解:
什么是随机快速排序?
快速排序是在一个数组中,每次选定一个基准,然后把这个数组分为三部分(大于这个数的、等于这个数的、小于这个数的)
这三部分之中,等于标准数的这个部分,就是排好序的,它们不需要再动了。那么左右两边继续重复这个过程,在左边再次选择一个标准数,右边也是一样,重复到最后,所有数的位置也就固定了!随机快速排序是在这个基础之上,每次选定的那个数是随机产生的,普通快速排序可能会选择最右边的那个数或者最左边的数,这容易出现问题,比如 1234567 如果选定了7这个数,那么从左往右走一遍,最后发现比7小的本身都在左边,那么这一遍排序其实是浪费了的,所以选定的那个数的位置很重要!
partition这个方法的作用是返回每次快排之后那个数组的小于区的最右边界以及大于区的最左边界!是一个长度为2的数组!
递归方法:先对左侧递归完成左侧排序,再对右侧递归,完成右边排序,最终整体有序!