-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathPriorityQueue.swift
78 lines (53 loc) · 1.64 KB
/
PriorityQueue.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import Foundation
/// Implementation of Priority Queue based on Heap data structure.
public struct PriorityQueue<T> where T: Comparable {
// MARK: - Propertioes
fileprivate var heap: Heap<T>
// MARK: - Initializers
public init(order: @escaping (T, T) -> Bool) {
heap = Heap(order: order)
}
public init(elements: [T], order: @escaping (T, T) -> Bool) {
heap = Heap(array: elements, order: order)
}
// MARK: - Methods
public func isEmpty() -> Bool {
return heap.isEmpty
}
public func count() -> Int {
return heap.count
}
public func peek() -> T? {
return heap.peek()
}
public mutating func enqueue(_ element: T) {
heap.insert(node: element)
}
public mutating func dequeue() -> T? {
return heap.remove()
}
public mutating func changePriority(index i: Int, value: T) {
return heap.replace(elementAt: i, with: value)
}
}
extension PriorityQueue where T: Equatable {
// MARK: - Methods
public func index(of element: T) -> Int? {
return heap.index(of: element)
}
}
extension PriorityQueue: ExpressibleByArrayLiteral {
// MARK: - Initializers
public init(arrayLiteral elements: T...) {
self.init(elements: elements, order: >)
}
}
extension PriorityQueue: CustomStringConvertible, CustomDebugStringConvertible {
// MARK: - Properties
public var description: String {
return heap.description
}
public var debugDescription: String {
return heap.debugDescription
}
}