码迷,mamicode.com
首页 > 编程语言 > 详细

C++实现堆

时间:2016-06-02 00:59:48      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:数据结构      

#include <iostream>

using namespace std;

#include <vector>

#include <assert.h>


//仿函数

template<class T>

struct Less

{

bool operator()(const T& left, const T& right)

{

return left < right;

}

};


template<class T>

struct Greater

{

bool operator()(const T& left, const T& right)

{

return left > right;

}

};


template<class T, class Compare = Less<T>>//默认为小堆

class Heap

{

public:

Heap()

{}


Heap(const T* array, size_t size)

{

for (size_t i = 0; i < size; ++i)

{

_a.push_back(array[i]);

}


for (size_t i = (_a.size()-2)/2; i < _a.size(); --i)

{

_AdjustDown(i);

}

}


void Push(const T& x)

{

_a.push_back(x);


_AdjustUp(_a.size()-1);

}


void Pop()

{

assert(!_a.empty());


swap(_a[0], _a[_a.size()-1]);

_a.pop_back();

_AdjustDown(0);

}


T& GetTop()

{

assert(!_a.empty());


return _a[0];

}


bool Empty()

{

return _a.empty();

}


size_t Size()

{

return _a.size();

}


void Print()

{

for (size_t i = 0; i < _a.size(); ++i)

{

cout<<_a[i]<<" ";

}

cout<<endl;

}


protected:

//向下调整

void _AdjustDown(size_t parent)

{

Compare compare;

size_t child = parent*2 + 1;


while (child < _a.size())

{

//比较左右孩子

if (child+1 < _a.size() 

&& compare(_a[child+1], _a[child]))

{

++child;

}


if (compare(_a[child], _a[parent]))

{

swap(_a[child], _a[parent]);


parent = child;

child = parent*2 + 1;

}

else

{

break;

}

}

}


//向上调整

void _AdjustUp(size_t child)

{

Compare compare;

size_t parent = (child-1)/2;

while (child > 0)

{

if (compare(_a[child], _a[parent]))

{

swap(_a[parent], _a[child]);


child = parent;

parent = (child-1)/2;

}

else

{

break;

}

}

}


protected:

vector<T> _a;

};



void Test()

{

int a[10] = {10, 11, 13, 12, 16, 18, 15, 17, 14, 19};

Heap<int, Greater<int>> hp1(a, sizeof(a)/sizeof(a[0]));

hp1.Print();

cout<<"size:"<<hp1.Size()<<endl;

cout<<"top:"<<hp1.GetTop()<<endl;

cout<<"empty:"<<hp1.Empty()<<endl;

}


int main()

{

Test();


return 0;

}


本文出自 “zgw285763054” 博客,请务必保留此出处http://zgw285763054.blog.51cto.com/11591804/1785308

C++实现堆

标签:数据结构      

原文地址:http://zgw285763054.blog.51cto.com/11591804/1785308

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!