Java代碼實現快速排序(QuickSort)

Java代碼實現快速排序(QuickSort)

核心思想

若是要排序數組中下標從p到r之間的一組數據,咱們選擇p到r之間的任意一個數據爲pivot(分區點)。git

咱們遍歷p到r之間的數據,將小於pivot的放到左邊,將大於pivot的放到右邊,將pivot放到中間。通過這一步驟以後,數組p到r之間的數據就被分紅了三個部分,前面p到q-1之間都是小於pivot的,中間是pivot,後面的q=1到r之間是大於pivot的。 github

根據分治、遞歸的處理思想,咱們能夠用遞歸排序下標從p到q-1之間的數據和下標爲q+1到r以前的數據,直到區間縮小爲1,就說明全部的數據都有序了。數組

Java代碼實現

public class QuickSort {

    /**
     * 快速排序
     *
     * @param a
     * @param n
     */
    public static void quickSort(int[] a, int n) {
        quickSortRecursive(a, 0, n - 1);
    }

    /**
     * 快速排序遞歸函數,p,r爲下標。
     *
     * @param a
     * @param p
     * @param r
     */
    public static void quickSortRecursive(int[] a, int p, int r) {
        if (p >= r) {
            return;
        }
        // 獲取分區點
        int q = partition(a, p, r);
        quickSortRecursive(a, p, q - 1);
        quickSortRecursive(a, q + 1, r);
    }

    public static int partition(int[] a, int p, int r) {
        int pivot = a[r];
        int i = p;
        for (int j = p; j < r; j++) {
            if (a[j] < pivot) {
                int t = a[i];
                a[i] = a[j];
                a[j] = t;
                i++;
            }
        }
        int t = a[i];
        a[i] = a[r];
        a[r] = t;
        return i;
    }
}
複製代碼

測試代碼:bash

int size = 10;
        if (size <= 0) {
            throw new IllegalArgumentException("size cannot bo lower than 0");
        }
        int[] a = SortUtils.generateRandomArray(size, 100);
        System.out.println("快速排序:");
        System.out.println(SortUtils.getArrayToString(a));
        QuickSort.quickSort(a, size);
        System.out.println(SortUtils.getArrayToString(a));
        System.out.println();
複製代碼

測試結果:符合預期。dom

I/System.out: 快速排序:
I/System.out: [63,81,43,54,37,84,45,97,50,87]
I/System.out: [37,43,45,50,54,63,81,84,87,97]
複製代碼

完整代碼請查看

項目中搜索QuickSort便可。 github傳送門 github.com/tinyvampire…函數

gitee傳送門 gitee.com/tinytongton…測試

參考: 排序(下):如何用快排思想在O(n)內查找第K大元素?ui

相關文章
相關標籤/搜索