如何快速稳定地对数组进行排序? [英] How to stable sort an array in swift?
本文介绍了如何快速稳定地对数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在使用 sort() 函数,但它混淆了相对顺序.
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 说:
排序算法不稳定.不稳定的排序可能会改变比较相等的元素的相对顺序.
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?
推荐答案
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
}
})
取自此处:https://medium.com/@cocotutch/a-swift-sorting-problem-e0ebfc4e46d4
这篇关于如何快速稳定地对数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文