Skip to content

Instantly share code, notes, and snippets.

@muratcakmak
Last active November 13, 2017 22:13
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 muratcakmak/5e9e219de1a9a1fafe6a6bda564c4ed1 to your computer and use it in GitHub Desktop.
Save muratcakmak/5e9e219de1a9a1fafe6a6bda564c4ed1 to your computer and use it in GitHub Desktop.
Binary Search implementation in Swift
func binarySearch<T: Comparable> (on array: [T], target: T) -> Int?{
if(array.count <= 1 && array.first != target){
return nil
}
let middle = array.count/2
if(target == array[middle]){
return middle
}else if(target < array[middle]){
return binarySearch(on: Array(array.dropLast(middle)), target: target)
}else{
let result = binarySearch(on: Array(array.dropFirst(middle)), target: target)
return result != nil ? (middle + result!) : result!
}
}
let numbers = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67]
binarySearch(on: numbers, target: 67) == numbers.index(of: 67) //true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment