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