Last active
September 17, 2019 00:24
-
-
Save ChrisChares/4c208ad17b0f89056925db4bbf7f7077 to your computer and use it in GitHub Desktop.
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
func binarySearchIterative<T: Comparable, E: RandomAccessCollection>(_ xs: E, target: T) -> E.Index? where E.Element == T { | |
// Start with two indexes, one at the beginning | |
var startIndex = xs.startIndex; | |
// And one at the end | |
var endIndex = xs.index(before: xs.endIndex); | |
// We are done when are our indexes converge | |
while startIndex < endIndex { | |
// Find the midpoint between our current range | |
let midPoint = xs.index(startIndex, offsetBy: xs.distance(from: startIndex, to: endIndex) / 2); | |
let midValue = xs[midPoint]; | |
// Evaluate the middle value against our target value | |
if ( target < midValue ) { | |
// If the target is less than our middle value,we can narrow the search space to | |
// [start, mid] | |
endIndex = midPoint | |
} else if ( target > midValue ) { | |
// If the target is greater than our middle value,we can narrow the search space to | |
// [mid, end] | |
startIndex = min(midPoint, xs.index(after: startIndex)) | |
} else { | |
// If the target is equal, we've found it | |
return midPoint; | |
} | |
} | |
// We did not find a match | |
return nil; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment