How do I implement a generic priority queue in Swift?

generic priority queue, Swift, data structures, programming, algorithms
Learn how to implement a generic priority queue in Swift with this comprehensive guide and example code. Perfect for developers looking to enhance their understanding of data structures.
// 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 }

generic priority queue Swift data structures programming algorithms