c++ 最大/最小堆

用完全二叉樹的數組存儲方法

用二叉搜索樹(binary search tree)來實現

插入時,在最後插入,用上調操作,把節點調置相應位置

刪除時,刪除根節點值,以最後一個節點填補根節點,再用下調操作,把其調製相應位置

 

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn= 1000010;

class MinHeap{
public:
    MinHeap(int sz= maxn);
    MinHeap(int arr[], int n);
    void push(int x);
    void pop();
    bool empty(){
        return currentSize > 0;
    }
    int front(){
        return heap[0];
    }
    int size(){
        return currentSize;
    }
    void clear(){
        currentSize= 0;
    }
private:
    int *heap;
    int currentSize, maxSize;
    void shiftDown(int start, int m);
    void shiftUp(int start);
};
MinHeap::MinHeap(int sz){
    heap= new int[sz];
    currentSize= 0;
}
MinHeap::MinHeap(int arr[], int n){
    maxSize= n;
    heap= new int [maxSize];
    for(int i= 0; i<n; i++)heap[i]= arr[i];
    currentSize= n;
    int currentPos = currentSize/2 -1;
    while( currentPos >= 0){
        shiftDown(currentPos, currentSize -1);
        currentPos--;
    }
}
void MinHeap :: shiftDown(int start, int m){
    int i= start, j= 2*i + 1;
    int tmp= heap[i];
    while( j<= m){
        if( j<m && heap[j] > heap[j+1]) j++;
        if( tmp < heap[j]) break;
        else {
            heap[i]= heap[j];
            i= j;
            j= 2*j+ 1;
        }
        heap[i]= tmp;
    }
}
void MinHeap::shiftUp(int start){
    int j= start, i= (j-1)/2;
    int tmp = heap[j];
    while( j> 0){
        if( heap[i] <= tmp) break;
        else{
            heap[j]= heap[i];
            j= i;
            i= (i-1)/2;
        }
        heap[j]= tmp;
    }
}
void MinHeap::push(int x){
    heap[currentSize]= x;
    shiftUp(currentSize);
    currentSize++;
}
void MinHeap::pop(){
    heap[0]= heap[currentSize-1];
    currentSize--;
    shiftUp(currentSize-1);
}
int main(){
    MinHeap p(10000);
    p.push(2);
    p.push(3);
    p.push(5);
    cout<<p.front()<<endl;
    cout<<p.size()<<endl;
    p.pop();
    cout<<p.front()<<endl;
    p.clear();
    cout<<p.size();
}


 

發佈了69 篇原創文章 · 獲贊 1 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章