Skip to content

Instantly share code, notes, and snippets.

@ChrisChares
Last active September 17, 2019 00:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChrisChares/d5ce1afcde01a80b2528682b59ea4bc8 to your computer and use it in GitHub Desktop.
Save ChrisChares/d5ce1afcde01a80b2528682b59ea4bc8 to your computer and use it in GitHub Desktop.
func binarySearchRecursive<T: Comparable, E: RandomAccessCollection>(_ xs: E, target: T, start _start: E.Index? = nil, end _end: E.Index? = nil) -> E.Index? where E.Element == T {
// Base cases
guard !xs.isEmpty else { return nil; }
guard xs.count > 1 else {
return xs[xs.startIndex] == target ? xs.startIndex : nil
}
// Start with two indexes, optionally supplied
let startIndex = _start ?? xs.startIndex;
let endIndex = _end ?? xs.endIndex;
// Calculate the middle index
let midPoint = xs.index(startIndex, offsetBy: xs.distance(from: startIndex, to: endIndex) / 2);
let midValue = xs[midPoint];
// Compare middle value to target value
if ( target < midValue ) {
// recursively search the new search space of: [start, mid]
return binarySearchRecursive(xs, target: target, start: startIndex, end: midPoint);
} else if ( target > midValue ) {
// recursively search the new search space of [mid, end]
return binarySearchRecursive(xs, target: target, start: midPoint, end: endIndex)
} else {
// If the target is equal, we've found it
return midPoint;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment