Created
August 15, 2023 21:05
-
-
Save brandonasuncion/00c89936a2a72a2c39df355675aa81fd to your computer and use it in GitHub Desktop.
fast branchless binary search that uses the cmov instruction in Swift
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
| // branchless binary search | |
| // https://news.ycombinator.com/item?id=37086796 | |
| func binarySearch<T: Comparable>(_ value: T, in values: UnsafePointer<T>, length: Int) -> Int { | |
| let values = Int(bitPattern: values) | |
| var first = values | |
| var length = length | |
| while length != 0 { | |
| let half = length &>> 1 | |
| if UnsafePointer<T>(bitPattern: first).unsafelyUnwrapped[half] < value { | |
| first &+= (length &- half) &* MemoryLayout<T>.stride | |
| } | |
| length = half | |
| } | |
| return (first &- values) / MemoryLayout<T>.stride | |
| } | |
| func binarySearch<T, V: Comparable>(_ value: V, in values: UnsafePointer<T>, length: Int, by map: (T) -> V) -> Int { | |
| let values = Int(bitPattern: values) | |
| var first = values | |
| var length = length | |
| while length != 0 { | |
| let half = length &>> 1 | |
| if map(UnsafePointer<T>(bitPattern: first).unsafelyUnwrapped[half]) < value { | |
| first &+= (length &- half) &* MemoryLayout<T>.stride | |
| } | |
| length = half | |
| } | |
| return (first &- values) / MemoryLayout<T>.stride | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment