Skip to content

Instantly share code, notes, and snippets.

@christopherkarani
Created November 10, 2017 11:29
Show Gist options
  • Save christopherkarani/93b20cb78ad9d38bcce9c21339b5acc8 to your computer and use it in GitHub Desktop.
Save christopherkarani/93b20cb78ad9d38bcce9c21339b5acc8 to your computer and use it in GitHub Desktop.
var numbers = [Int]()
for x in 1...100 {
numbers.append(x)
}
var num = [1,2,4,6,8,9,11,13,16,17,20]
func binarySearch(for searchValue: Int, withDatasoucre datasource: [Int]) -> Bool {
var firstIndex = 0
var lastIndex = datasource.count - 1
while firstIndex <= lastIndex {
let middleIndex = (firstIndex + lastIndex) / 2
let middleValue = datasource[middleIndex]
print("middleValue: \(middleValue), firstIndex: \(firstIndex), lastIndex: \(lastIndex), [\(datasource[firstIndex]),\(datasource[lastIndex])]")
if middleValue == searchValue {
return true
}
if searchValue < middleValue {
lastIndex = middleIndex - 1
}
if searchValue > middleValue {
firstIndex = middleIndex + 1
}
}
return false
}
func searchValueIsFound(x: Int, y: Int) -> Bool {
if x == y {
return true
}
return false
}
let searchValue: Int = 4101
print(binarySearch(for: searchValue, withDatasoucre: numbers))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment