二叉堆的简单实现

二叉堆即优先队列,在本例程中,我们将用自增数组模拟完全二叉树。我将《数据结构与算法分析》上的的代码片段加入自己的理解简单实现了该结构:

BinaryHeap.hpp:

#ifndef BINARYHEAP_HPP_INCLUDED #define BINARYHEAP_HPP_INCLUDED # include <vector>

using namespace std; template <typename Comparable>
class BinaryHeap { public : explicit BinaryHeap( int capacity = 100 ) : array( capacity ) { } explicit BinaryHeap( const vector<Comparable> &items ) : array( items.size() + 10 ),currentSize( items.size() ) { for ( int i = 0 ; i < items.size() ; i++ ) array[i + 1] = items[i]; buildHeap(); } bool isEmpty() const { return currentSize == 0; } const Comparable& findMin() const { return array[1]; } void insert( const Comparable &x ) { if ( currentSize = array.size() - 1 ) array.resize( array.size() * 2 ); int hole = ++currentSize; for ( ; hole > 1 && x < array[ hole/2 ] ; hole /= 2 ) array[hole] = array[ hole/2 ]; array[hole] = x; } void deleteMin() { if ( isEmpty() ) return; array[1] = array[ currentSize-- ]; percolateDown( 1 ); } void deleteMin( Comparable &minItem ) { if ( isEmpty() ) return ; minItem = array[1]; array[1] = array[ currentSize-- ]; percolateDown( 1 ); } void makeEmpty() { while ( !isEmpty() ) deleteMin(); } private : int currentSize; vector<Comparable> array; void buildHeap() { for ( int i = currentSize / 2 ; i > 0 ; i-- ) percolateDown( i ); } void 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; } }; #endif // BINARYHEAP_HPP_INCLUDED

再写个测试的主程序:

#include <iostream> #include "BinaryHeap.hpp"

using namespace std; int main() { cout << "输入一些数据:" << endl; int temp; vector<int> vec; while ( cin >> temp ) vec.push_back( temp ); BinaryHeap<int> BH( vec ); cout << "按升序输出:" << endl; while ( !BH.isEmpty() ){ cout << BH.findMin() << endl; BH.deleteMin(); } return 0; }

 

你可能感兴趣的:(二叉堆的简单实现)