Python Program for Heap Sort
Pre-requisite: What is Heap Sort?
Heapsort is a comparison-based sorting technique based on a Binary Heap data structure. It is similar to selection sort where we first find the maximum element and place the maximum element at the end. We repeat the same process for the remaining element.
Sorted array is 5 6 7 11 12 13
Time Complexity: O(n*log(n))
- The time complexity of heapify is O(log(n)).
- Time complexity of createAndBuildHeap() is O(n).
- And, hence the overall time complexity of Heap Sort is O(n*log(n)).
Auxiliary Space: O(log(n))
Approach Name: Heap Sort using Python STL
- Import the Python STL library “heapq“.
- Convert the input list into a heap using the “heapify” function from heapq.
- Create an empty list “result” to store the sorted elements.
- Iterate over the heap and extract the minimum element using “heappop” function from heapq and append it to the “result” list.
- Return the “result” list as the sorted output.
Input Array: [60, 20, 40, 70, 30, 10] Sorted Array: [10, 20, 30, 40, 60, 70]
Time Complexity: O(n log n), where “n” is the size of the input list.
Auxiliary Space: O(1).
Please refer complete article on Heap Sort for more details!
My Personal Notes arrow_drop_up
Please Login to comment...