Skip to content

Instantly share code, notes, and snippets.

@joanmolinas
Last active August 26, 2016 01:47
Show Gist options
  • Save joanmolinas/552e102eabab8322b5d3518e9bb3f2c5 to your computer and use it in GitHub Desktop.
Save joanmolinas/552e102eabab8322b5d3518e9bb3f2c5 to your computer and use it in GitHub Desktop.
let arr = (0...15).map {$0*2}
func binarySearch<T : Comparable>(arr : Array<T>, value : T) -> Bool {
let midPosition = arr.startIndex.advancedBy(arr.startIndex.distanceTo(arr.endIndex)/2)
let midElement = arr[midPosition]
guard midElement != value else {
return true
}
guard value >= arr[arr.startIndex] && value <= arr[arr.endIndex-1] else {
return false
}
var subArray : Array<T>
if value < midElement {
subArray = Array(arr[arr.startIndex..<midPosition])
} else {
subArray = Array(arr[midPosition.successor()...arr.endIndex-1])
}
return binarySearch(subArray, value: value)
}
binarySearch(arr, value: 4) //True
binarySearch(arr, value:50323) //False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment