def max_heapify(A, i): """Given array A and index i, max_heapify assumes left(i) and right(i) are max-heaps, but A[i] might be smaller than its children.""" L = left(i) R = right(i) if L <= len(A) - 1 and A[L] > A[i]: # assume len(A) is A.heap_size largest = L else: largest = i if R <= len(A) - 1 and A[R] > A[largest]: largest = R if largest != i: A[i], A[largest] = A[largest], A[i] max_heapify(A, largest)
def minheapify(self, A, i): ''' 保持堆:使某一个结点i成为最小堆(其子树本身已经为最小堆) ''' l = heap.left(i) r = heap.right(i) minest = 0 if l <= heap.heapsize(A) and A[l] <= A[i]: minest = l else: minest = i if r <= heap.heapsize(A) and A[r] <= A[minest]: minest = r if minest != i: A[i], A[minest] = A[minest], A[i] self.minheapify(A, minest) return A
def maxheapify(self, A, i): ''' 保持堆:使某一个结点i成为最大堆(其子树本身已经为最大堆) ''' l = heap.left(i) r = heap.right(i) largest = 0 if l <= heap.heapsize(A) and A[l] >= A[i]: largest = l else: largest = i if r <= heap.heapsize(A) and A[r] >= A[largest]: largest = r if largest != i: A[i], A[largest] = A[largest], A[i] self.maxheapify(A, largest) return A
def maxheapify_quick(self, A, i): ''' 保持堆:使某一个结点i成为最大堆(其子树本身已经为最大堆) ''' count = len(A) largest = count while largest != i: l = heap.left(i) r = heap.right(i) if l <= heap.heapsize(A) and A[l] >= A[i]: largest = l else: largest = i if r <= heap.heapsize(A) and A[r] >= A[largest]: largest = r if largest != i: A[i], A[largest] = A[largest], A[i] i, largest = largest, count return A
def test_right(self): self.assertEqual(6, right(2)) self.assertEqual(8, right(3))