Created
July 9, 2018 08:19
-
-
Save cemaleker/b49ddee8fe6e4a22926c8106637ef89c to your computer and use it in GitHub Desktop.
Stable sorting for swift sequences
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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