【发布时间】:2017-10-05 08:21:07
【问题描述】:
我需要类似以下的东西:
let arr = [...] //array of strings
let resultArr = arr.sort({obj1,obj2 in
if some_condition(obj1, obj2) {
...//return the order of obj1 and obj2 from arr
} else {
return obj1 < obj2
}
})
我看到很多问题/答案如何简单地对数组项进行排序,但没有人回答如何存储原始顺序。 some_condition 可以是任何数组对象,但每个数组对象可以按原始顺序或新顺序排序。如何解决这个问题?
示例
let arr = ["a", "f", "d", "b", "y", "c", "e"]
//elements "a", "d", "f" conform some_condition
resultArr == ["a", "f", "d", "b", "c", "e", "y"]
【问题讨论】:
-
您正在寻找«稳定排序»:stackoverflow.com/questions/40673374/…?
-
“每个数组对象可能按原始顺序或新顺序排序” 我不清楚。也许您可以添加一个清楚地说明您的问题的示例?
-
@MartinR @Larme 没有。那个问题是关于
A nonstable sort may change the relative order of elements that compare equal.加了一个例子 -
“如何存储原始订单”让我认为您想要一个“稳定排序”的问题要么不清楚和/或被我误解了。你的意思是像伪代码
let except = ["a", "d", "f"] if (except.contains(obj1) && !except.contains(obj2){ return true} else if (!except.contains(obj1) && except.contains(obj2){ return false} else{ return obj1< obj2 }? -
我看到了字母顺序排序,但是如果
let arr = ["a", "f", "d", "b", "y", "c", "e"]、resultArr == ["a", "f", "d", "b", "c", "e", "y"]或resultArr == ["a", "d", "f", "b", "c", "e", "y"]呢?如果是第一个,稳定排序应该是解决方案(除非有另一个特殊顺序),对于最后一个,只需阅读我之前评论中的伪代码即可。
标签: objective-c arrays swift sorting