Skip to content

Instantly share code, notes, and snippets.

@brandonasuncion
Created August 15, 2023 21:05
Show Gist options
  • Select an option

  • Save brandonasuncion/00c89936a2a72a2c39df355675aa81fd to your computer and use it in GitHub Desktop.

Select an option

Save brandonasuncion/00c89936a2a72a2c39df355675aa81fd to your computer and use it in GitHub Desktop.
fast branchless binary search that uses the cmov instruction in Swift
// 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