Heap Sort Implementation in Python
Overview
Heap sort algorithm is very efficient and costs O(log(n)) time complexity.
Here is an implementation in Python.
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
# # Create heap subtree rooted at index i of total n elements. # def make_heap(arr, 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 it is greater than root if l < n and arr[i] < arr[l]: largest = l # See if right child of root exists and is greater than root if r < n and arr[largest] < arr[r]: largest = r # Change root, if needed if largest != i: arr[i],arr[largest] = arr[largest],arr[i] # swap # Create heap rooted at the largest. make_heap(arr, n, largest) # The main function to sort an array of given size def heap_sort(arr): n = len(arr) for i in range(n, -1, -1): make_heap(arr, n, i) # One by one extract elements for i in range(n-1, 0, -1): arr[i], arr[0] = arr[0], arr[i] # swap make_heap(arr, i, 0) if __name__ == '__main__': numbers = [ int(i) for i in input("Enter numbers: ").rstrip().split() ] heap_sort(numbers) print("Heap Sort Result: ", numbers) |