|
| 1 | +# Author: OMKAR PATHAK |
| 2 | + |
| 3 | +# Approach: |
| 4 | +# Heap sort happens in two phases. In the first phase, the array |
| 5 | +# is transformed into a heap. A heap is a binary tree where |
| 6 | +# 1) each node is greater than each of its children |
| 7 | +# 2) the tree is perfectly balanced |
| 8 | +# 3) all leaves are in the leftmost position available. |
| 9 | +# In phase two the heap is continuously reduced to a sorted array: |
| 10 | +# 1) while the heap is not empty |
| 11 | +# - remove the top of the head into an array |
| 12 | +# - fix the heap. |
| 13 | + |
| 14 | +# Time Complexity of Solution: |
| 15 | +# Best O(nlog(n)); Average O(nlog(n)); Worst O(nlog(n)). |
| 16 | + |
| 17 | +def HeapSort(alist): |
| 18 | + heapify(alist) # create the heap |
| 19 | + end = len(alist) - 1 |
| 20 | + while end > 0: |
| 21 | + alist[end], alist[0] = alist[0], alist[end] |
| 22 | + shiftDown(alist, 0, end - 1) |
| 23 | + end -= 1 |
| 24 | + |
| 25 | +def heapify(alist): |
| 26 | + ''' This function helps to maintain the heap property ''' |
| 27 | + # start = (len(alist) - 2) // 2 (faster execution) |
| 28 | + start = len(alist) // 2 |
| 29 | + while start >= 0: |
| 30 | + shiftDown(alist, start, len(alist) - 1) |
| 31 | + start -= 1 |
| 32 | + |
| 33 | +def shiftDown(alist, start, end): |
| 34 | + root = start |
| 35 | + while root * 2 + 1 <= end: |
| 36 | + child = root * 2 + 1 |
| 37 | + # right child exists and is greater than left child |
| 38 | + if child + 1 <= end and alist[child] < alist[child + 1]: |
| 39 | + child += 1 |
| 40 | + # if child is greater than root(parent), then swap their positions |
| 41 | + if child <= end and alist[root] < alist[child]: |
| 42 | + alist[root], alist[child] = alist[child], alist[root] |
| 43 | + root = child |
| 44 | + else: |
| 45 | + return |
| 46 | + |
| 47 | +if __name__ == '__main__': |
| 48 | + alist = [12, 2, 4, 5, 2, 3] |
| 49 | + HeapSort(alist) |
| 50 | + print('Sorted Array:',alist) |
0 commit comments