-
Notifications
You must be signed in to change notification settings - Fork 0
/
Heap - Largest 3.js
84 lines (45 loc) · 1.53 KB
/
Heap - Largest 3.js
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// ======================LARGEST THREE NUMBERS======================
function heapSort(arr) {
// Build Max Heap
for (let i = Math.floor(arr.length / 2) - 1; i >= 0; i--) {
heapify(arr, i, arr.length);
}
// Heap Sort
for (let i = arr.length - 1; i > 0; i--) {
// Swap the root element (max value) with the last element
[arr[0], arr[i]] = [arr[i], arr[0]];
// Heapify the reduced heap
heapify(arr, 0, i);
}
return arr;
}
function heapify(arr, rootIndex, size) {
let largestIndex = rootIndex;
let leftChildIndex = 2 * rootIndex + 1;
let rightChildIndex = 2 * rootIndex + 2;
if (leftChildIndex < size && arr[leftChildIndex] > arr[largestIndex]) {
largestIndex = leftChildIndex;
}
if (rightChildIndex < size && arr[rightChildIndex] > arr[largestIndex]) {
largestIndex = rightChildIndex;
}
if (largestIndex !== rootIndex) {
// Swap the root with the largest element
[arr[rootIndex], arr[largestIndex]] = [arr[largestIndex], arr[rootIndex]];
// Recursively heapify the affected sub-tree
heapify(arr, largestIndex, size);
}
}
function findLargestThree(arr) {
let sortedArr = heapSort(arr);
let len = sortedArr.length;
if (len < 3) {
return sortedArr;
} else {
return [sortedArr[len - 1], sortedArr[len - 2], sortedArr[len - 3]];
}
}
// ======================TEST CASES======================
let unsortedArr = [5, 8, 3, 11, 6, 9];
let largestThree = findLargestThree(unsortedArr);
console.log(largestThree); // Output: [11, 9, 8]