Skip to content

Commit 5df13a3

Browse files
committed
Added support for CollectionType and first Unit Test
1 parent c6bc27c commit 5df13a3

File tree

3 files changed

+42
-9
lines changed

3 files changed

+42
-9
lines changed

.gitignore

+3-7
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
.DS_Store
2+
.Trashes
3+
*.swp
14
# Xcode
25
#
36
build/
@@ -24,10 +27,3 @@ DerivedData
2427
# http://guides.cocoapods.org/using/using-cocoapods.html#should-i-ignore-the-pods-directory-in-source-control
2528
#
2629
# Pods/
27-
28-
# Carthage
29-
#
30-
# Add this line if you want to avoid checking in source code from Carthage dependencies.
31-
# Carthage/Checkouts
32-
33-
Carthage/Build

SwiftPriorityQueue/SwiftPriorityQueue.swift

+24-2
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,12 @@
2424

2525
// This code was inspired by Section 2.4 of Algorithms by Sedgewick & Wayne, 4th Edition
2626

27-
class PriorityQueue<T: Comparable>: Printable, GeneratorType, SequenceType {
27+
/// A PriorityQueue takes objects to be pushed of any type that implements Comparable.
28+
/// It will pop the objects in the order that they would be sorted. A pop() or a push()
29+
/// can be accomplished in O(lg n) time. It can be specified whether the objects should
30+
/// be popped in ascending or descending order (Max Priority Queue or Min Priority Queue)
31+
/// at the time of initialization.
32+
class PriorityQueue<T: Comparable>: Printable, GeneratorType, SequenceType, CollectionType {
2833
private final var heap: [T] = []
2934
private let contrast: (T, T) -> Bool
3035

@@ -118,7 +123,10 @@ class PriorityQueue<T: Comparable>: Printable, GeneratorType, SequenceType {
118123
//Implement GeneratorType
119124
typealias Element = T
120125
func next() -> Element? {
121-
return pop()
126+
if let e = pop() {
127+
return e
128+
}
129+
return nil
122130
}
123131

124132
//Implement SequenceType
@@ -127,4 +135,18 @@ class PriorityQueue<T: Comparable>: Printable, GeneratorType, SequenceType {
127135
return self
128136
}
129137

138+
//Implement CollectionType
139+
typealias Index = Int
140+
141+
var startIndex: Int {
142+
return 0
143+
}
144+
145+
var endIndex: Int {
146+
return count
147+
}
148+
149+
subscript(i: Int) -> T {
150+
return heap[i]
151+
}
130152
}

SwiftPriorityQueueTests/SwiftPriorityQueueTests.swift

+15
Original file line numberDiff line numberDiff line change
@@ -33,4 +33,19 @@ class SwiftPriorityQueueTests: XCTestCase {
3333
}
3434
}
3535

36+
func testBasic() {
37+
var pq: PriorityQueue<Int> = PriorityQueue<Int>()
38+
for var i: Int = 0; i < 10; i++ {
39+
pq.push(i);
40+
}
41+
42+
let expected: [Int] = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
43+
var actual: [Int] = []
44+
for i in pq {
45+
actual.append(i)
46+
}
47+
48+
XCTAssertEqual(expected, actual, "Basic 10 Integer Array Test Pass")
49+
}
50+
3651
}

0 commit comments

Comments
 (0)