Last active
July 14, 2020 17:24
-
-
Save khanlou/4986e186efa458b97829584cb2dc0058 to your computer and use it in GitHub Desktop.
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 { | |
func smallest(_ n: Int, usingTest areInIncreasingOrder: (Element, Element) -> Bool) -> [Element] { | |
var result = self.prefix(n).sorted(by: areInIncreasingOrder) | |
for e in self.dropFirst(n) { | |
if let insertionIndex = result.firstIndex(where: { areInIncreasingOrder(e, $0) }) { | |
result.insert(e, at: insertionIndex) | |
result.removeLast() | |
} | |
} | |
return result | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment