What is the benefit for a sort algorithm to be stable?

后端 未结 10 2414
被撕碎了的回忆
被撕碎了的回忆 2020-12-12 22:35

A sort is said to be stable if it maintains the relative order of elements with equal keys. I guess my question is really, what is the benefit of maintaining this relative o

10条回答
  •  伪装坚强ぢ
    2020-12-12 23:31

    The advantage of stable sorting for multiple keys is dubious, you can always use a comparison that compares all the keys at once. It's only an advantage if you're sorting one field at a time, as when clicking on a column heading - Joe Koberg gives a good example.

    Any sort can be turned into a stable sort if you can afford to add a sequence number to the record, and use it as a tie-breaker when presented with equivalent keys.

    The biggest advantage comes when the original order has some meaning in and of itself. I couldn't come up with a good example, but I see JeffH did so while I was thinking about it.

提交回复
热议问题