Are the sorting algorithms used by NSArray stable sorts?

前端 未结 3 618
盖世英雄少女心
盖世英雄少女心 2020-12-11 15:41

Are the sorting algorithms used by the various sorting methods in NSArray stable? (As in are they \"stable sort\" algorithms, where items with the same sort key have their

3条回答
  •  孤城傲影
    2020-12-11 16:25

    The only "official" answer I've found about this is a 2002 mailing list post by Chris Kane from Apple:

    The stability of NSArray/NSMutableArray's sorting methods is undefined, so you should anticipate that they are unstable. Being undefined, the situation may also change from release to release, though I don't (myself) anticipate that this is likely. The current implementation uses quick sort, a version of the algorithm nearly identical to BSD's qsort() routine. A bunch of experimentation found at one point that it was hard to do better than that for the general types of data we through at the tests. [Of course, if one has additional information about the data being sorted, one can use other algorithms or modifications which help that case.]

    I don't know whether this is still true, given how old the post is, but it's probably best to assume that NSArray's sorting methods are not stable.

提交回复
热议问题