Heap
Heap sort is a comparison-based sorting algorithm that uses a binary heap data structure to sort elements.
The basic idea is to build a max heap (for ascending order) or a min heap (for descending order) from the input data and repeatedly remove the maximum (or minimum) element from the heap and put it into the sorted array.
Here's how the heap sort algorithm works:
Build a max heap from the input array.
Swap the root element (maximum element) with the last element of the heap and decrease the size of the heap by 1.
Heapify the root element to maintain the heap property.
Repeat steps 2 and 3 until the size of the heap is 1.
pseudocode:
In this implementation, heapify
function is used to heapify a subtree rooted with node i
, and heapSort
function sorts the array using the heap data structure.
Finally, we use example usage to demonstrate how to sort an array using heap sort.
Last updated