Skip to content

Instantly share code, notes, and snippets.

@luki
Created November 11, 2017 15:30
Show Gist options
  • Save luki/70970ef099fb702d253a7716b37fed98 to your computer and use it in GitHub Desktop.
Save luki/70970ef099fb702d253a7716b37fed98 to your computer and use it in GitHub Desktop.
Binary Search Algorithm (Must be sorted!)
extension Int {
var asDouble: Double {
return Double(self)
}
}
extension Double {
var halve: Double {
return self / 2
}
var asInt: Int {
return Int(self)
}
}
func binary_search(_ nums: [Int], n: Int) -> Bool {
let midIndex = (nums.count - 1).asDouble.halve.rounded().asInt
// midIndex == Nums.count - 1 && n != nums[midIndex]: Mid index and amount of elements is the same and the number doesn't equal that one single element
// OR the midindex is smaller than 0, in that case that means the item that is being looked for is smaller than the smallest item in the array
// and thus doesn't exist
if midIndex == nums.count - 1 && n != nums[midIndex] || midIndex < 0 { return false }
let leftRange = 0..<midIndex
let rightRange = midIndex..<nums.count
if n == nums[midIndex] { return true }
if n < nums[midIndex] { return binary_search(Array(nums[leftRange]), n: n) }
// => if n > nums[midIndex]
return binary_search(Array(nums[rightRange]), n: n)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment