2

以下の実装は、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);
    }
}
4

2 に答える 2

7

<=コード内の は、同じ値の要素 (並べ替え配列の左半分と右半分) が交換されないことを保証するためです。また、無駄なやり取りを避けます。

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) です)。

巨大な配列をソートするときは、再実装する必要があるかもしれません。

于 2009-12-21T14:50:32.433 に答える
2

既知の最速安定ソート:
http://thomas.baudel.name/Visualisation/VisuTri/inplacestablesort.html

于 2011-03-14T11:13:33.733 に答える