데이터 구조 이 진 더미 C + + 최소 더미 구현

3000 단어
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;
template<class Comparable>
class BinaryHeap
{
public:
    BinaryHeap();
    explicit BinaryHeap(const vector<Comparable>& items);

    bool isEmpty() const;
    const Comparable& findMin() const;

    void insert(const Comparable& x);
    void deleteMin();
    void deleteMin(Comparable& minItem);
    void makeEmpty();

    void printHeap() const;
private:
    int currentSize;
    vector<Comparable> array;
    void buildheap();
    void percolateDown(int hole);
};
template<class Comparable>
BinaryHeap<Comparable>::BinaryHeap() : currentSize(0)
{
    array.push_back(Comparable());
}
template<class Comparable>
BinaryHeap<Comparable>::BinaryHeap(const vector<Comparable>& items) : array(items.size() + 1), currentSize(items.size())
{
    for(size_t i = 0; i < items.size(); ++i)
        array[i + 1] = items[i];
    buildheap();
}
template<class Comparable>
bool BinaryHeap<Comparable>::isEmpty() const
{
    return currentSize == 0;
}
template<class Comparable>
const Comparable& BinaryHeap<Comparable>::findMin() const
{
    return array[1];
}
template<class Comparable>
void BinaryHeap<Comparable>::insert(const Comparable& x)
{
    int hole = ++currentSize;
    array.push_back(x);
    for(;hole > 1 && x < array[hole / 2]; hole /= 2)
        array[hole] = array[hole / 2];
    array[hole] = x;
}
template<class Comparable>
void BinaryHeap<Comparable>::deleteMin()
{
    if(isEmpty())
        return;
    array[1] = array[currentSize--];
    percolateDown(1);
}
template<class Comparable>
void BinaryHeap<Comparable>::deleteMin(Comparable &minItem)
{
    if(isEmpty())
        return;
    minItem = array[1];
    array[1] = array[currentSize--];
    percolateDown(1);
}
template<class Comparable>
void BinaryHeap<Comparable>::makeEmpty()
{
    array.clear();
    currentSize = 0;
    array.push_back(Comparable());
}
template<class Comparable>
void BinaryHeap<Comparable>::buildheap()
{
    for(int i = currentSize / 2; i > 0; --i)
        percolateDown(i);
}
template<class Comparable>
void BinaryHeap<Comparable>::percolateDown(int hole)
{
    int child;
    Comparable tmp = array[hole];
    for(; hole * 2 <= currentSize; hole = child)
    {
        child = hole * 2;
        if(child != currentSize && array[child + 1] < array[child])
            ++child;
        if(array[child] < tmp)
            array[hole] = array[child];
        else
            break;
    }
    array[hole]  = tmp;
}
template<class Comparable>
void BinaryHeap<Comparable>::printHeap() const
{
    copy(array.begin() + 1, array.begin() + currentSize + 1, ostream_iterator<Comparable>(cout, " "));
}
int main()
{
    return 0;
}

좋은 웹페이지 즐겨찾기