forked from kodecocodes/swift-algorithm-club
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PriorityQueue.swift
58 lines (47 loc) · 1.39 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
/*
Priority Queue, a queue where the most "important" items are at the front of
the queue.
The heap is a natural data structure for a priority queue, so this object
simply wraps the Heap struct.
All operations are O(lg n).
Just like a heap can be a max-heap or min-heap, the queue can be a max-priority
queue (largest element first) or a min-priority queue (smallest element first).
*/
public struct PriorityQueue<T> {
fileprivate var heap: Heap<T>
/*
To create a max-priority queue, supply a > sort function. For a min-priority
queue, use <.
*/
public init(sort: @escaping (T, T) -> Bool) {
heap = Heap(sort: sort)
}
public var isEmpty: Bool {
return heap.isEmpty
}
public var count: Int {
return heap.count
}
public func peek() -> T? {
return heap.peek()
}
public mutating func enqueue(_ element: T) {
heap.insert(element)
}
public mutating func dequeue() -> T? {
return heap.remove()
}
/*
Allows you to change the priority of an element. In a max-priority queue,
the new priority should be larger than the old one; in a min-priority queue
it should be smaller.
*/
public mutating func changePriority(index i: Int, value: T) {
return heap.replace(index: i, value: value)
}
}
extension PriorityQueue where T: Equatable {
public func index(of element: T) -> Int? {
return heap.index(of: element)
}
}