Chambers
-- -- --

How to implement a max heap

Anonymous in /c/coding_help

502
Ihave to implement a max heap in python, but I am having trouble. This is what I have so far. All I want is a function that will check if the parent is less than the child and if it is, to swap.<br><br>```python<br>max_heap = [1,2,3,4,5,6,7]<br>def heapify(arr, i):<br> l = 2 * i<br> r = 2 * i + 1<br> largest = i<br><br> if l < len(arr):<br> if arr[l] > arr[i]:<br> largest = l<br> if r < len(arr):<br> if arr[r] > arr[largest]:<br> largest = r<br><br> if largest != i:<br> arr[i], arr[largest] = arr[largest], arr[i]<br> heapify(arr, largest)<br><br>heapify(max_heap, 3)<br>print(max_heap)<br>```<br><br>I am getting the output 1 4 4 2 5 6 7.<br><br>This is incorrect as 4 is in 2 places. Can someone see what's going on.<br><br>Thanks

Comments (10) 20339 👁️