Max Heap (3, a) |
function maxSiftDown(arr, i=0, value=arr[i], comparator) {
if (i >= arr.length) return;
while (true) {
var j = i*2+1;
if (j+1 < arr.length && comparator(arr[j], arr[j+1])) j++;
if (j >= arr.length || !comparator(value, arr[j])) break;
arr[i] = arr[j];
i = j;
}
arr[i] = value;
}
function maxHeapify(arr, comparator) {
for (var i = arr.length>>1; i--; ) maxSiftDown(arr, i, arr[i], comparator);
return arr;
}
function partialSortWithMaxHeap(items, k, comparator) {
var heap = maxHeapify(items.slice(0, k), comparator);
for (var i = k, len = items.length; i < len; ++i) {
var item = items[i];
if (comparator(item, heap[0])) maxSiftDown(heap, 0, item, comparator);
}
return heap.sort(comparator);
}
var arr = Array.from({length:20}, () => Math.floor(Math.random() * 1e5));
partialSortWithMaxHeap(arr, 3, (a, b) => a < b);
| ready |
Max Heap (5) |
function maxSiftDown(arr, i=0, value=arr[i], comparator) {
if (i >= arr.length) return;
while (true) {
var j = i*2+1;
if (j+1 < arr.length && comparator(arr[j], arr[j+1])) j++;
if (j >= arr.length || !comparator(value, arr[j])) break;
arr[i] = arr[j];
i = j;
}
arr[i] = value;
}
function maxHeapify(arr, comparator) {
for (var i = arr.length>>1; i--; ) maxSiftDown(arr, i, arr[i], comparator);
return arr;
}
function partialSortWithMaxHeap(items, k, comparator) {
var heap = maxHeapify(items.slice(0, k), comparator);
for (var i = k, len = items.length; i < len; ++i) {
var item = items[i];
if (comparator(item, heap[0])) maxSiftDown(heap, 0, item, comparator);
}
return heap.sort(comparator);
}
var arr = Array.from({length:20}, () => Math.floor(Math.random() * 1e5));
partialSortWithMaxHeap(arr, 5, (a, b) => a < b);
| ready |