Skip to content

Instantly share code, notes, and snippets.

@gilesvangruisen
Last active August 29, 2015 14:11
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 gilesvangruisen/e1831f010c1a87e285b6 to your computer and use it in GitHub Desktop.
Save gilesvangruisen/e1831f010c1a87e285b6 to your computer and use it in GitHub Desktop.
Swift generic binary search
// Binary search
func binarySearch<T: Comparable>(target: T, collection: [T]) -> Int {
var min = 0
var max = countElements(collection) - 1
return binaryMakeGuess(min, max, target, collection)
}
func binaryMakeGuess<T: Comparable>(min: Int, max: Int, target: T, collection: [T]) -> Int {
let guess = (min + max) / 2
if max < min {
// illegal, guess not in array
return -1
} else if collection[guess] == target {
// guess is correct
return guess
} else if collection[guess] > target {
// guess is too high
return binaryMakeGuess(min, guess - 1, target, collection)
} else {
// array[guess] < target
// guess is too low
return binaryMakeGuess(guess + 1, max, target, collection)
}
}
let strings = ["a", "b", "c", "d", "e", "f"]
binarySearch("a", strings)
binarySearch("z", strings)
let nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
binarySearch(7, nums)
binarySearch(-2, nums)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment