2

the python code is:

def max_heapify(i, arr, n):
    l = 2*i
    r = 2*i+1
    largest = i
    if (2*i <= n-1 and arr[l] > arr[i]):
        largest = l

    if (2*i+1 <= n-1 and arr[r] > arr[largest]):
        largest = r
    if largest != i:
        temp = arr[largest]
        arr[largest] = arr[i]
        arr[i] = temp

        max_heapify(largest, arr, n)
    return arr

arr=[16,4,10,14,7,9,3,2,8,1]
n=len(arr)

#max_heapify(i,arr,n)
for i in range(n//2):
    max_heapify(n//2-1-i,arr,n)
Alexandre B.
  • 5,387
  • 2
  • 17
  • 40
anadi
  • 63
  • 1
  • 6
  • 1
    `l`and `r` should be `2*i+1` and `2*i+2`, respectively. – Heike Jul 01 '19 at 10:03
  • Heike, thanks for the reply. but the output is still not correct. Can you run the code once and check? – anadi Jul 01 '19 at 10:14
  • With the array as above I get `[16, 14, 10, 8, 7, 9, 3, 2, 4, 1]` which is correct I think since 16 > max(14, 10), 14 > max(8, 7), 10 > max(9, 3), 8 > max(2, 4), and 7 > 1. – Heike Jul 01 '19 at 10:21
  • I think this link will help you https://codereview.stackexchange.com/questions/197040/min-max-heap-implementation-in-python – Ghaliah Jul 01 '19 at 10:58

1 Answers1

0

Try this

Python Program for Heap Sort

Heap sort is a comparison based sorting technique based on Binary Heap data structure. It is similar to selection sort where we first find the maximum element and place the maximum element at the end. We repeat the same process for remaining element.

Python program for implementation of heap Sort

To heapify subtree rooted at index i.

n is size of heap

def heapify(arr, n, i):

largest = i  # Initialize largest as root 

l = 2 * i + 1     # left = 2*i + 1 

r = 2 * i + 2     # right = 2*i + 2 



# See if left child of root exists and is 

# greater than root 

if l < n and arr[i] < arr[l]: 

    largest = l 



# See if right child of root exists and is 

# greater than root 

if r < n and arr[largest] < arr[r]: 

    largest = r 



# Change root, if needed 

if largest != i: 

    arr[i],arr[largest] = arr[largest],arr[i]  # swap 



    # Heapify the root. 

    heapify(arr, n, largest) 

The main function to sort an array of given size

def heapSort(arr):

n = len(arr) 



# Build a maxheap. 

for i in range(n, -1, -1): 

    heapify(arr, n, i) 



# One by one extract elements 

for i in range(n-1, 0, -1): 

    arr[i], arr[0] = arr[0], arr[i]   # swap 

    heapify(arr, i, 0) 

Driver code to test above

arr = [ 12, 11, 13, 5, 6, 7] heapSort(arr)

n = len(arr)

print ("Sorted array is")

for i in range(n):

print ("%d" %arr[i]), 

This code is contributed by Mohit Kumra

Output:

Sorted array is 5 6 7 11 12 13

Ghaliah
  • 16
  • 1