Loading topic
i, the parent is at (i - 1) // 2, and the children are at 2*i + 1 and 2*i + 2.3 min readleft(i) = 2*i + 1, right(i) = 2*i + 2) and the max-heap property: every parent is at least as large as its children. Sift-down is the single operation that heap construction and heap sort both depend on. If you get i2 min readleft(i) = 2i + 1, right(i) = 2i + 2), the max-heap property, and the sift_down function from the previous chapter. The goal here is to turn any unordered array into a valid max-heap in place, which is3 min readsift_down and build_max_heap work. Here we put those pieces together into the full sorting algorithm.2 min readsift_down, build_max_heap, and heap_sort functions from the earlier chapters, and the index formulas left(i) = 2i + 1 and right(i) = 2i + 2. We will run heap sort by hand on [5, 2, 9, 1, 7, 3] and check each step against instrumented code.3 min readsift_down, build_max_heap, and heap_sort. Here we count the work those functions do and the memory they need.3 min readsift_down and heap_sort functions from the earlier chapters. You should also be comfortable sorting records by a key, for example sorting tuples by their first field.2 min readsift_down and build_max_heap. The goal is to show why calling sift_down on about n/2 nodes costs O(n) in total, not O(n log n).3 min readheapq module to sort, and see how that differs from the in-place heap sort you 3 min readsift_down, build_max_heap, and heap_sort, and that you know heap sort runs in O(n log n) time. Both variants below keep that bound. They change the constant factors: how many comparisons are made and how the memory is accessed.2 min read