Chapter 25: Priority Queue Challenges
public struct PriorityQueueArray<T: Equatable>: Queue {
// 利用array來存elements
private var elements: [T] = []
let sort: (Element, Element) -> Bool
public var isEmpty: Bool {
return elements.isEmpty
}
public var peek: T? {
return elements.first
}
// 建立init
public init(sort: @escaping(Element, Element) -> Bool, elements: [Element] = []) {
self.sort = sort
self.elements = elements
// 將element進行排序
// Accord to Apple the sort function takes O(n log n) time.
// Swift's sort function uses introsort which is a combination of insertion sort and heap sort.
self.elements.sort(by: sort)
}
public mutating func enqueue(_ element: T) -> Bool {
// O(n)
for (index, otherElement) in elements.enumerated() {
// 檢查element是否有更高priority
if sort(element, otherElement) {
elements.insert(element, at: index)
return true
}
}
// If the element does not have a higher priority than any element in the queue, simply append the element to the end
elements.append(element)
return true
}
public mutating func dequeue() -> T? {
// O(n) operation, since you have to shift the existing elements to the left by one.
return isEmpty ? nil : elements.removeFirst()
}
}Last updated