Are the sorting algorithms used by NSArray stable sorts?

ios, nsarray, objective-c, sorting

Solution

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];
}];

Problem

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 relative orders preserved.)

Original source