排序算法

java排序算法

package me.itzhu.arrays;

import java.util.Arrays;

/**
 * Created by itzhu on 2017/6/6 0006.
 * desc arrays 源码分析
 * 1.了解几种排序
 * 2.测试个排序方法,与jdk方法进行比较
 * 3.分析Arrays.sort(int[] num)源码(未完成)
 * 参考以及copy:
 * http://www.cnblogs.com/0201zcr/p/4764427.html
 * http://www.cnblogs.com/0201zcr/p/4763806.html
 * http://www.cnblogs.com/0201zcr/p/4764705.html
 */
public class Arrays1 {

    public static void main(String... args) {
        int[] nums = new int[]{46, 45, 254, 64, 49, 45, 344, 13, 48, 34};

        //冒泡排序
        //bubbleSort(nums);

        //快速排序
        //QuickSort.sort(nums);

        //选择排序
        //selectSort(nums);

        //插入排序
        //insertSort(nums);

        //希尔排序
        //shellSort(nums);

        //归并排序
        //MergeSort.sort(nums);

        //堆排序
        HeapSort.sort(nums);

        //jdk内置排序方法-源码查看Arrays1Test
        //Arrays.sort(nums);

        printArr(nums);
    }


    /**
     * 打印数字
     *
     * @param nums
     */
    public static void printArr(int[] nums) {
        for (int i : nums) {
            System.out.print(i + ",");
        }
        System.out.println("  ");
    }

    /**
     * 冒泡排序
     *
     * @param nums
     */
    public static void bubbleSort(int[] nums) {
        int temp = 0;
        int size = nums.length;
        for (int i = 0; i < size; i++) {
            for (int j = i + 1; j < size; j++) {
                if (nums[i] > nums[j]) {
                    temp = nums[i];
                    nums[i] = nums[j];
                    nums[j] = temp;
                }
            }
        }
    }

    /**
     * 选择排序
     * 在未排序序列中找到最小元素,存放到排序序列的起始位置
     * 再从剩余未排序元素中继续寻找最小元素,然后放到排序序列末尾。
     * 以此类推,直到所有元素均排序完毕。
     *
     * @param nums
     */
    public static void selectSort(int[] nums) {
        int temp = 0;
        int size = nums.length;
        for (int i = 0; i < size; i++) {
            int k = i;
            for (int j = i + 1; j < size; j++) {
                if (nums[k] > nums[j]) {
                    k = j;
                }
            }
            temp = nums[i];
            nums[i] = nums[k];
            nums[k] = temp;
        }
    }

    /**
     * 插入排序
     * 1从第一个元素开始,该元素可以认为已经被排序
     * 2取出下一个元素,在已经排序的元素序列中从后向前扫描
     * 3如果该元素(已排序)大于新元素,将该元素移到下一位置
     * 4重复步骤3,直到找到已排序的元素小于或者等于新元素的位置
     * 5将新元素插入到该位置中
     * 6重复步骤2
     * <p>
     * 时间复杂度:O(n^2).
     *
     * @param nums
     */
    public static void insertSort(int[] nums) {
        int size = nums.length;
        int currentValue = 0;
        int j = 0;
        for (int i = 1; i < size; i++) {
            currentValue = nums[i];//取出当前需要插入的元素
            for (j = i; j > 0 && currentValue < nums[j - 1]; j--) {
                nums[j] = nums[j - 1];
            }
            nums[j] = currentValue;
        }
    }

