数据结构与算法-java实现快速排序

之前学习的几个排序又忘记了,今天回顾《数据结构与算法(java描述)》这本书的时候才又不得不花时间来搞懂,其中比较难理解和难实现的就是堆排序和快速排序了吧。

快速排序的算法:

数据结构与算法-java实现快速排序_第1张图片

实现代码:

    private static final int CUTOFF = 3;
    
    public static >
    void quickSort(AnyType[] arr) {
        quickSort(arr, 0, arr.length - 1);
    }

    private static >
    void quickSort(AnyType[] a, int left, int right) {
        if (left == right) {
            return;
        }
        if (left + CUTOFF <= right) {
            AnyType pivot = median3(a, left, right);

            // Begin partitioning
            int i = left, j = right - 1;
            for (; ; ) {
                while (a[++i].compareTo(pivot) < 0) {
                }
                while (a[--j].compareTo(pivot) > 0) {
                }
                if (i < j)
                    swapReferences(a, i, j);
                else
                    break;
            }

            swapReferences(a, i, right - 1);   // Restore pivot

            quickSort(a, left, i - 1);    // Sort small elements
            quickSort(a, i + 1, right);
        } else {
            insertionSort(a);
        }
    }

    private static >
    void insertionSort(AnyType[] a, int left, int right) {
        for (int p = left + 1; p <= right; p++) {
            AnyType tmp = a[p];
            int j;

            for (j = p; j > left && tmp.compareTo(a[j - 1]) < 0; j--)
                a[j] = a[j - 1];
            a[j] = tmp;
        }
    }

    private static >
    AnyType median3(AnyType[] a, int left, int right) {
        int center = (left + right) / 2;
        if (a[center].compareTo(a[left]) < 0)
            swapReferences(a, left, center);
        if (a[right].compareTo(a[left]) < 0)
            swapReferences(a, left, right);
        if (a[right].compareTo(a[center]) < 0)
            swapReferences(a, center, right);

        // Place pivot at position right - 1
        swapReferences(a, center, right - 1);
        return a[right - 1];
    }

    public static  void swapReferences(AnyType[] a, int index1, int index2) {
        AnyType tmp = a[index1];
        a[index1] = a[index2];
        a[index2] = tmp;
    }

 

你可能感兴趣的:(数据结构与算法,java)