-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHeapSort.js
30 lines (23 loc) · 850 Bytes
/
HeapSort.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
import Sort from '../Sort';
import MinHeap from '../../../data-structures/heap/MinHeap';
export default class HeapSort extends Sort {
sort(originalArray) {
const sortedArray = [];
const minHeap = new MinHeap(this.callbacks.compareCallback);
// Insert all array elements to the heap.
originalArray.forEach((element) => {
// Call visiting callback.
this.callbacks.visitingCallback(element);
minHeap.add(element);
});
// Now we have min heap with minimal element always on top.
// Let's poll that minimal element one by one and thus form the sorted array.
while (!minHeap.isEmpty()) {
const nextMinElement = minHeap.poll();
// Call visiting callback.
this.callbacks.visitingCallback(nextMinElement);
sortedArray.push(nextMinElement);
}
return sortedArray;
}
}