@@ -74,22 +74,27 @@ public struct PriorityQueue<T: Comparable> {
74
74
swim ( heap. count - 1 )
75
75
}
76
76
77
- /// Add a new element onto a Priority Queue, limiting its size. O(n lg n)
78
- /// If the size limit has been reached, `maxCount` - `count` elements will be popped.
77
+ /// Add a new element onto a Priority Queue, limiting the size of the queue. O(n^2)
78
+ /// If the size limit has been reached, the lowest priority element will be removed and returned.
79
+ /// Note that because this is a binary heap, there is no easy way to find the lowest priority
80
+ /// item, so this method can be inefficient.
81
+ /// Also note, that only one item will be removed, even if count > maxCount by more than one.
79
82
///
80
- /// - parameter element: The element to be attempted insertion into the Priority Queue.
83
+ /// - parameter element: The element to be inserted into the Priority Queue.
81
84
/// - parameter maxCount: The Priority Queue will not grow further if its count >= maxCount.
82
- /// - returns: the first element popped , or `nil` if no elements were popped
85
+ /// - returns: the discarded lowest priority element , or `nil` if count < maxCount
83
86
public mutating func push( _ element: T , maxCount: Int ) -> T ? {
84
87
precondition ( maxCount > 0 )
85
- push ( element)
86
- if heap. count >= maxCount {
87
- var discard : T ?
88
- discard = pop ( )
89
- while heap. count >= maxCount { pop ( ) }
88
+ if maxCount <= count {
89
+ push ( element)
90
+ return nil
91
+ } else { // heap.count > maxCount
92
+ // find the min priority element
93
+ var discard : T ? = heap. min ( by: ordered)
94
+ if ordered ( element, discard) { return element }
95
+ remove ( discard)
90
96
return discard
91
97
}
92
- return nil
93
98
}
94
99
95
100
/// Remove and return the element with the highest priority (or lowest if ascending). O(lg n)
0 commit comments