堆的概念:堆是一组将 元素按照完全二叉树的形式存储在一个人以为数组里面并且在这个完全二叉树里面满足父节点和子节点的关系为Ki <= K2*i+1 且 Ki<= K2*i+2(Ki >= K2*i+1 且 Ki >= K2*i+2) i = 0,1,2…,
的一种数据结构。
分类:
- 小堆
大堆
大堆的小堆的创建
创建堆:
在创建堆的时候采用的是向下调整的方式,即从最后一个非叶节点开始向下调整,当调整到根节点的时候为止。
代码:
void _AdjustDown(int parent)
{
int child = parent*2 + 1;
Compare Cmp;
int size = hp.size();
while(child < size)
{
if(child +1< size && Cmp(hp[child] , hp[child+1]))
child = child +1;
if(Cmp(hp[parent] , hp[child]))
swap(hp[child] , hp[parent]);
else
break;
parent = child;
child = parent*2+1;
}
}
创建大堆的代码:
Heap(T* arr,size_t size)
{
if(NULL == arr)
return ;
for(int i=0;i<size;i++)
hp.push_back(arr[i]);
for(int j = (hp.size()-2)>>1;j >= 0;j--)
_AdjustDown(j);
}
在上面的代码里面含有一个选择器,用户可以利用选择器来自由选择需要创建的堆是大堆还是小堆,选择器的代码:
template<class T>
class less
{
public:
bool operator()(const T left,const T right)
{
return left > right;
}
};
template<class T>
class Grate
{
public:
bool operator()(const T left,const T right)
{
return left < right;
}
};
然后在堆的创建类里面就可以使用这个选择类来使创建的堆是按照自己的方式创建的。
在堆类里面就可以这样调用:
template< typename T , class Compare = less<T> >
堆在创建的时候是按照二叉树的形式来创建的但是在实际的内存里面存储的时候确实按照以为数组的形式在存储这些元素的,所以在这个对遍历的时候就可以按照对数组的遍历方式来进行一系列的操作。
完整的堆代码:
#ifndef __HEAP_H__
#define __HEAP_H__
#include<vector>
#include<iostream>
using namespace std;
template<class T>
class less
{
public:
bool operator()(const T left,const T right)
{
return left > right;
}
};
template<class T>
class Grate
{
public:
bool operator()(const T left,const T right)
{
return left < right;
}
};
template< typename T , class Compare = less<T> >
class Heap
{
public:
Heap()
{}
Heap(T* arr,size_t size)
{
if(NULL == arr)
return ;
for(int i=0;i<size;i++)
hp.push_back(arr[i]);
for(int j = (hp.size()-2)>>1;j >= 0;j--)
_AdjustDown(j);
}
void Show()
{
int size = hp.size();
for(int i =0;i<size;i++)
cout<<hp[i]<<" ";
cout<<endl;
}
void Insert(T d)
{
_Insert(d);
}
void Pop()
{
_Pop();
}
T& Top()
{
return hp.front();
}
T& Back()
{
return hp.back();
}
void _Pop()
{
if(hp.empty())
return ;
int size = hp.size();
swap(hp[0],hp[size -1]); //swap first and last data,next pop last data
hp.pop_back(); //pop last data
if(size > 1)
_AdjustDown(0); //adjust data
}
bool Empty()
{
return hp.empty();
}
void _Insert(T d)
{
hp.push_back(d);
int size = hp.size();
for(int i=size-1;i>0;i--)
_AdjustUp(i);
}
void _AdjustDown(int parent)
{
int child = parent*2 + 1;
Compare Cmp;
int size = hp.size();
while(child < size)
{
if(child +1< size && Cmp(hp[child] , hp[child+1]))
child = child +1;
if(Cmp(hp[parent] , hp[child]))
swap(hp[child] , hp[parent]);
else
break;
parent = child;
child = parent*2+1;
}
}
void _AdjustUp(int child)
{
int parent = (child-1)>>1;
int size = hp.size();
T p = hp[child];
while(child >= 0)
{
if(parent >= 0 && p > hp[parent])
{
hp[child] = hp[parent];
child = parent;
parent = (parent-1)>>1;
}
else
break;
}
hp[child] = p;
}
vector<T> hp;
};
#endif //__HEAP_H__