forked from kodecocodes/swift-algorithm-club
-
Notifications
You must be signed in to change notification settings - Fork 0
/
OrderedArray.swift
58 lines (49 loc) · 1.29 KB
/
OrderedArray.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/*
An ordered array. When you add a new item to this array, it is inserted in
sorted position.
*/
public struct OrderedArray<T: Comparable> {
private var array = [T]()
public init(array: [T]) {
self.array = array.sort()
}
public var isEmpty: Bool {
return array.isEmpty
}
public var count: Int {
return array.count
}
public subscript(index: Int) -> T {
return array[index]
}
public mutating func removeAtIndex(index: Int) -> T {
return array.removeAtIndex(index)
}
public mutating func removeAll() {
array.removeAll()
}
public mutating func insert(newElement: T) -> Int {
let i = findInsertionPoint(newElement)
array.insert(newElement, atIndex: i)
return i
}
private func findInsertionPoint(newElement: T) -> Int {
var range = 0..<array.count
while range.startIndex < range.endIndex {
let midIndex = range.startIndex + (range.endIndex - range.startIndex) / 2
if array[midIndex] == newElement {
return midIndex
} else if array[midIndex] < newElement {
range.startIndex = midIndex + 1
} else {
range.endIndex = midIndex
}
}
return range.startIndex
}
}
extension OrderedArray: CustomStringConvertible {
public var description: String {
return array.description
}
}