Last active
November 11, 2017 15:01
-
-
Save volkanbicer/a67f27f5f073dca503ffe6dd7c568dbe to your computer and use it in GitHub Desktop.
Binary search function for 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
import Foundation | |
let numbers = Array(1...1000) | |
func binarySearch<T: Comparable>(_ a: [T], key: T, range:Range<Int>) -> Int?{ | |
if range.lowerBound >= range.upperBound{ return nil} | |
let midIndex = range.lowerBound + (range.upperBound - range.lowerBound)/2 | |
if key < a[midIndex]{ | |
return binarySearch(a, key: key, range: range.lowerBound..<midIndex) | |
}else if key > a[midIndex]{ | |
return binarySearch(a, key:key, range: midIndex..<range.upperBound) | |
}else{ | |
return midIndex | |
} | |
} | |
func search(_ a: [Int], _ item: Int) -> Int{ | |
if a.count < 1{ | |
return -1 | |
} | |
func binarySearch(_ a:[Int], _ low: Int, _ high: Int) -> Int{ | |
if low > high{ | |
return -1 | |
} | |
let midIndex = low + (high - low)/2 | |
if item < a[midIndex]{ | |
return binarySearch(a, low, midIndex-1) | |
} else if item > a[midIndex]{ | |
return binarySearch(a, midIndex+1, high) | |
}else { | |
return midIndex | |
} | |
} | |
return binarySearch(a, 0, a.count-1) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment