Skip to content

Instantly share code, notes, and snippets.

@xsleonard
Created September 10, 2020 02:59
Show Gist options
  • Save xsleonard/1e8aa11f13e8b6f68501d1da50ebf207 to your computer and use it in GitHub Desktop.
Save xsleonard/1e8aa11f13e8b6f68501d1da50ebf207 to your computer and use it in GitHub Desktop.
Binary search for Swift arrays
extension Array where Element: Comparable {
// Returns the location of the value in the array,
// or where you should insert the value into the array.
// If the value does not exist in the array, the Bool return value is false.
func binarySearch(value: Element) -> (Index, Bool) {
guard !isEmpty else {
return (0, false)
}
if value > self.last! {
return (endIndex, false)
}
if value < self.first! {
return (startIndex, false)
}
var low = startIndex
var high = endIndex
while low <= high {
let d = distance(from: low, to: high)
let mid = index(low, offsetBy: d/2)
if self[mid] < value {
low = mid + 1
} else if self[mid] > value {
high = mid - 1
} else {
return (mid, true)
}
}
return (low, false)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment