A binary heap which satisfies max-heap property is called max-heap. In a max-heap, for…
- User
A binary heap which satisfies max-heap property is called max-heap. In a max-heap, for every node other than the root, , that is, the value of a node is at most the value of its parent. The largest element in a max-heap is stored at the root, and the subtree rooted at a node contains values no larger than that contained at the node itself.
Here is an example of a max-heap.
Write a program which reads an array and constructs a max-heap from the array based on the following pseudo code.
move the value of down to leaves to make a sub-tree of node a max-heap. Here, is the size of the heap.
Assistant
def max_heapify(A, i, H): l = 2 * i + 1 r = 2 * i + 2 largest = i if l < H and A[l] > A[largest]: largest = l if r < H and A[r] > A[largest]: largest = r if largest != i: A[i], A[largest] = A[largest], A[i] max_heapify(A, largest, H) def build_max_heap(A): H = len(A) for i in range((H - 1) // 2, -1, -1): max_heapify(A, i, H) H = int(input()) A = list(map(int, input().split())) build_max_heap(A) print(' ' + ' '.join(map(str, A)))
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.