Skip to content

Instantly share code, notes, and snippets.

@cemaleker
Created July 9, 2018 08:19
Show Gist options
  • Save cemaleker/b49ddee8fe6e4a22926c8106637ef89c to your computer and use it in GitHub Desktop.
Save cemaleker/b49ddee8fe6e4a22926c8106637ef89c to your computer and use it in GitHub Desktop.
Stable sorting for swift sequences
extension Sequence {
/// return a sorted collection using a stable sort algorithm
///
/// - Parameter areInIncreasingOrder: return nil when two element are equal
/// - Returns: the sorted collection
///
/// Shamelessly copied from https://stackoverflow.com/a/45585365
///
public func stableSorted(by areInIncreasingOrder: (Element, Element) throws -> Bool) rethrows -> [Element] {
return try enumerated()
.sorted(by: { lhs, rhs -> Bool in
try areInIncreasingOrder(lhs.element, rhs.element)
|| (lhs.offset < rhs.offset && !areInIncreasingOrder(rhs.element, lhs.element))
})
.map { $0.element }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment