这个MergeSort实现是否稳定?

时间:2016-02-28 19:29:00

标签: algorithm sorting mergesort

我正在攻读算法考试。有人可以解释为什么这不稳定,问题在哪里不稳定?我怎样才能让它稳定下来?

由于

//The numbers to be sorted are given in array A[1..n]
//We use an additional array B[1..n] as temporary storage space
MergeSort(A, left, right) {
    if (left < right) {
        mid = floor( (left + right)/2 );     // find the middle
        MergeSort(A, left, mid);             // sort the left subarray recursively
        MergeSort(A, mid+1, right);          // sort the right subarray recursively
        Merge(A,left,mid,right);             // merge the two sorted subarrays
    }
}

Merge(A, left, mid, right) {
    // left subarray: A[left..mid], right subarray: A[mid+1 .. right]
    m = left; // index for the temporary array
    i = left;
    j = mid+1;
    while (i <= mid && j <= right) {     // copy the smaller element to the output
        if ( A[i] >= A[j] ) {
            B[m] = A[j];
            j++;
        } else {
            B[m] = A[i];
            i++;
        }
        m++;
    }
    while (i <= mid) {                   // copy the remaining part in the left array
        B[m] = A[i];
        m++;
        i++;
    }
    while (j <= right) {                 // copy the remaining part in the right array
        B[m] = A[j];
        m++;
        j++;
    }
    for (m = left; m <= right; m++)      // copy the merged form back to A
        A[m] = B[m];
}

1 个答案:

答案 0 :(得分:2)

您的问题出现在此细分中:

i = left;
j = mid+1;
while (i <= mid && j <= right) { // copy the smaller element to the output
    if ( A[i] >= A[j] ) {
        B[m] = A[j];

这就是说,如果数组左侧的元素等于右侧的元素,请从右侧选择一个元素。这样做会颠倒这些元素的原始排序。