← Course home

Python reference · Reference

Heaps

Maintain a partial order when the next smallest or largest item matters most.

ReferenceAbout 2 min

This page lists the library modules for Heaps. The lesson is Heap operations.

This page is the module index for heaps.

Review the heap invariant and heapsort, then see priority queues for indexed updates.

  • heaps/heapsort.py — heapify is O(n); heapsort is O(n log n) time and O(1) extra memory. Not stable.
  • heaps/priority_queue.py — min-heap with decrease_key through an index map. Push, pop, and decrease-key are O(log n).

Industry

A working engineer uses heapq as a priority queue. Python documents a min-heap whose smallest item is always heap[0], with heapify in linear time. Removing that root and restoring the heap is logarithmic, and repeating the removal sorts in O(n log n). The same page notes that this heapsort is not stable, which is also true of heapsort here.

Implementation and tests Optional reference

Library code 2

  • bitsandbytes.heaps.heapsort
  • bitsandbytes.heaps.priority_queue

Use these references to compare the explanation with repository code and tests. A test link means it imports a lesson symbol; it does not by itself claim complete behavior coverage.