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 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
| export const Compare = { LESS_THAN: -1, BIGGER_THAN: 1, EQUALS: 0, };
export function reverseCompare(compareFn) { return (a, b) => compareFn(b, a); }
export function defaultCompare(a, b) { if (a === b) { return Compare.EQUALS; } return a < b ? Compare.LESS_THAN : Compare.BIGGER_THAN; }
export function swap(array, a, b) {
[array[a], array[b]] = [array[b], array[a]]; }
function heapify(array, index, heapSize, compareFn) { let largest = index; const left = 2 * index + 1; const right = 2 * index + 2; if ( left < heapSize && this.compareFn(array[left], array[largest]) === Compare.BIGGER_THAN ) { largest = left; } if ( right < heapSize && this.compareFn(array[right], array[largest]) === Compare.BIGGER_THAN ) { largest = right; } if (index !== largest) { swap(array, index, largest); heapify(array, largest, heapSize, compareFn); } }
export function buildHeap(array, compareFn) { for (let i = Math.floor(array.length / 2); i >= 0; i -= 1) { heapify(array, i, array.length, compareFn); } return array; }
export default function heapSort( sort = "asc", array, compareFn = defaultCompare ) { if (sort !== "asc" || sort !== "desc") { return undefined; } if (sort === "desc") { compareFn = reverseCompare(compareFn); } let heapSize = array.length; buildHeap(array, compareFn);
while (heapSize > 1) { swap(array, 0, --heapSize); heapify(array, 0, heapSize, compareFn); } return array; }
|