`

阅读更多
在优先级队列的各种实现中,堆是最高效的一种数据结构

关键码:在各个数据记录中存在一个能够标识数据记录(或元素)的数据项,并将依据该数据项对数据进行组织,这个数据项就是关键码

最小堆:父结点总是小于等于子结点

最大堆:父结点总是大于等于子结点
MinHeap.h
#ifndef MINHEAP_H
#define MINHEAP_H

#include"../T3/PQueue.h"
#include<assert.h>

#define DefaultSize 10

template<typename E>
class MinHeap:public PQueue<E>{
public:
    MinHeap(int sz=DefaultSize);
    MinHeap(E arr[],int n);
    ~MinHeap(){delete[]heap;}
    bool Insert(const E &x);
    bool RemoveMin(E &x);
    bool IsEmpty() const{
        return currentSize==0?true:false;
    }
    bool IsFull()const{
        return currentSize==maxHeapSize?true:false;
    }
    void makeEmpty(){
        currentSize=0;
    }
    void display();
private:
    E *heap;
    int currentSize;
    int maxHeapSize;
    void siftDown(int start,int m);
    void siftUp(int start);
};

template<typename E>
MinHeap<E>::MinHeap(int sz)
{
    maxHeapSize=sz>DefaultSize?sz:DefaultSize;
    heap=new E[maxHeapSize];
    assert(heap!=NULL);
    currentSize=0;
}

/*
  最小堆的下滑高速算法
  */
template<typename E>
void MinHeap<E>::siftDown(int start, int m)
{
    int i=start,j=2*i+1;
    E temp = heap[i];
    while(j<=m){
        if(j<m&&heap[j]>heap[j+1]){
            j++;//指向子女中最小的一个
        }
        if(temp<=heap[j]){
            break;
        }else{
            heap[i]=heap[j];
            i=j;
            j=j*2+1;
        }
    }
    heap[i]=temp;
}

template<typename E>
MinHeap<E>::MinHeap(E arr[], int n)
{
    maxHeapSize=n>DefaultSize?n:DefaultSize;
    heap=new E[maxHeapSize];
    assert(heap!=NULL);
    for(int i=0;i<n;++i)
        heap[i]=arr[i];
    currentSize=n;
    int currentPos=(currentSize-2)/2;
    while(currentPos>=0){//自底向上逐步扩大
        siftDown(currentPos,currentSize-1);
        currentPos--;
    }
}

/*
  把start处的结点向上调整
  */
template<typename E>
void MinHeap<E>::siftUp(int start)
{
    int j=start,i=(j-1)/2;
    E temp=heap[j];
    while(j>0){
        if(heap[i]<=temp){
            break;
        }else{
            heap[j]=heap[i];
            j=i;
            i=(i-1)/2;
        }
    }
    heap[j]=temp;
}

template<typename E>
bool MinHeap<E>::Insert(const E &x)
{
    if(currentSize==maxHeapSize){
        cerr << "full" << endl;
        return false;
    }
    heap[currentSize]=x;
    siftUp(currentSize);
    currentSize++;
    return true;
}

template<typename E>
bool MinHeap<E>::RemoveMin(E &x)
{
    if(currentSize==0){
        cout << "empty" << endl;
        return false;
    }
    x=heap[0];
    currentSize--;
    siftDown(0,maxHeapSize-1);
    return true;
}

template<typename E>
void MinHeap<E>::display()
{
    for(int i=0;i<currentSize;++i)
        cout << heap[i] << " ";
}

#endif // MINHEAP_H


MinHeap.cpp
#include "MinHeap.h"

int main(){
    int a[10]={53,17,78,9,45,65,87,23};
    MinHeap<int> minHeap(a,8);
    minHeap.display();
}

9 17 65 23 45 78 87 53


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics