-
Notifications
You must be signed in to change notification settings - Fork 0
/
heap.js
39 lines (37 loc) · 1.32 KB
/
heap.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
// Heap a.k.a. Priority Queue is basically just a list that stays sorted
// every time you add a value, the list stays sorted.
// Javascript doesn't have a native implementation but you can make one by using a binary search
// and figuring out where to put each value prior to inserting it
let arr = [];
const binSearchGetIndex = (val) => {
let low = 0;
let high = arr.length;
while (low < high) {
let mid = (low + high) >> 1;
if (val > arr[mid]) {
low = mid + 1;
} else {
high = mid;
}
}
return low;
}
const startTime = performance.now();
for (let i = 0; i < 2000; i++) {
let rand = Math.floor(Math.random() * 20);
let index = binSearchGetIndex(rand);
arr.splice(index, 0, rand);
}
const endTime = performance.now();
console.log(`Heap approach took ${endTime - startTime} milliseconds`) // Heap approach took 2.5 milliseconds
console.log(arr); // arr will be sorted
// vs. doing a sort after each call will be significantly slower...
arr = [];
const sortStartTime = performance.now();
for (let i = 0; i < 2000; i++) {
let rand = Math.floor(Math.random() * 20);
arr.push(rand);
arr.sort();
}
const sortEndTime = performance.now();
console.log(`Sort approach took ${sortEndTime - sortStartTime} milliseconds`) // Sort approach took 53 milliseconds