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
H = int(input()) elements = list(map(int, input().split())) arr = [0] + elements def max_heapify(arr, i, H): l = 2 * i r = 2 * i + 1 largest = i if l <= H and arr[l] > arr[i]: 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, 0, -1): max_heapify(arr, i, H) build_max_heap(arr, 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.