forked from DhanushNehru/Hacktoberfest2025
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeapSort.js
More file actions
52 lines (43 loc) · 1.28 KB
/
HeapSort.js
File metadata and controls
52 lines (43 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
function heapSort(arr) {
let n = arr.length;
// Build max heap
for (let i = Math.floor(n / 2) - 1; i >= 0; i--) {
heapify(arr, n, i);
}
// Extract elements from heap one by one
for (let i = n - 1; i > 0; i--) {
// Move current root (largest) to end
let temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
// Call heapify on the reduced heap
heapify(arr, i, 0);
}
}
// Heapify a subtree rooted at index 'i'
// 'n' is the size of the heap
function heapify(arr, n, i) {
let largest = i; // Initialize largest as root
let left = 2 * i + 1; // Left child
let right = 2 * i + 2; // Right child
// 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, swap and heapify
if (largest !== i) {
let swap = arr[i];
arr[i] = arr[largest];
arr[largest] = swap;
// Recursively heapify the affected subtree
heapify(arr, n, largest);
}
}
// Test the heapSort function
let arr = [12, 11, 13, 5, 6, 7];
heapSort(arr);
console.log("Sorted array is:", arr);