package com.thinker.suanfa.sort;

/**
 * @author lzh
 * @apiNote 快速排序，小到大
 */
public class FastSort {

    /**
     * @param arr  arr
     * @param low  low
     * @param high high
     * @return int
     * @apiNote get the location of arr[low] after sorted
     */
    private static int getMiddle(int[] arr, int low, int high) {
        int tmp = arr[low];
        while (low < high) {
            while (low < high && arr[high] >= tmp) {
                high--;
            }
            arr[low] = arr[high];
            while (low < high && arr[low] <= tmp) {
                low++;
            }
            arr[high] = arr[low];
        }
        arr[low] = tmp;
        return low;
    }

    private static void fastSort(int[] arr, int low, int high) {

        if (low < high) {
            int middle = getMiddle(arr, low, high);
            fastSort(arr, low, middle - 1);
            fastSort(arr, middle + 1, high);
        }

    }

    public static void main(String[] args) {
        int[] arr = new int[]{4, 2, 6, 8, 9, 3, 1, 5};
        long begin = System.nanoTime();
        fastSort(arr, 0, arr.length - 1);
        long end = System.nanoTime();
        for (int a : arr) {
            System.out.print(a + "\t");
        }
        System.out.println("\nrun time:" + (double) (end - begin) / 1000 + " ms");
    }
}
