1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| class Solution: def max_heapify(self, heap, root, heap_len): p = root while p * 2 + 1 < heap_len: l, r = p * 2 + 1, p * 2 + 2 if heap_len <= r or heap[r] < heap[l]: nex = l else: nex = r if heap[p] < heap[nex]: heap[p], heap[nex] = heap[nex], heap[p] p = nex else: break def build_heap(self, heap): for i in range(len(heap) - 1, -1, -1): self.max_heapify(heap, i, len(heap))
def heap_sort(self, nums): self.build_heap(nums) for i in range(len(nums) - 1, -1, -1): nums[i], nums[0] = nums[0], nums[i] self.max_heapify(nums, 0, i) def sortArray(self, nums): self.heap_sort(nums) return nums
|