Sign In with GitHub…
New Snippet

Swift

func binarySearch<T: Comparable>(_ array: [T], searchFor: T) -> Int? {
	func search(low: Int, high: Int) -> Int? {
		guard low <= high else { return nil }
		
		let mid = (low + high) / 2
		if searchFor == array[mid] {
			return mid
		} else {
			if searchFor < array[mid] {
				return search(low: low, high: mid-1)
			} else {
				return search(low: mid+1, high: high)
			}
		}
	}
	
	return search(low: 0, high: arr.count-1)
}