Nenhuma descrição

heap.py 962B

1234567891011121314151617181920212223242526272829303132333435363738
  1. ''' Luis Andrés López Mañán
  2. Program written by hand as a draft on 09/19/2022
  3. Credit goes to GeeksForGeeks
  4. Link: https://www.geeksforgeeks.org/python-program-for-heap-sort/
  5. Last access on 09/19/2022
  6. Program wrriten and edited on 10/10/2022
  7. '''
  8. # Python program for implementation of heap Sort (Part I)
  9. # This function heapifies a subtree rooted at an index
  10. # i. Also, n is the size of a heap and arr is array.
  11. def heapify(lista, n, i):
  12. largest = i # Initialize largest as root
  13. l = 2 * i + 1 # left = 2*i + 1
  14. r = 2 * i + 2 # right = 2*i + 2
  15. # See if left child of root exists and is
  16. # greater than root
  17. if l < n and lista[i] < lista[l]:
  18. largest = l
  19. # See if right child of root exists and is
  20. # greater than root
  21. if r < n and lista[largest] < lista[r]:
  22. largest = r
  23. # Change root, if needed
  24. if largest != i:
  25. (lista[i], lista[largest]) = (lista[largest], lista[i]) # swap
  26. # Heapify the root.
  27. heapify(lista, n, largest)