Skip to content

Instantly share code, notes, and snippets.

@lamtev
Created November 19, 2019 19:13
Show Gist options
  • Save lamtev/dc789f263cc6539e22130216c8730af6 to your computer and use it in GitHub Desktop.
Save lamtev/dc789f263cc6539e22130216c8730af6 to your computer and use it in GitHub Desktop.
Binary search implementation that returns insertion index if element not found
import Foundation
public extension RandomAccessCollection {
func binarySearch(startIndex: Index? = nil, endIndex: Index? = nil, comparator: (Element) -> Int) -> (index: Index, found: Bool) {
var low = startIndex ?? self.startIndex
var high = index(before: endIndex ?? self.endIndex)
while low <= high {
let mid = index(low, offsetBy: distance(from: low, to: high) >> 1)
let midVal = self[mid]
let cmp = comparator(midVal)
if cmp < 0 {
low = index(after: mid)
} else if cmp > 0 {
high = index(before: mid)
} else {
return (index: mid, found: true)
}
}
return (index: low, found: false)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment