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