Heap sort is a comparison-based sorting algorithm that uses a binary heap data structure. It divides its input into a sorted and an unsorted region, and it iteratively shrinks the unsorted region by extracting the largest element from it and moving that to the end of the sorted region. The heap data structure ensures that the largest (or smallest) element is always at the root of the heap, making it easy to extract.
Heap sort is an efficient sorting algorithm with a time complexity of \(O(n \log n)\) in the worst, average, and best cases. It's not a stable sort, meaning that it does not preserve the relative order of equal elements. However, its performance is consistent across different types of input data, making it suitable for large datasets.
A heap is a specialized tree-based data structure that satisfies the heap property: for any given node \(i\), the value of \(i\) is greater than or equal to (in a max heap) or less than or equal to (in a min heap) the values of its children. This property ensures that the largest element in a max heap is always at the root.
To perform heap sort, we first need to build a max heap from the input data. This involves rearranging the elements so that they satisfy the max heap property.
\((n/2) - 1\), where \(n\) is the total number of nodes.function buildMaxHeap(arr) {
const n = arr.length;
// Start from the last non-leaf node and heapify each node
for (let i = Math.floor(n / 2) - 1; i >= 0; i--) {
heapify(arr, n, i);
}
}
function heapify(arr, n, i) {
let largest = i; // Initialize largest as root
const left = 2 * i + 1; // Left child index
const right = 2 * i + 2; // Right child index
// If left child is larger than root
if (left < n && arr[left] > arr[largest]) {
largest = left;
}
// If right child is larger than largest so far
if (right < n && arr[right] > arr[largest]) {
largest = right;
}
// If largest is not root
if (largest !== i) {
[arr[i], arr[largest]] = [arr[largest], arr[i]]; // Swap
// Recursively heapify the affected sub-tree
heapify(arr, n, largest);
}
}
function heapSort(arr) {
const n = arr.length;
// Build a max heap
buildMaxHeap(arr);
// One by one extract an element from heap
for (let i = n - 1; i > 0; i--) {
// Move current root to end
[arr[0], arr[i]] = [arr[i], arr[0]];
// Call max heapify on the reduced heap
heapify(arr, i, 0);
}
}
// Example usage:
const data = [12, 11, 13, 5, 6, 7];
heapSort(data);
console.log("Sorted array is:", data);
Time Complexity: \(O(n \log n)\)
\(O(n)\).\(n\) elements is extracted from the heap with a cost of \(O(\log n)\).Space Complexity: \(O(1)\)
Heap sort is used in various applications where efficiency and consistency are crucial:
By understanding the heap sort algorithm, you can effectively utilize it in scenarios requiring efficient sorting of large datasets.