fork download
  1. def heapify(arr,n,i): #to form max heap
  2. highest=i
  3. left=(2*i)+1 #left node of the parent
  4. right=left+1 #right node of the parent
  5.  
  6. #extracting the largest of the three
  7. #i.e. parent and its children
  8. if left<n and arr[i]<arr[left]:
  9. highest=left
  10. if right<n and arr[highest]<arr[right]:
  11. highest=right
  12.  
  13. #if the chosen parent is not the highest
  14. #swap it with the largest
  15. if highest!=i:
  16. #swapping the largest
  17. arr[i],arr[highest]=arr[highest],arr[i]
  18. heapify(arr,n,highest)
  19.  
  20. def heapSort(arr):
  21. n=len(arr)
  22. #n//2 gives the first parent node
  23. #every node after n//2 is a leaf node.
  24. for i in range(n//2,-1,-1):
  25. heapify(arr,n,i)
  26.  
  27. #heapifying after deletion operation
  28. for i in range(n-1,0,-1):
  29. #swapping the last element with the root
  30. arr[0],arr[i]=arr[i],arr[0]
  31. heapify(arr,i,0)
  32.  
  33. arr = [60,50,45,40,35,20,25,30]
  34. heapSort(arr)
  35. n = len(arr)
  36. print("Sorted array is: ")
  37. for i in range(n):
  38. print("%d " % arr[i], end='')# your code goes here
Success #stdin #stdout 0.02s 9124KB
stdin
Standard input is empty
stdout
Sorted array is: 
20 25 30 35 40 45 50 60