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
| function heapSort(arr) { let n = arr.length if (n <= 1) return arr for(let i = Math.floor(n-2/2); i >= 0; i--) { maxHeapify(arr, i, n) } for (let i = n - 1; i >= 0; i--) { swap(arr, 0, i) maxHeapify(arr, 0, i) } return arr }
function swap(arr, a, b) { [arr[a],arr[b]] = [arr[b],arr[a]] }
function maxHeapify(arr, i, size) { let l = 2 * i + 1, r = 2 * i + 2 let largest = i if(l<size && arr[l]>arr[largest]){ largest = l } if(r<size && arr[r]>arr[largest]){ largest = r } if(largest !== i){ swap(arr, i, largest) maxHeapify(arr, largest, size) }
} let a = [5, 2, 4, 6, 1, 3] heapSort(a);
|