liveBook · Manning

Priority queue

As explained in Classic Computer Science Problems in Swift: Essential techniques for practicing programmers

A priority queue is a data structure that removes elements according to priority rather than insertion order.

In A* maze search, the frontier holds locations still to explore. A priority queue pops the most promising one first—not necessarily the one added first. Here, “highest priority” means the lowest estimated total cost, f(n) = g(n) + h(n): cost so far plus estimated cost to the goal. section 2.2

A* therefore uses a different frontier from depth-first search’s stack or breadth-first search’s queue. A priority queue usually uses a binary heap, giving O(log n) pushes and pops. In Swift, the example uses SwiftPriorityQueue rather than building one from scratch. section 2.2

class Node<T>: Comparable, Hashable {
    let state: T
    let parent: Node?
    let cost: Float
    let heuristic: Float
    init(state: T, parent: Node?, cost: Float = 0.0, heuristic: Float = 0.0) {
        self.state = state
        self.parent = parent
        self.cost = cost
        self.heuristic = heuristic
    }

    var hashValue: Int { return Int(cost + heuristic) }
}

func < <T>(lhs: Node<T>, rhs: Node<T>) -> Bool {
    return (lhs.cost + lhs.heuristic) < (rhs.cost + rhs.heuristic)
}

func == <T>(lhs: Node<T>, rhs: Node<T>) -> Bool {
    return lhs === rhs
}

A search node implements Comparable by comparing cost + heuristic, so the queue can order nodes by f(n). section 2.2

How Classic Computer Science Problems in Swift: Essential techniques for practicing programmers covers it

How deep it goes
Defines pop order and notes typical heap performance, but defers implementation to SwiftPriorityQueue.
Examples
Uses Swift search nodes whose Comparable ordering evaluates cost plus heuristic.
What it assumes
Assumes familiarity with Swift nodes and search frontiers; introduces priority ordering without teaching heap construction.
What you can do after
Apply it via SwiftPriorityQueue to order an A* frontier by estimated total cost.
How it connects
Connects A* search, search frontiers, heuristics, binary heaps, depth-first search, and breadth-first search.

Also explained in

Compare how 5 books explain priority queue →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Classic Computer Science Problems in Swift: Essential techniques for practicing programmers. The section links point to the parts of the book it draws on.