Last active
August 26, 2016 01:47
-
-
Save joanmolinas/552e102eabab8322b5d3518e9bb3f2c5 to your computer and use it in GitHub Desktop.
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
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