Why is Selection Sort not stable?

前端 未结 3 609
遥遥无期
遥遥无期 2021-01-30 04:12

This might be trivial, but I don\'t understand why the default implementation of Selection Sort is not stable?

At each iteration you find the minimum element in the rema

3条回答
  •  醉话见心
    2021-01-30 04:37

    A small example:

    Let b = B in

    < B > , < b > , < a > , < C > (with a < b < c)

    After one cycle the sequence is sorted but the order of B and b has changed:

    < a > , < b > , < B > , < c >

    But you can however implement Selections Sort stable if you, instead of switching, insert the minimum value. But for that to be efficient you should have a data structure that supports insertion at a low cost or otherwise you end up with quadratic complexity.

提交回复
热议问题