c++小根堆数组实现

本文介绍了如何使用C++实现小根堆的主要功能,包括最小堆排序、删除首元素和插入元素。提供了向下调整小根堆的关键代码,并且包含了迭代版本的实现,确保父节点值小于其左右子节点值。
主要功能

最小堆排序(大到小):
void order();
删除首元素:
Type fetch_root();
插入元素:
void insert_item(const Type & item);
void insert_item_faster(const Type & item);//快速版本

关键
  • 向下调整比较关键,即从start结点到end结点逐个调整最小堆:
    void shiftdown(Type* array, int start, int end);
    另外是实现了迭代版本,效果都是一样的;
    void shiftdown_regression(Type* array, int start, int end);
  • 最小堆调整函数:
    int mini_operation(Type* array, int father, int lchild , int rchild);
    保证父结点比左右子都小;
source code
/**
 * @file mini-complete-binary-heap.cpp
 * @brief 
 * @author anribras@gmail.com
 * @version 
 * @date 2017-07-04
 */
#include <string.h>
#include <stdio.h>

#include <iostream>
#include <math.h>
#include <stdlib.h>


using namespace std;


#define min_2(a,b) ((a<b)?(a):(b))
#define min_3(a,b,c) min_2(min_2(a,b),min_2(a,c))
#define Null (0)


/** @brief min_array_heap 
 *
 * 最小根堆 最大的作用是从huge数据中找到最小的元素
 *           也可以排序
 *
 *
 * */


template<typename Type>
class min_array_heap {
    private:
        int m_size;
        Type* m_array;
        void swap(Type & a, Type & b) {
            Type tmp;
            tmp = a;
            a = b;
            b = tmp;
        };

        //从i节点开始往下调整,调整到第end个节点,序号从0开始
        void shiftdown(Type* array, int start, int end) {
            int lchild = 2* start + 1;
            int rchild = 2* start + 2;

            int min;
            while (lchild <= end) {
                //cout << "father[" << start << "] = " << array[start] << endl;
                //cout << "left child[" << lchild << "] = " << array[lchild] << endl;
                //cout << "right child[" << rchild << "] = " << array[rchild] << endl;
#if 0
                // 左子 < 父亲
                if( array[lchild] < array[start]) {
                    // 如果 右子存在 且 右子 < 左子
                    if (  (rchild < end)  && (array[rchild] < array[lchild]) ) {
                        swap(array[rchild],array[start]);
                        start ++;
                    } else 
                        swap(array[lchild],array[start]);
                } 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值