数据结构 -js 实现堆排序

1、 数据和工具类


module.exports.list = [9, 3, 4, 32, 42, 3, 45, 33, 2, 76, 89, 34];

module.exports.swap = function (list, i, j) {
  let temp = list[i];
  list[i] = list[j];
  list[j] = temp;
};

module.exports.display = function (list) {
  let str = "";
  for (let i = 0; i < list.length; i++) {
    str += list[i] + ", ";
  }
  console.log(str.replace(/, $/, ""));
};

2、堆排序实现

/**
 * 堆排序
 */
const { list, swap, display } = require("./utils/common");

/**
 * 开始堆排序
 */
function heapSort(list) {
  if (!list || list.length <= 1) {
    return;
  }

  //构建最大的堆
  buildMaxHeap(list);
  //1、将顶部的最大元素与最末位的元素进行交换,使得最末尾的元素脱离树结构。
  //2、重新构造最大的堆
  for (let i = list.length - 1; i > 0; i--) {
    swap(list, 0, i);
    console.log("buildMaxHeap: ", list[i]);
    heapify(list, 0, i);
  }
}

/**
 * 构建最大堆
 */
function buildMaxHeap(list) {
  //找到最后一个非叶子结点,从下向上依次构建最大堆
  let start = Math.trunc(list.length / 2) - 1;
  for (let i = start; i >= 0; i--) {
    heapify(list, i, list.length);
  }
}

/**
 * 对某一个树构造二叉堆
 */
function heapify(list, cur, length) {
  //先根据性质,找出它的左右节点的索引
  let left = 2 * cur + 1;
  let right = 2 * cur + 2;
  //默认当前节点(父节点)是最大值.
  let maxIndex = cur;
  if (left < length && list[left] > list[maxIndex]) {
    maxIndex = left;
  }
  if (right < length && list[right] > list[maxIndex]) {
    maxIndex = right;
  }
  if (maxIndex != cur) {
    swap(list, maxIndex, cur);
    heapify(list, maxIndex, length);
  }
}

heapSort(list);
display(list);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值