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

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

提交回复
热议问题