Last active
November 13, 2017 22:13
-
-
Save muratcakmak/5e9e219de1a9a1fafe6a6bda564c4ed1 to your computer and use it in GitHub Desktop.
Binary Search implementation in Swift
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 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