Skip to content

Commit 03fa3c1

Browse files
authored
Update SwiftPriorityQueue.swift
1 parent 0c0463c commit 03fa3c1

File tree

1 file changed

+15
-10
lines changed

1 file changed

+15
-10
lines changed

Sources/SwiftPriorityQueue/SwiftPriorityQueue.swift

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -74,22 +74,27 @@ public struct PriorityQueue<T: Comparable> {
7474
swim(heap.count - 1)
7575
}
7676

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.
7982
///
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.
8184
/// - 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
8386
public mutating func push(_ element: T, maxCount: Int) -> T? {
8487
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)
9096
return discard
9197
}
92-
return nil
9398
}
9499

95100
/// Remove and return the element with the highest priority (or lowest if ascending). O(lg n)

0 commit comments

Comments
 (0)