Brak opisu

heap.py 979B

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 is root for now
  13. largest = i
  14. # left child of root
  15. left = 2 * i + 1
  16. # right child of root
  17. right = 2 * i + 2
  18. # Checks if root has a left child and is greater
  19. # than root
  20. if l < n and lista[i] < lista[l] :
  21. largest = l
  22. # Checks if root has a right child and is greater
  23. # than root
  24. if r < n and lista[largest] < lista[r]:
  25. largest = r
  26. # If necessary, this changes root by swapping va-
  27. # lues
  28. lista[i], lista[largest] = lista[largest], lista[i]
  29. heapify(lista, n, largest)