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

后端 未结 10 2407
被撕碎了的回忆
被撕碎了的回忆 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.

    0 讨论(0)
  • 2020-12-12 23:40

    A sorting algorithm is stable if it preserves the order of duplicate keys.

    OK, fine, but why should this be important? Well, the question of "stability" in a sorting algorithm arises when we wish to sort the same data more than once according to different keys.

    Sometimes data items have multiple keys. For example, perhaps a (unique) primary key such as a social insurance number, or a student identification number, and one or more secondary keys, such as city of residence, or lab section. And we may very well want to sort such data according to more than one of the keys. The trouble is, if we sort the same data according to one key, and then according to a second key, the second key may destroy the ordering achieved by the first sort. But this will not happen if our second sort is a stable sort.

    From Stable Sorting Algorithms

    0 讨论(0)
  • 2020-12-12 23:40

    It means if you want to sort by Album, AND by Track Number, that you can click Track number first, and it's sorted - then click Album Name, and the track numbers remain in the correct order for each album.

    0 讨论(0)
  • 2020-12-12 23:41

    An example:

    Say you have a data structure that contains pairs of phone numbers and employees who called them. A number/employee record is added after each call. Some phone numbers may be called by several different employees.

    Furthermore, say you want to sort the list by phone number and give a bonus to the first 2 people who called any given number.

    If you sort with an unstable algorithm, you may not preserve the order of callers of a given number, and the wrong employees could be given the bonus.

    A stable algorithm makes sure that the right 2 employees per phone number get the bonus.

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