Heap sort is a comparison-based sorting algorithm that uses a binary heap data structure. Heap sort has two main steps: building a max heap from the input list and repeatedly extracting the max element from the heap, and appending it to the sorted list.
Heap sort saves time by maintaining the unsorted region in a heap data structure to quickly find the largest element in each step, where in selection sort, heap sort does not perform linear-time scans of the unsorted region.
Heap sort starts by building a max heap from the input list, then repeatedly swapping the first element of the heap with the last element and decrementing the size of the heap. Heapify is called after each swap.
def heap_sort(arr):n = len(arr)# Max heapfor i in range(n, -1, -1):heapify(arr, n, i)# One by one extract elementsfor i in range(n - 1, 0, -1):# swaparr[i], arr[0] = arr[0], arr[i]heapify(arr, i, 0)return arr
Our heapify function is used to maintain the max-heap property of the heap.
def heapify(arr, n, i):# Largest = rootlargest = i# Leftl = 2 * i + 1# Rightr = 2 * i + 2# Check if left child of root exists and is greater than rootif l < n and arr[i] < arr[l]:largest = l# Check if right child of root exists and is greater than rootif r < n and arr[largest] < arr[r]:largest = r# If needed, change rootif largest != i:# Swaparr[i], arr[largest] = arr[largest], arr[i]# Heapify rootheapify(arr, n, largest)
Sorted array is:[11, 22, 33, 44, 77, 99]
Heap sort has a time complexity of O(n log n). This ranks this algorithm more efficient than selection and bubble sorting algorithms. Heap sort is an in-place sorting algorithm and doesn’t require additional memory.
We can make our implementation more efficient by using the built-in python heapq module which uses the heap queue algorithm.
We convert our array to a max heap by passing each element to the heapify function. Then repeatedly extracting the first element which is the maximum element of
the heap and append it to the sorted list.
import heapqdef heap_sort(arr):# Convert array to max heapheap = [x for x in arr]heapq.heapify(heap)# Pull element from heapsorted_arr = [heapq.heappop(heap) for _ in range(len(arr))]return sorted_arrarr = [44,11,77,22,99,33]print("Sorted array is: ")print(heap_sort(arr))
Sorted array is:[11, 22, 33, 44, 77, 99]
For descending order:
heap = [-x for x in arr]heapq.heapify(heap)# Pull element from heapsorted_arr = [-heapq.heappop(heap) for _ in range(len(arr))]return sorted_arr
Sorted array is:[99, 77, 44, 33, 22, 11]
Legal Stuff