

Smallest N items in a sequence, with binary search improvements · GitHub
source link: https://gist.github.com/khanlou/770c24d5141e52e117642c4b03498966
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Instantly share code, notes, and snippets.
import Foundation
extension Array { func insertionIndex(of element: Element, by areInIncreasingOrder: (Element, Element) -> Bool) -> Index? { if isEmpty { return nil } if let last = self.last, areInIncreasingOrder(last, element) { return nil } var start = startIndex var end = endIndex while start < end { let middle = start / 2 + end / 2 if areInIncreasingOrder(self[middle], element) { start = middle + 1 } else if areInIncreasingOrder(element, self[middle]) { end = middle } else { return middle } } return start } }
extension Sequence { func smallest(_ m: 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.insertionIndex(of: e, by: areInIncreasingOrder) { result.insert(e, at: insertionIndex) result.removeLast() } }
return result } }
let start = Date() let shuff = (0..<55000).shuffled()
let a = shuff.smallest(20, usingTest: <)
let end = Date() print(a) print(end.timeIntervalSince(start))
Recommend
-
88
README.md KidVPN The world's smallest VPN server and client (For SylixOS and Linux). Configure File Configure file is a ini format...
-
47
The most useful smallest tmux trick by yours truly. peek() { tmux split-window -p 33 $EDITOR $@ || exit; } - lf94/peek-for-tmux
-
10
Copy link Contributor Folyd commente...
-
8
Copy link Contributor ecstatic-morse ...
-
13
Copy link Contributor vojtechkral ...
-
14
Copy link Contributor SOF3 commented
-
11
Setting up and maintaining a test framework can sometimes be complex and time consuming. I've created xv to be a test runner that is low maintainance, easy to setup and use. xv is great for sm...
-
10
Ranked #12 for today
-
12
Apple Store App Updated With Improvements for Saved Items and Enhanced Store Information ...
-
4
Conversation Contributor Previe...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK