Last active
August 29, 2015 14:11
-
-
Save gilesvangruisen/e1831f010c1a87e285b6 to your computer and use it in GitHub Desktop.
Swift generic binary search
This file contains hidden or 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
// 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