堆的C++实现

#include<iostream>
#include<cstdio>
#define e -1
#define  initiate 100
#define increase 10
using namespace std;

class heap {
private:
    int *m_heap;
    int i;
    int maxsize;
public:
    heap();
    heap(int size);
    void push(int p);
    int top();
    void pop();
    int size();

};
int heap::size() {
    return i;
}
heap::heap() {
    m_heap = (int*)malloc(sizeof(int)*initiate);
    m_heap[0] = e;
    maxsize = initiate;
    i = 0;
}
heap::heap(int size) {
    m_heap = (int*)malloc(sizeof(int)*size);
    m_heap[0] = e;
    maxsize = size;
    i = 0;
}
void heap::push(int p) {
    if (i >= maxsize) {
        int *temp = (int*)realloc(m_heap, sizeof(int)*(maxsize + increase));
        maxsize += increase;
        m_heap = temp;
    }int j;
    for (j = ++i; m_heap[j / 2] > p; j /= 2)
        m_heap[j] = m_heap[j/ 2];
    m_heap[j] = p;
    return;
}
int heap::top() {
    return m_heap[1];
}
void heap::pop() {
    if (i < 1) { cout << "heap is empty!" << endl; return; }
    if (i == 1) { i--; return; }
    int j , child = 0;
    int lastelement = m_heap[i--];
    for (j = 1; j * 2 <=i; j = child) {
        child = j * 2;
        if (child<i&&m_heap[child]>m_heap[child+1])
            child++;
        if (m_heap[child] < lastelement)
            m_heap[j] = m_heap[child];
        else
            break;
    }
    m_heap[j] = lastelement;
    return;
}

int main() {
    heap q(10);
    int n[10] = { 8,10, 15, 12, 3, 4, 13, 1, 15,56 };
    for (int i = 0; i < 10; i++) {
        q.push(n[i]);
    }
    while (q.size() > 0) {
        cout << q.top() << endl;
        q.pop();
    }
    return 0;
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值