Search code examples
arraysswiftsorting

How to stable sort an array in swift?


I've been using the sort() function but it mixes up the relative order.

This is how my code looks.

recipes.sort { $0.skill.value <= $1.skill.value }

Swift API says that:

The sorting algorithm is not stable. A nonstable sort may change the relative order of elements that compare equal.

How can I change this so that the relative order stays the same as before?


Solution

  • let sortedArray = (recipes as NSArray).sortedArray(options: .stable, usingComparator: { (lhs, rhs) -> ComparisonResult in
        let lhs = (lhs as! Recipe)
        let rhs = (rhs as! Recipe)
        if lhs.skill.value == rhs.skill.value {
            return ComparisonResult.orderedSame
        } else if lhs.skill.value < rhs.skill.value {
            return ComparisonResult.orderedAscending
        } else {
            return ComparisonResult.orderedDescending
        }
    })
    

    Took from here: https://medium.com/@cocotutch/a-swift-sorting-problem-e0ebfc4e46d4