Skip to content

Instantly share code, notes, and snippets.

@chrisbrandow
Created November 2, 2016 18:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisbrandow/bbe6a57e7c969ac6e12f67f9f6a5a73c to your computer and use it in GitHub Desktop.
Save chrisbrandow/bbe6a57e7c969ac6e12f67f9f6a5a73c to your computer and use it in GitHub Desktop.
results testing linear search vs. binary search
import Foundation
var array = [Int]()
for i in 1 ..< 10000000 {
array.append(i)
}
//let numberList = array
extension Array where Element: Comparable {
mutating func linearSearch(forElement key: Element) -> Bool {
//check all possible values
for number in self {
if number == key {
return true
}
}
return false
}
func binarySearch(forElement key: Element) -> Bool {
// print("check")
var result = false
//establish indices
let min = self.startIndex
let max = self.endIndex - 1
let mid = self.midIndex()
//check bounds
if key > self[max] || key < self[min] {
print("search value \(key) not found..")
return false
}
//evaluate chosen number..
let n = self[mid]
if n > key {
var slice = Array(self[min...mid - 1])
result = slice.binarySearch(forElement: key)
}
else if n < key {
var slice = Array(self[mid + 1...max])
result = slice.binarySearch(forElement: key)
}
else {
//print("search value \(key) found..")
result = true
}
return result
}
//returns middle index
func midIndex() -> Index {
return startIndex + (count / 2)
}
}
//execute search
let date = NSDate()
var isFound: Bool = array.linearSearch(forElement: 9000000)
print(date.timeIntervalSinceNow) //-0.01704
let date2 = NSDate()
isFound = array.binarySearch(forElement: 9000000)
print(date2.timeIntervalSinceNow) //-0.03014
@chrisbrandow
Copy link
Author

I also tried this without binarySearch function being mutating, changing internal methods to
var slice = ... to let slice = ...
it was basically the same result

I compiled on CodeRunner 2 with -O flag,

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment