zoukankan      html  css  js  c++  java
  • Collections.sort()中的mergeSort归并排序

    @SuppressWarnings({"unchecked", "rawtypes"})
        private static void mergeSort(Object[] src,
                                      Object[] dest,
                                      int low,
                                      int high,
                                      int off) {
            int length = high - low;
    
            // Insertion sort on smallest arrays
            if (length < INSERTIONSORT_THRESHOLD) {
                for (int i=low; i<high; i++)
                    for (int j=i; j>low &&
                             ((Comparable) dest[j-1]).compareTo(dest[j])>0; j--)
                        swap(dest, j, j-1);
                return;
            }
    
            // Recursively sort halves of dest into src
            int destLow  = low;
            int destHigh = high;
            low  += off;
            high += off;
            int mid = (low + high) >>> 1;
            mergeSort(dest, src, low, mid, -off);
            mergeSort(dest, src, mid, high, -off);
    
            // If list is already sorted, just copy from src to dest.  This is an
            // optimization that results in faster sorts for nearly ordered lists.
            if (((Comparable)src[mid-1]).compareTo(src[mid]) <= 0) {
                System.arraycopy(src, low, dest, destLow, length);
                return;
            }
    
            // Merge sorted halves (now in src) into dest
            for(int i = destLow, p = low, q = mid; i < destHigh; i++) {
                if (q >= high || p < mid && ((Comparable)src[p]).compareTo(src[q])<=0)
                    dest[i] = src[p++];
                else
                    dest[i] = src[q++];
            }
        }
    
        /**
         * Swaps x[a] with x[b].
         */
        private static void swap(Object[] x, int a, int b) {
            Object t = x[a];
            x[a] = x[b];
            x[b] = t;
        }
  • 相关阅读:
    NOIP2009 靶形数独
    NOIP2014 寻找道路
    NOIP2005 篝火晚会
    NOIP2014 联合权值
    NOIP2011 选择客栈
    luogu2659 美丽的序列
    NOIP2008 传纸条
    vijos1642 班长的任务
    codevs1427 RQNOJ204 特种部队
    AC自动机
  • 原文地址:https://www.cnblogs.com/w1570631036/p/6480738.html
Copyright © 2011-2022 走看看