Last active
May 21, 2017 04:36
-
-
Save ashevin/360ee60fdc25f78604bcc2682576efd7 to your computer and use it in GitHub Desktop.
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
//: Playground - noun: a place where people can play | |
import UIKit | |
extension Array { | |
func binarySearch<T: Comparable>(key: T, returnInsertionIndex: Bool = false) -> Int? { | |
var range = 0..<self.count | |
var midIndex: Int = 0 | |
var value: T? | |
while range.startIndex < range.endIndex { | |
// Find the middle point in the array within the given range | |
midIndex = range.startIndex + (range.endIndex - range.startIndex) / 2 | |
let m = self[midIndex] as? T | |
guard let midValue = m else { | |
return nil | |
} | |
value = midValue | |
if midValue == key { | |
// If we found our search key, return the index | |
return midIndex | |
} else if midValue < key { | |
// If the mdidle value is less than the key, look at the right half | |
range = (midIndex + 1)..<range.endIndex | |
} else { | |
// If the midle value is greater than the key, look at the left half | |
range = range.startIndex..<midIndex | |
} | |
} | |
if let value = value, returnInsertionIndex { | |
return value > key ? midIndex : midIndex + 1 | |
} | |
return nil | |
} | |
} | |
[0.0, 1.0, 3.2, 5.4].binarySearch(key: 1.1, returnInsertionIndex: true) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
mdidle, midle = middle