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()) A = list(map(int, input().split())) def maxHeapify(arr, i, heap_size): l = 2 * i + 1 r = 2 * i + 2 largest = i if l < heap_size and arr[l] > arr[largest]: largest = l if r < heap_size and arr[r] > arr[largest]: largest = r if largest != i: arr[i], arr[largest] = arr[largest], arr[i] maxHeapify(arr, largest, heap_size) def buildMaxHeap(arr, heap_size): for i in range(heap_size // 2 - 1, -1, -1): maxHeapify(arr, i, heap_size) buildMaxHeap(A, H) 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.