Skip to content

Commit 4efac16

Browse files
committed
Updated OrderedArray to Swift 3
1 parent a3d0d8f commit 4efac16

File tree

1 file changed

+19
-17
lines changed

1 file changed

+19
-17
lines changed

Ordered Array/OrderedArray.playground/Contents.swift

+19-17
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
//: Playground - noun: a place where people can play
22

33
public struct OrderedArray<T: Comparable> {
4-
private var array = [T]()
4+
fileprivate var array = [T]()
55

66
public init(array: [T]) {
7-
self.array = array.sort()
7+
self.array = array.sorted()
88
}
99

1010
public var isEmpty: Bool {
@@ -20,16 +20,16 @@ public struct OrderedArray<T: Comparable> {
2020
}
2121

2222
public mutating func removeAtIndex(index: Int) -> T {
23-
return array.removeAtIndex(index)
23+
return array.remove(at: index)
2424
}
2525

2626
public mutating func removeAll() {
2727
array.removeAll()
2828
}
2929

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)
3333
return i
3434
}
3535

@@ -47,18 +47,20 @@ public struct OrderedArray<T: Comparable> {
4747

4848
// Fast version that uses a binary search.
4949
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+
}
6062
}
61-
return range.startIndex
63+
return startIndex
6264
}
6365
}
6466

0 commit comments

Comments
 (0)