Created
June 30, 2017 13:43
-
-
Save BrandonShega/952b24bae22c3fcbd8ef7b9d794a6a6a to your computer and use it in GitHub Desktop.
Swift Sorted Array
This file contains 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 UIKit | |
import XCPlayground | |
import PlaygroundSupport | |
struct SortedArray<Element: Comparable> { | |
var elements: [Element] | |
init<S: Sequence>(unsorted: S) where S.Iterator.Element == Element { | |
elements = unsorted.sorted() | |
} | |
mutating func insert(_ element: Element) { | |
elements.insert(element, at: index(for: element)) | |
} | |
func index(for element: Element) -> Int { | |
var start = startIndex | |
var end = endIndex | |
while start < end { | |
let middle = start + (end - start) / 2 | |
if elements[middle] < element { | |
start = middle + 1 | |
} else { | |
end = middle | |
} | |
} | |
return start | |
} | |
func contains(_ element: Element) -> Bool { | |
let index = self.index(for: element) | |
guard index < elements.endIndex else { return false } | |
return self[index] == element | |
} | |
} | |
extension SortedArray: Collection { | |
var startIndex: Int { | |
return elements.startIndex | |
} | |
var endIndex: Int { | |
return elements.endIndex | |
} | |
subscript(index: Int) -> Element { | |
return elements[index] | |
} | |
func index(after i: Int) -> Int { | |
return elements.index(after: i) | |
} | |
func min() -> Element? { | |
return elements.first | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment