why is in place merge sort not stable?

后端 未结 2 2094
野的像风
野的像风 2021-01-07 01:30

The implementation below is stable as it used <= instead of < at line marked XXX. This also makes it more efficient. Is there any reason to u

相关标签:
2条回答
  • 2021-01-07 02:23

    Fastest known in place stable sort:
    http://thomas.baudel.name/Visualisation/VisuTri/inplacestablesort.html

    0 讨论(0)
  • 2021-01-07 02:32

    Because the <= in your code assures that same-valued elements (in left- and right-half of sorting array) won't be exchanged. And also, it avoids useless exchanges.

    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.
      */
     ...
    }
    

    Assume that same-valued element (e.g., ‘5’) in both-halves and the operator above is <. As comments above shows, the right ‘5’ will be inserted before the left ‘5’, in other words, same-valued elements will be exchanged. This means the sort is not stable. And also, it's inefficient to exchange same-valued elements.


    I guess the cause of inefficiency comes from the algorithm itself. Your merging stage is implemented using insertion sort (as you know, it's O(n^2)).

    You may have to re-implement when you sort huge arrays.

    0 讨论(0)
提交回复
热议问题