    /**
     * 希尔排序的原理:根据需求,如果你想要结果从大到小排列,它会首先将数组进行分组,然后将较大值移到前面,较小值
     * 移到后面,最后将整个数组进行插入排序,这样比起一开始就用插入排序减少了数据交换和移动的次数,可以说希尔排序是加强
     * 版的插入排序
     * 拿数组5, 2, 8, 9, 1, 3,4来说,数组长度为7,当increment为3时,数组分为两个序列
     * 5,2,8和9,1,3,4,第一次排序,9和5比较,1和2比较,3和8比较,4和比其下标值小increment的数组值相比较
     * 此例子是按照从大到小排列,所以大的会排在前面,第一次排序后数组为9, 2, 8, 5, 1, 3,4
     * 第一次后increment的值变为3/2=1,此时对数组进行插入排序,
     * 实现数组从大到小排
     * // TODO: 2017/6/6 0006 没有搞明白
     */
    public static void shellSort(int[] data) {
        int j = 0;
        int temp = 0;
        //每次将步长缩短为原来的一半
        for (int increment = data.length / 2; increment > 0; increment /= 2) {
            for (int i = increment; i < data.length; i++) {
                temp = data[i];
                for (j = i; j >= increment; j -= increment) {
                    if (temp < data[j - increment]) {//如想从小到大排只需修改这里
                        data[j] = data[j - increment];
                    } else {
                        break;
                    }
                }
                data[j] = temp;
            }
        }
    }
}

/**
 * 归并排序
 * 简介:将两个(或两个以上)有序表合并成一个新的有序表
 * 即把待排序序列分为若干个子序列,每个子序列是有序的。然后再把有序子序列合并为整体有序序列
 * 时间复杂度为O(nlogn)
 * 稳定排序方式
 */
class MergeSort {

    /**
     * @param nums 待排序数组
     * @param low  待排的开始位置
     * @param high 待排结束位置
     * @return 输出有序数组
     */
    public static void sort(int[] nums, int low, int high) {
        int mid = (low + high) / 2;
        if (low < high) {
            // 左边
            sort(nums, low, mid);
            // 右边
            sort(nums, mid + 1, high);
            // 左右归并
            merge(nums, low, mid, high);
        }
    }

    public static void sort(int[] nums) {
        sort(nums, 0, nums.length - 1);
    }

    /**
     * 将数组中low到high位置的数进行排序
     *
     * @param nums 待排序数组
     * @param low  待排的开始位置
     * @param mid  待排中间位置
     * @param high 待排结束位置
     */

    private static void merge(int[] nums, int low, int mid, int high) {
        int[] temp = new int[high - low + 1];
        int i = low;// 左指针
        int j = mid + 1;// 右指针
        int k = 0;

        // 把较小的数先移到新数组中
        while (i <= mid && j <= high) {
            if (nums[i] < nums[j]) {
                temp[k++] = nums[i++];
            } else {
                temp[k++] = nums[j++];
            }
        }

        // 把左边剩余的数移入数组
        while (i <= mid) {
            temp[k++] = nums[i++];
        }

        // 把右边边剩余的数移入数组
        while (j <= high) {
            temp[k++] = nums[j++];
        }

        // 把新数组中的数覆盖nums数组
        for (int k2 = 0; k2 < temp.length; k2++) {
            nums[k2 + low] = temp[k2];
        }
    }
}

/**
 * 快速排序是通常被认为在同数量级(O(nlog2n))的排序方法中平均性能最好的。
 * 但若初始序列按关键码有序或基本有序时,快排序反而蜕化为冒泡排序。
 * 为改进之,通常以“三者取中法”来选取基准记录,即将排序区间的两个端点与中点三个记录关键码居中的调整为支点记录。
 * 快速排序是一个不稳定的排序方法。
 */
class QuickSort {

    /**
     * 查找出中轴(默认是最低位low)的在numbers数组排序后所在位置
     *
     * @param numbers 带查找数组
     * @param low     开始位置
     * @param high    结束位置
     * @return 中轴所在位置
     */
    private static int getMiddle(int[] numbers, int low, int high) {
        int temp = numbers[low]; //数组的第一个作为中轴
        while (low < high) {
            while (low < high && numbers[high] >= temp) {//从右向左找第一个//小于等于基准值得index
                high--;
            }
            numbers[low] = numbers[high];//比中轴小的记录移到低端
            while (low < high && numbers[low] <= temp) {//从左向右找第一个//大于等于基准值的index
                low++;
            }
            numbers[high] = numbers[low]; //比中轴大的记录移到高端
        }
        numbers[low] = temp; //中轴记录到尾
        return low; // 返回中轴的位置
    }

