Keine Beschreibung

heap.py 994B

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. # This function heapifies a subtree rooted at an index
  9. # i. Also, n is the size of a heap and arr is array.
  10. def heapify(lista, n, i):
  11. # largest is root for now
  12. largest = i
  13. # left child of root
  14. l = 2 * i + 1
  15. # right child of root
  16. r = 2 * i + 2
  17. # Checks if root has a left child and is greater
  18. # than root
  19. if l < n and lista[i] < lista[l] :
  20. largest = l
  21. # Checks if root has a right child and is greater
  22. # than root
  23. if r < n and lista[largest] < lista[r]:
  24. largest = r
  25. # If necessary, this changes root by swapping va-
  26. # lues
  27. if largest != i:
  28. lista[i], lista[largest] = lista[largest], lista[i]
  29. # This heapifies the root repeatedly
  30. heapify(lista, n, largest)