Created
November 2, 2016 18:21
-
-
Save chrisbrandow/bbe6a57e7c969ac6e12f67f9f6a5a73c to your computer and use it in GitHub Desktop.
results testing linear search vs. binary search
This file contains hidden or 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 | |
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I also tried this without
binarySearch
function being mutating, changing internal methods tovar slice = ...
tolet slice = ...
it was basically the same result
I compiled on CodeRunner 2 with -O flag,