    /**
     * @param numbers 带排序数组
     * @param low     开始位置
     * @param high    结束位置
     */
    private static void quickSort(int[] numbers, int low, int high) {
        if (low < high) {
            int middle = getMiddle(numbers, low, high); //将numbers数组进行一分为二
            quickSort(numbers, low, middle - 1);   //对低字段表进行递归排序
            quickSort(numbers, middle + 1, high); //对高字段表进行递归排序
        }
    }

    /**
     * 快速排序
     *
     * @param numbers 带排序数组
     */
    public static void sort(int[] numbers) {
        if (numbers.length > 0) {   //查看数组是否为空
            quickSort(numbers, 0, numbers.length - 1);
        }
    }
}

/**
 * 堆排序
 */
class HeapSort {
//    public static void main(String[] args) {
//        int[] a = {49, 38, 65, 97, 76, 13, 27, 49, 78, 34, 12, 64};
//        int arrayLength = a.length;
//        //循环建堆
//        for (int i = 0; i < arrayLength - 1; i++) {
//            //建堆
//            buildMaxHeap(a, arrayLength - 1 - i);
//            //交换堆顶和最后一个元素
//            swap(a, 0, arrayLength - 1 - i);
//            System.out.println(Arrays.toString(a));
//        }
//    }

    public static void sort(int[] nums) {
        int size = nums.length;
        //循环建堆
        for (int i = 0; i < size - 1; i++) {
            //建堆
            buildMaxHeap(nums, size - 1 - i);
            //交换堆顶和最后一个元素
            swap(nums, 0, size - 1 - i);
        }
    }

    //对data数组从0到lastIndex建大顶堆
    public static void buildMaxHeap(int[] data, int lastIndex) {
        //从lastIndex处节点(最后一个节点)的父节点开始
        for (int i = (lastIndex - 1) / 2; i >= 0; i--) {
            //k保存正在判断的节点
            int k = i;
            //如果当前k节点的子节点存在
            while (k * 2 + 1 <= lastIndex) {
                //k节点的左子节点的索引
                int biggerIndex = 2 * k + 1;
                //如果biggerIndex小于lastIndex,即biggerIndex+1代表的k节点的右子节点存在
                if (biggerIndex < lastIndex) {
                    //若果右子节点的值较大
                    if (data[biggerIndex] < data[biggerIndex + 1]) {
                        //biggerIndex总是记录较大子节点的索引
                        biggerIndex++;
                    }
                }
                //如果k节点的值小于其较大的子节点的值
                if (data[k] < data[biggerIndex]) {
                    //交换他们
                    swap(data, k, biggerIndex);
                    //将biggerIndex赋予k,开始while循环的下一次循环,重新保证k节点的值大于其左右子节点的值
                    k = biggerIndex;
                } else {
                    break;
                }
            }
        }
    }

    //交换
    private static void swap(int[] data, int i, int j) {
        int tmp = data[i];
        data[i] = data[j];
        data[j] = tmp;
    }
}

/**
 * Arrays.sort()源码
 * Arrays1测试方法
 */
class Arrays1Test {

    /*--------------源码------  java version 1.8.0_121 -------*/
    /**
     *
     * @explain :
     * 这里不保证各方法的翻译正确,中文只用于辅助参考
     *
     * 下面有几种排序方式
     * 1.快速排序  Quicksort
     * 2.插入排序  insertion sort
     * 3.合并排序  merge sort
     *
     * */

    /**
     * If the length of an array to be sorted is less than this
     * constant, insertion sort is used in preference to Quicksort.
     * <p>
     * 如果要排序的数组的长度小于这个常量,插入排序优先于快速排序。
     * INSERTION_SORT_THRESHOLD = 47
     */
    private static final int INSERTION_SORT_THRESHOLD = 47;

    /**
     * The maximum length of run in merge sort.
     * <P></P>
     * 归并排序的最大长度。
     * MAX_RUN_LENGTH = 33
     */
    private static final int MAX_RUN_LENGTH = 33;

    /**
     * If the length of an array to be sorted is less than this
     * constant, Quicksort is used in preference to merge sort.
     * <p>
     * 如果要排序的数组的长度小于这个常量,快速排序被用于合并排序。
     * QUICKSORT_THRESHOLD = 286
     */
    private static final int QUICKSORT_THRESHOLD = 286;


    /**
     * The maximum number of runs in merge sort.
     * 归并排序中最大的运行数。
     * MAX_RUN_COUNT = 67
     */
    private static final int MAX_RUN_COUNT = 67;

    /**
     * Sorts the specified range of the array using the given
     * workspace array slice if possible for merging
     * <p>
     * 对数组指定区间进行排序,索引从left到right区间的数将会被排序,其他数位置不变
     *
     * @param a        the array to be sorted -需要排序的数组
     * @param left     the index of the first element, inclusive, to be sorted  -第一个元素的索引,包括,进行排序
     * @param right    the index of the last element, inclusive, to be sorted -最后一个元素的索引,包括,进行排序
     * @param work     a workspace array (slice) -一个工作区阵列(片)
     * @param workBase origin of usable space in work array -工作数组中可用空间的起源
     * @param workLen  usable size of work array -可用长度的工作数组
     */
    static void sort(int[] a, int left, int right,
                     int[] work, int workBase, int workLen) {
        // Use Quicksort on small arrays  - 如果排序长度小于QUICKSORT_THRESHOLD(286) 使用快速排序
        if (right - left < QUICKSORT_THRESHOLD) {
            sort(a, left, right, true);
            return;
        }

        /*
         * Index run[i] is the start of i-th run
         * (ascending or descending sequence).
         * Index run[i] 是从第i个数开始 (升序或降序)。
         * run的大小为(MAX_RUN_COUNT + 1)(68)
         */
        int[] run = new int[MAX_RUN_COUNT + 1];
        int count = 0;
        run[0] = left;

        // Check if the array is nearly sorted -检查数组是否接近被排序
        for (int k = left; k < right; run[count] = k) {
            if (a[k] < a[k + 1]) { // ascending-升序
                while (++k <= right && a[k - 1] <= a[k]) ;
            } else if (a[k] > a[k + 1]) { // descending-降序
                while (++k <= right && a[k - 1] >= a[k]) ;
                for (int lo = run[count] - 1, hi = k; ++lo < --hi; ) {
                    int t = a[lo];
                    a[lo] = a[hi];
                    a[hi] = t;
                }
            } else { // equal-相同
                for (int m = MAX_RUN_LENGTH; ++k <= right && a[k - 1] == a[k]; ) {
                    if (--m == 0) {
                        sort(a, left, right, true);
                        return;
                    }
                }
            }

            /*
             * The array is not highly structured,
             * use Quicksort instead of merge sort.
             * 数组不是高度结构化的,使用快速排序代替归并排序。
             *
             */
            if (++count == MAX_RUN_COUNT) {//++count是先++再运算
                sort(a, left, right, true);
                return;
            }
        }

        // Check special cases
        // Implementation note: variable "right" is increased by 1.
        if (run[count] == right++) { // The last run contains one element
            run[++count] = right;
        } else if (count == 1) { // The array is already sorted
            return;
        }

        // Determine alternation base for merge
        byte odd = 0;
        for (int n = 1; (n <<= 1) < count; odd ^= 1) ;

        // Use or create temporary array b for merging
        int[] b;                 // temp array; alternates with a
        int ao, bo;              // array offsets from 'left'
        int blen = right - left; // space needed for b
        if (work == null || workLen < blen || workBase + blen > work.length) {
            work = new int[blen];
            workBase = 0;
        }
        if (odd == 0) {
            System.arraycopy(a, left, work, workBase, blen);
            b = a;
            bo = 0;
            a = work;
            ao = workBase - left;
        } else {
            b = work;
            ao = 0;
            bo = workBase - left;
        }

        // Merging
        for (int last; count > 1; count = last) {
            for (int k = (last = 0) + 2; k <= count; k += 2) {
                int hi = run[k], mi = run[k - 1];
                for (int i = run[k - 2], p = i, q = mi; i < hi; ++i) {
                    if (q >= hi || p < mi && a[p + ao] <= a[q + ao]) {
                        b[i + bo] = a[p++ + ao];
                    } else {
                        b[i + bo] = a[q++ + ao];
                    }
                }
                run[++last] = hi;
            }
            if ((count & 1) != 0) {
                for (int i = right, lo = run[count - 1]; --i >= lo;
                     b[i + bo] = a[i + ao]
                        )
                    ;
                run[++last] = right;
            }
            int[] t = a;
            a = b;
            b = t;
            int o = ao;
            ao = bo;
            bo = o;
        }
    }

    /**
     * Sorts the specified range of the array by Dual-Pivot Quicksort.
     * 通过双主快速排序对数组的指定范围进行排序。
     *
     * @param a        the array to be sorted
     * @param left     the index of the first element, inclusive, to be sorted
     * @param right    the index of the last element, inclusive, to be sorted
     * @param leftmost indicates if this part is the leftmost in the range 这部分是否为最左边的那部分
     */
    private static void sort(int[] a, int left, int right, boolean leftmost) {
        int length = right - left + 1;

        // Use insertion sort on tiny arrays--排序数组长度小于47(需要排序的长度) ->使用插入排序
        if (length < INSERTION_SORT_THRESHOLD) {
            if (leftmost) {
                /*
                 * Traditional (without sentinel) insertion sort,
                 * optimized for server VM, is used in case of
                 * the leftmost part.
                 */
                for (int i = left, j = i; i < right; j = ++i) {
                    int ai = a[i + 1];
                    while (ai < a[j]) {
                        a[j + 1] = a[j];
                        if (j-- == left) {
                            break;
                        }
                    }
                    a[j + 1] = ai;
                }
            } else {
                /*
                 * Skip the longest ascending sequence.
                 */
                do {
                    if (left >= right) {
                        return;
                    }
                } while (a[++left] >= a[left - 1]);

                /*
                 * Every element from adjoining part plays the role
                 * of sentinel, therefore this allows us to avoid the
                 * left range check on each iteration. Moreover, we use
                 * the more optimized algorithm, so called pair insertion
                 * sort, which is faster (in the context of Quicksort)
                 * than traditional implementation of insertion sort.
                 *
                 * 相邻部分的每个元素都扮演哨兵的角色,因此这使得我们可以避免每次迭代的左范围检查。
                 * 此外,我们使用了更优化的算法,即所谓的对插入排序,它比传统的插入排序更快(在快速排序的环境中)。
                 *
                 */
                for (int k = left; ++left <= right; k = ++left) {
                    int a1 = a[k], a2 = a[left];

                    if (a1 < a2) {
                        a2 = a1;
                        a1 = a[left];
                    }
                    while (a1 < a[--k]) {
                        a[k + 2] = a[k];
                    }
                    a[++k + 1] = a1;

                    while (a2 < a[--k]) {
                        a[k + 1] = a[k];
                    }
                    a[k + 1] = a2;
                }
                int last = a[right];

                while (last < a[--right]) {
                    a[right + 1] = a[right];
                }
                a[right + 1] = last;
            }
            return;
        }

        /**
         * java中有三种移位运算符
         * <<      :     左移运算符,num << 1,相当于num乘以2
         * >>      :     右移运算符,num >> 1,相当于num除以2
         * >>>    :      无符号右移,忽略符号位,空位都以0补齐
         * */
        // Inexpensive approximation of length / 7 -类似于length/7--- int seventh = length/8 + length/64 + 1
        int seventh = (length >> 3) + (length >> 6) + 1;

        /*
         * Sort five evenly spaced elements around (and including) the
         * center element in the range. These elements will be used for
         * pivot selection as described below. The choice for spacing
         * these elements was empirically determined to work well on
         * a wide variety of inputs.
         *
         * 将5个均匀间隔的元素(包括)范围内的中心元素排序。
         * 这些元素将被用于主选择,如下所述,
         * 对这些元素进行间距的选择是根据经验决定的,在各种各样的输入上都能很好地工作。
         */
        int e3 = (left + right) >>> 1; // The midpoint
        int e2 = e3 - seventh;
        int e1 = e2 - seventh;
        int e4 = e3 + seventh;
        int e5 = e4 + seventh;

        // Sort these elements using insertion sort - 使用插入排序来排序这些元素
        if (a[e2] < a[e1]) {
            int t = a[e2];
            a[e2] = a[e1];
            a[e1] = t;
        }

        if (a[e3] < a[e2]) {
            int t = a[e3];
            a[e3] = a[e2];
            a[e2] = t;
            if (t < a[e1]) {
                a[e2] = a[e1];
                a[e1] = t;
            }
        }
        if (a[e4] < a[e3]) {
            int t = a[e4];
            a[e4] = a[e3];
            a[e3] = t;
            if (t < a[e2]) {
                a[e3] = a[e2];
                a[e2] = t;
                if (t < a[e1]) {
                    a[e2] = a[e1];
                    a[e1] = t;
                }
            }
        }
        if (a[e5] < a[e4]) {
            int t = a[e5];
            a[e5] = a[e4];
            a[e4] = t;
            if (t < a[e3]) {
                a[e4] = a[e3];
                a[e3] = t;
                if (t < a[e2]) {
                    a[e3] = a[e2];
                    a[e2] = t;
                    if (t < a[e1]) {
                        a[e2] = a[e1];
                        a[e1] = t;
                    }
                }
            }
        }

        // Pointers
        int less = left;  // The index of the first element of center part
        int great = right; // The index before the first element of right part

        if (a[e1] != a[e2] && a[e2] != a[e3] && a[e3] != a[e4] && a[e4] != a[e5]) {
            /*
             * Use the second and fourth of the five sorted elements as pivots.
             * These values are inexpensive approximations of the first and
             * second terciles of the array. Note that pivot1 <= pivot2.
             */
            int pivot1 = a[e2];
            int pivot2 = a[e4];

            /*
             * The first and the last elements to be sorted are moved to the
             * locations formerly occupied by the pivots. When partitioning
             * is complete, the pivots are swapped back into their final
             * positions, and excluded from subsequent sorting.
             */
            a[e2] = a[left];
            a[e4] = a[right];

            /*
             * Skip elements, which are less or greater than pivot values.
             */
            while (a[++less] < pivot1) ;
            while (a[--great] > pivot2) ;

            /*
             * Partitioning:
             *
             *   left part           center part                   right part
             * +--------------------------------------------------------------+
             * |  < pivot1  |  pivot1 <= && <= pivot2  |    ?    |  > pivot2  |
             * +--------------------------------------------------------------+
             *               ^                          ^       ^
             *               |                          |       |
             *              less                        k     great
             *
             * Invariants:
             *
             *              all in (left, less)   < pivot1
             *    pivot1 <= all in [less, k)     <= pivot2
             *              all in (great, right) > pivot2
             *
             * Pointer k is the first index of ?-part.
             */
            outer:
            for (int k = less - 1; ++k <= great; ) {
                int ak = a[k];
                if (ak < pivot1) { // Move a[k] to left part
                    a[k] = a[less];
                    /*
                     * Here and below we use "a[i] = b; i++;" instead
                     * of "a[i++] = b;" due to performance issue.
                     */
                    a[less] = ak;
                    ++less;
                } else if (ak > pivot2) { // Move a[k] to right part
                    while (a[great] > pivot2) {
                        if (great-- == k) {
                            break outer;
                        }
                    }
                    if (a[great] < pivot1) { // a[great] <= pivot2
                        a[k] = a[less];
                        a[less] = a[great];
                        ++less;
                    } else { // pivot1 <= a[great] <= pivot2
                        a[k] = a[great];
                    }
                    /*
                     * Here and below we use "a[i] = b; i--;" instead
                     * of "a[i--] = b;" due to performance issue.
                     */
                    a[great] = ak;
                    --great;
                }
            }

            // Swap pivots into their final positions
            a[left] = a[less - 1];
            a[less - 1] = pivot1;
            a[right] = a[great + 1];
            a[great + 1] = pivot2;

            // Sort left and right parts recursively, excluding known pivots
            sort(a, left, less - 2, leftmost);
            sort(a, great + 2, right, false);

            /*
             * If center part is too large (comprises > 4/7 of the array),
             * swap internal pivot values to ends.
             */
            if (less < e1 && e5 < great) {
                /*
                 * Skip elements, which are equal to pivot values.
                 */
                while (a[less] == pivot1) {
                    ++less;
                }

                while (a[great] == pivot2) {
                    --great;
                }

                /*
                 * Partitioning:
                 *
                 *   left part         center part                  right part
                 * +----------------------------------------------------------+
                 * | == pivot1 |  pivot1 < && < pivot2  |    ?    | == pivot2 |
                 * +----------------------------------------------------------+
                 *              ^                        ^       ^
                 *              |                        |       |
                 *             less                      k     great
                 *
                 * Invariants:
                 *
                 *              all in (*,  less) == pivot1
                 *     pivot1 < all in [less,  k)  < pivot2
                 *              all in (great, *) == pivot2
                 *
                 * Pointer k is the first index of ?-part.
                 */
                outer:
                for (int k = less - 1; ++k <= great; ) {
                    int ak = a[k];
                    if (ak == pivot1) { // Move a[k] to left part
                        a[k] = a[less];
                        a[less] = ak;
                        ++less;
                    } else if (ak == pivot2) { // Move a[k] to right part
                        while (a[great] == pivot2) {
                            if (great-- == k) {
                                break outer;
                            }
                        }
                        if (a[great] == pivot1) { // a[great] < pivot2
                            a[k] = a[less];
                            /*
                             * Even though a[great] equals to pivot1, the
                             * assignment a[less] = pivot1 may be incorrect,
                             * if a[great] and pivot1 are floating-point zeros
                             * of different signs. Therefore in float and
                             * double sorting methods we have to use more
                             * accurate assignment a[less] = a[great].
                             */
                            a[less] = pivot1;
                            ++less;
                        } else { // pivot1 < a[great] < pivot2
                            a[k] = a[great];
                        }
                        a[great] = ak;
                        --great;
                    }
                }
            }

            // Sort center part recursively
            sort(a, less, great, false);

        } else { // Partitioning with one pivot
            /*
             * Use the third of the five sorted elements as pivot.
             * This value is inexpensive approximation of the median.
             */
            int pivot = a[e3];

            /*
             * Partitioning degenerates to the traditional 3-way
             * (or "Dutch National Flag") schema:
             *
             *   left part    center part              right part
             * +-------------------------------------------------+
             * |  < pivot  |   == pivot   |     ?    |  > pivot  |
             * +-------------------------------------------------+
             *              ^              ^        ^
             *              |              |        |
             *             less            k      great
             *
             * Invariants:
             *
             *   all in (left, less)   < pivot
             *   all in [less, k)     == pivot
             *   all in (great, right) > pivot
             *
             * Pointer k is the first index of ?-part.
             */
            for (int k = less; k <= great; ++k) {
                if (a[k] == pivot) {
                    continue;
                }
                int ak = a[k];
                if (ak < pivot) { // Move a[k] to left part
                    a[k] = a[less];
                    a[less] = ak;
                    ++less;
                } else { // a[k] > pivot - Move a[k] to right part
                    while (a[great] > pivot) {
                        --great;
                    }
                    if (a[great] < pivot) { // a[great] <= pivot
                        a[k] = a[less];
                        a[less] = a[great];
                        ++less;
                    } else { // a[great] == pivot
                        /*
                         * Even though a[great] equals to pivot, the
                         * assignment a[k] = pivot may be incorrect,
                         * if a[great] and pivot are floating-point
                         * zeros of different signs. Therefore in float
                         * and double sorting methods we have to use
                         * more accurate assignment a[k] = a[great].
                         */
                        a[k] = pivot;
                    }
                    a[great] = ak;
                    --great;
                }
            }

            /*
             * Sort left and right parts recursively.
             * All elements from center part are equal
             * and, therefore, already sorted.
             */
            sort(a, left, less - 1, leftmost);
            sort(a, great + 1, right, false);
        }
    }
    /*-----------------------------*/
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值