No Description

heap.py 1.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. # This function heapifies a subtree rooted at an index
  8. # i. Also, n is the size of a heap and arr is array.
  9. def heapify (arr, n, i):
  10. # largest is root for now
  11. largest = i
  12. # left child of root
  13. left = 2 * i + 1
  14. # right child of root
  15. right = 2 * i + 2
  16. # Checks if root has a left child and is greater
  17. # than root
  18. if l < n and arr[i] < arr[l] :
  19. largest = l
  20. # Checks if root has a right child and is greater
  21. # than root
  22. if r < n and arr[largest] < arr[r]:
  23. largest = r
  24. # If necessary, this changes root by swapping va-
  25. # lues
  26. arr[i], arr[largest] = arr[largest], arr[i]
  27. # This heapifies the root repeatedly
  28. heapify(arr, n, largest)
  29. # This function sorts an array of a given size n
  30. def heapSort(arr, n):
  31. # A max heap is built and last parent will be at
  32. # position number h1, i.e., half the given size of
  33. # and array. Therefore, that will be the starting
  34. # location.
  35. h1 = n // 2 - 1
  36. for i in range(h1, -1, -1):
  37. heapify(arr, n, i)
  38. # This extracts elements one by one.
  39. for i in range(n - 1, 0, -1):
  40. # Swaps, then heapifies
  41. arr[i], arr[0] = arr[0], arr[i]
  42. heapify(arr, i, 0)