排序算法-大根堆c++ && javascript实现

知识点

堆:一个完全二叉树;

大根堆:除根结点外的所有节点,其节点的值小于等于父结点;
小根堆:除根结点外的所有节点,其节点的值大于等于父结点;
堆排序:O(nlogn),O(1),不稳定;

满二叉树:每个节点是叶节点或度为2
完美二叉树:深度为k,节点个数为2^k-1个的二叉树
完全二叉树:节点的编号与完美二叉树的编号一一对应

函数说明

  • heapify:让当前结点的子树满足最大堆或最小堆的定义
  • swap:交换
  • build_heap:建立堆,从第一个非叶子结点开始逐渐向上遍历,也就是遍历的每个结点都调用heapify函数
  • heap_sort:实现堆排序(大根堆),让根结点(index=0)与最后一个节点交换,这时,不满足大根堆,于是把最后一个节点(也就是最大值)砍掉,重新对根结点进行heapify
function swap(tree, i, j){
    let temp = tree[i];
    tree[i] = tree[j];
    tree[j] = temp;
}
function heapify(tree, n, i){
    if (i >= n) return;
    let left = i*2 + 1;
    let right = i*2 + 2;
    let max = i;
    if (left < n && tree[left] > tree[max]){
        max = left;
    }
    if (right < n && tree[right] > tree[max]){
        max = right;
    }
    if (max !== i){
        swap(tree, max, i);
        heapify(tree, n, max);
    }
}

function build_heap(tree, n){
    let last_node = n-1;
    let parent = Math.floor((last_node - 1) / 2); // 注意向下取整
    for (let i = parent; i >= 0; i--){
        heapify(tree, n, i);
    }
}

function heap_sort(tree, n){
    build_heap(tree, n);
    for (let i=n-1; i>=0; i--){
        swap(tree, 0, i);
        heapify(tree, i, 0);
    }
}
let tree = [2,4,6,3,10,1,5];
heap_sort(tree, 7);
console.log(tree);
#include <iostream>
using namespace std;


void swap(int tree[], int i, int j){
    int temp = tree[i];
    tree[i] = tree[j];
    tree[j] = temp;
}
// 最大堆就是一个完全二叉树
// 当前节点i(i表示下标)的parent的index: (i-1)/2
// 当前节点i的left-child的index:i*2 + 1
// 当前节点i的right-child的index:i*2 + 2
void heapify(int tree[], int n, int i){
    // heapify就是从某个节点出发,让这个节点满足最大堆的定义
    if (i >= n) return;
    // n表示数组的长度,i表示当前的第几个元素
    int c1 = i*2 + 1;
    int c2 = i*2 + 2;
    int max = i;
    if (c1 < n && tree[c1] > tree[max]){
        max = c1;
    }
    if (c2 < n && tree[c2] > tree[max]){
        max = c2;
    }
    if (max != i){
        swap(tree, i, max); // 说明存在比tree[i]大的值
        heapify(tree, n, max);
    }
}

void build_heap(int tree[], int n){ // 建立大根堆
    // 从第一个非叶子结点开始做heapify
    int last_node = n-1;
    int parent = (last_node - 1) / 2;
    for (int i=parent; i>=0; i--){
        heapify(tree, n, i);
    }
}
void heap_sort(int tree[], int n){
    build_heap(tree, n);
    for (int i=n-1; i>=0; i--){ 
        swap(tree, i, 0); 
        // 将第一个节点,也就是最大值与最后一个元素交换,然后把最后一个元素“砍断”,不进行heapify
        heapify(tree, i, 0); // O(logi)
    }
}
int main(){
    int tree[] = {2,4,6,3,10,1,5};
    // heapify(tree, 7, 0);
    heap_sort(tree, 7);
    for(int i=0; i<7; i++){
        cout << tree[i] << " ";
    }
    cout << endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值