Are the sorting algorithms used by NSArray stable sorts?

前端 未结 3 614
盖世英雄少女心
盖世英雄少女心 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:16

    Stable sort is not guaranteed unless you use NSSortStable. From the documentation on NSSortOptions:

    NSSortStable

    Specifies that the sorted results should return compared items have equal value in the order they occurred originally.

    If this option is unspecified equal objects may, or may not, be returned in their original order.

    If you need to guarantee a stable sort, try something like:

    [array sortWithOptions:NSSortStable usingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [obj1 compare:obj2];
    }];
    

提交回复
热议问题