1
1
//: Playground - noun: a place where people can play
2
2
3
3
public struct OrderedArray < T: Comparable > {
4
- private var array = [ T] ( )
4
+ fileprivate var array = [ T] ( )
5
5
6
6
public init ( array: [ T ] ) {
7
- self . array = array. sort ( )
7
+ self . array = array. sorted ( )
8
8
}
9
9
10
10
public var isEmpty : Bool {
@@ -20,16 +20,16 @@ public struct OrderedArray<T: Comparable> {
20
20
}
21
21
22
22
public mutating func removeAtIndex( index: Int ) -> T {
23
- return array. removeAtIndex ( index)
23
+ return array. remove ( at : index)
24
24
}
25
25
26
26
public mutating func removeAll( ) {
27
27
array. removeAll ( )
28
28
}
29
29
30
- public mutating func insert( newElement: T ) -> Int {
31
- let i = findInsertionPoint ( newElement)
32
- array. insert ( newElement, atIndex : i)
30
+ public mutating func insert( _ newElement: T ) -> Int {
31
+ let i = findInsertionPoint ( newElement: newElement )
32
+ array. insert ( newElement, at : i)
33
33
return i
34
34
}
35
35
@@ -47,18 +47,20 @@ public struct OrderedArray<T: Comparable> {
47
47
48
48
// Fast version that uses a binary search.
49
49
private func findInsertionPoint( newElement: T ) -> Int {
50
- var range = 0 ..< array. count
51
- while range. startIndex < range. endIndex {
52
- let midIndex = range. startIndex + ( range. endIndex - range. startIndex) / 2
53
- if array [ midIndex] == newElement {
54
- return midIndex
55
- } else if array [ midIndex] < newElement {
56
- range. startIndex = midIndex + 1
57
- } else {
58
- range. endIndex = midIndex
59
- }
50
+ var startIndex = 0
51
+ var endIndex = array. count
52
+
53
+ while startIndex < endIndex {
54
+ let midIndex = startIndex + ( endIndex - startIndex) / 2
55
+ if array [ midIndex] == newElement {
56
+ return midIndex
57
+ } else if array [ midIndex] < newElement {
58
+ startIndex = midIndex + 1
59
+ } else {
60
+ endIndex = midIndex
61
+ }
60
62
}
61
- return range . startIndex
63
+ return startIndex
62
64
}
63
65
}
64
66
0 commit comments