java - 为什么就地合并排序不稳定?

标签 java sorting mergesort in-place

下面的实现是稳定的,因为它使用了 <=而不是<在标记为 XXX 的行处。这也使其更加高效。有什么理由使用<而不是<=在这一行?

/**
class for In place MergeSort
**/
class MergeSortAlgorithm extends SortAlgorithm {
    void sort(int a[], int lo0, int hi0) throws Exception {
    int lo = lo0;
    int hi = hi0;
    pause(lo, hi);
    if (lo >= hi) {
        return;
    }
    int mid = (lo + hi) / 2;

        /*
         *  Partition the list into two lists and sort them recursively
         */
        sort(a, lo, mid);
        sort(a, mid + 1, hi);

        /*
         *  Merge the two sorted lists
         */
    int end_lo = mid;
        int start_hi = mid + 1;
    while ((lo <= end_lo) && (start_hi <= hi)) {
            pause(lo);
        if (stopRequested) {
                return;
            }
            if (a[lo] <= a[start_hi]) {                   // LINE XXX
                lo++;
            } else {
                /*  
                 *  a[lo] >= a[start_hi]
                 *  The next element comes from the second list, 
                 *  move the a[start_hi] element into the next 
                 *  position and shuffle all the other elements up.
                 */
        int T = a[start_hi];
                for (int k = start_hi - 1; k >= lo; k--) {
                    a[k+1] = a[k];
                    pause(lo);
                }
                a[lo] = T;
                lo++;
                end_lo++;
                start_hi++;
            }
        }
    }

    void sort(int a[])  throws Exception {
    sort(a, 0, a.length-1);
    }
}

最佳答案

因为 <=在代码中确保相同值的元素(在排序数组的左半部分和右半部分中)不会被交换。 而且,它还避免了无用的交换。

if (a[lo] <= a[start_hi]) {
 /* The left value is smaller than or equal to the right one, leave them as is. */
 /* Especially, if the values are same, they won't be exchanged. */
 lo++;
} else {
 /*
  * If the value in right-half is greater than that in left-half,
  * insert the right one into just before the left one, i.e., they're exchanged.
  */
 ...
}

假设两半中都有相同值的元素(例如“5”),并且上面的运算符是 < 。 正如上面的注释所示,右侧的“5”将被插入到左侧的“5”之前,换句话说,将交换相同值的元素。 这意味着排序不稳定。 而且,交换相同值的元素效率很低。

<小时/>

我猜效率低下的原因来自于算法本身。 您的合并阶段是使用插入排序实现的(如您所知,它的时间复杂度为 O(n^2))。

当你对巨大的数组进行排序时,你可能需要重新实现。

关于java - 为什么就地合并排序不稳定?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1933822/

相关文章:

sql - 具有 NaN 值的 Postgres 排序列

java - 检查哪个摄像头是 Open Front 还是 Back Android

java - 用相同的附加字段包装不同的子类

java - 无法通过 Apache Tomcat 访问网络文件夹

c - 合并排序 - 错误输出

java - 使用归并排序对数组索引进行排序

java - 链表的归并排序java : Stack overflow

java - Image View 和 onClickListener 问题

python按值排序json列表

javascript - 在 ('change' 上)功能不起作用