【经典排序算法 time: 2023-10-12】快速排序(单边)

  1. 原理
    每次以最右边的值作为基准数,每次循环找到小于基准数的数,放到左边(动态演示)
  2. 代码(包含部分双边快排代码实现)
public class QuickSort {
    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        int[] arr2 = {11, 23, 69, 99, 3, 1, 45, 67, 5, 234, 678, 999, 7, 123};
        quick1(arr2, 0, arr2.length - 1);
//        quick2(arr2, 0, arr2.length - 1);
//        partitionDouble(arr2,0,arr2.length-1);
        System.out.println(Arrays.toString(arr2));

        System.out.println(System.currentTimeMillis() - start);
    }

    private static void quick1(int[] arr2, int s, int l) {
        if (s >= l) {
            return;
        }
        int index = partition(arr2, s, l);
        // 左边界分区快排
        quick1(arr2, s, index - 1);
        // 左边界分区快排
        quick1(arr2, index + 1, l);
        System.out.println(Arrays.toString(arr2));

    }

    private static void quick2(int[] arr2, int s, int l) {
        if (s >= l) {
            return;
        }
        int index = partitionDouble(arr2, s, l);
        // 左边界分区快排
        quick2(arr2, s, index - 1);
        // 左边界分区快排
        quick2(arr2, index + 1, l);
        System.out.println(Arrays.toString(arr2));

    }

    private static int partition(int[] arr2, int s, int l) {
        int t = arr2[l];
        int i = s;
        for (int j = s; j < l; j++) {
            if (arr2[j] < t) {
                if (i != j) {
                    swap(arr2, i, j);
                }
                i++;
            }
        }
        if (i != l) {
            swap(arr2, i, l);
        }
        return i;
    }

    /**
     * 双边分区
     *
     * @param arr2
     * @param s
     * @param l
     * @return
     */
    private static int partitionDouble(int[] arr2, int s, int l) {
        int t = arr2[l];
        int i = s;
        int j = l;
        while (i < j) {
            while (i < j && arr2[j] > t) {
                j--;
            }
            while (i < j && arr2[i] <= t) {
                i++;
            }
            swap(arr2, i, j);
        }
        swap(arr2, s, j);
        return j;
    }


    public static void swap(int[] a, int i, int j) {
        int t = a[i];
        a[i] = a[j];
        a[j] = t;
    }
}

你可能感兴趣的:(排序算法,排序算法,算法,java)