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 maxHeapify(A, i, H): l = 2 * i r = 2 * i + 1 largest = i if l <= H and A[l] > A[i]: largest = l if r <= H and A[r] > A[largest]: largest = r if largest != i: A[i], A[largest] = A[largest], A[i] maxHeapify(A, largest, H) H = int(input()) arr = list(map(int, input().split())) arr = [0] + arr # Convert to 1-based indexing for i in range(H // 2, 0, -1): maxHeapify(arr, i, H) print(' '.join(map(str, arr[1:H+1])))
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.