如下图所示:使用数组来表示二叉树,可得
    堆 - 图1

    1. const parent = i => (i-1) >>> 1;
    2. const left = i => 1 + (i << 1);
    3. const right = i => 2 + (i << 1);
    1. const parent = i => (i-1) >>> 1;
    2. const left = i => 1 + (i << 1);
    3. const right = i => 2 + (i << 1);
    4. const swap = (nums, l, r) => [nums[l], nums[r]]=[nums[r], nums[l]];
    5. function toBottom(d, i, len, comp) {
    6. while (i < len) {
    7. let l = left(i), r = right(i), m = i;
    8. if (l < len && comp(d[l], d[m]) <= 0) {
    9. m = l;
    10. }
    11. if (r < len && comp(d[r], d[m]) <= 0) {
    12. m = r;
    13. }
    14. if (m===i) break;
    15. swap(d, i, m);
    16. i = m;
    17. }
    18. }
    19. function toUpper(d, i, comp) {
    20. while (i) {
    21. let p = parent(i);
    22. if (comp(d[p], d[i]) <= 0) break;
    23. swap(d, p, i);
    24. i = p;
    25. }
    26. }
    27. export class Heap {
    28. constructor(comp = (a, b) => a - b) {
    29. this.data = [];
    30. this.comp = comp;
    31. }
    32. push(d) {
    33. this.data.push(d);
    34. toUpper(this.data, this.data.length - 1, this.comp);
    35. }
    36. peek() {
    37. return this.data[0];
    38. }
    39. isEmpty() {
    40. return this.data.length === 0;
    41. }
    42. pop() {
    43. if (this.data.length <= 1) {
    44. return this.data.pop();
    45. }
    46. const r = this.data[0];
    47. this.data[0] = this.data.pop();
    48. toBottom(this.data, 0, this.data.length - 1, this.comp);
    49. return r;
    50. }
    51. static sort(arr, comp) {
    52. for (let i = (arr.length >>> 1); i >= 0; i--) {
    53. toBottom(arr, i, arr.length, comp);
    54. }
    55. for (let i = arr.length - 1; i > 0; i--) {
    56. swap(arr, i, 0);
    57. toBottom(arr, 0, i, comp);
    58. }
    59. arr.reverse();
    60. }
    61. }