Created
November 19, 2019 19:13
-
-
Save lamtev/dc789f263cc6539e22130216c8730af6 to your computer and use it in GitHub Desktop.
Binary search implementation that returns insertion index if element not found
This file contains 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
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