// Swift implementation of a generic priority queue
struct PriorityQueue {
private var elements: [Element] = []
var isEmpty: Bool {
return elements.isEmpty
}
var peek: Element? {
return elements.first
}
mutating func enqueue(_ element: Element) {
elements.append(element)
swim(elements.count - 1)
}
mutating func dequeue() -> Element? {
guard !isEmpty else { return nil }
let first = elements[0]
elements[0] = elements[elements.count - 1]
elements.removeLast()
sink(0)
return first
}
private func swim(_ index: Int) {
var childIndex = index
let child = elements[childIndex]
var parentIndex = (childIndex - 1) / 2
while childIndex > 0 && child > elements[parentIndex] {
elements[childIndex] = elements[parentIndex]
childIndex = parentIndex
parentIndex = (childIndex - 1) / 2
}
elements[childIndex] = child
}
private func sink(_ index: Int) {
var parentIndex = index
let parent = elements[parentIndex]
let count = elements.count
while true {
let leftChildIndex = 2 * parentIndex + 1
let rightChildIndex = 2 * parentIndex + 2
var highestIndex = parentIndex
if leftChildIndex < count && elements[leftChildIndex] > elements[highestIndex] {
highestIndex = leftChildIndex
}
if rightChildIndex < count && elements[rightChildIndex] > elements[highestIndex] {
highestIndex = rightChildIndex
}
if highestIndex == parentIndex { return }
elements[parentIndex] = elements[highestIndex]
parentIndex = highestIndex
}
}
}
// Example usage
var priorityQueue = PriorityQueue()
priorityQueue.enqueue(5)
priorityQueue.enqueue(10)
priorityQueue.enqueue(3)
while !priorityQueue.isEmpty {
print(priorityQueue.dequeue()!) // Output will be in descending order
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?