# 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 # This function heapifies a subtree rooted at an index # i. Also, n is the size of a heap and arr is array. def heapify (arr, n, i): # largest is root for now largest = i # left child of root left = 2 * i + 1 # right child of root right = 2 * i + 2 # Checks if root has a left child and is greater # than root if l < n and arr[i] < arr[l] : largest = l # Checks if root has a right child and is greater # than root if r < n and arr[largest] < arr[r]: largest = r # If necessary, this changes root by swapping va- # lues arr[i], arr[largest] = arr[largest], arr[i] # This heapifies the root repeatedly heapify(arr, n, largest) # This function sorts an array of a given size n def heapSort(arr, n): # A max heap is built and last parent will be at # position number h1, i.e., half the given size of # and array. Therefore, that will be the starting # location. h1 = n // 2 - 1 for i in range(h1, -1, -1): heapify(arr, n, i) # This extracts elements one by one. for i in range(n - 1, 0, -1): # Swaps, then heapifies arr[i], arr[0] = arr[0], arr[i] heapify(arr, i, 0)