您的位置:首页 > 其它

heap

2015-11-23 15:33 106 查看
//最大堆
#ifndef HEAP_H_
#define HEAP_H_

#include <vector>
using namespace std;
class Heap
{
private:
vector<int> heapData;

int heapSize;                               //堆中元素的个数
public:
Heap(int *arr,int n);                       //构造函数,n为数组元素个数
void percolateUp(int index, int value);      //从index(下标)上溯
void adjustHeap(int holeIndex, int value);        //调整以holeIndex为根的子树为堆
void pushHeap(int addValue);
void popHeap(int choose=0);                 //默认不删除,choose=1时,表示删除该元素,释放内存
void makeHeap();
void display();
void sort();                //排序
};

//构造函数
Heap::Heap(int *arr,int n)
{
heapSize = n;
for (int i = 0; i < n; i++) heapData.push_back(arr[i]);
makeHeap();
}

//上溯
void Heap::percolateUp(int index, int value)
{
int holeIndex = index;
int parent = (holeIndex - 1) / 2;
while (holeIndex >0 && heapData[parent]<value)    //**错过
{
heapData[holeIndex] = heapData[parent];
holeIndex = parent;
parent = (holeIndex - 1) / 2;
}
heapData[holeIndex] = value;
}

//调整以holeIndex为根的子树为堆,对应值为value,从上往下
void Heap::adjustHeap(int holeIndex, int value)
{
int topIndex = holeIndex;
int rightChild = topIndex * 2 + 2;
while (rightChild < heapSize)
{
if (heapData[rightChild - 1] > heapData[rightChild]) rightChild--;
heapData[holeIndex]=heapData[rightChild];
holeIndex = rightChild;
rightChild = 2 * rightChild + 2;          //找到新的洞节点的右孩子
}
if (rightChild == heapSize)
{
heapData[holeIndex] = heapData[rightChild - 1];
holeIndex = rightChild - 1;
}
heapData[holeIndex] = value;        //**错过,STL源码剖析里面没有这个
percolateUp(holeIndex,value);   //上溯调节
}

//往堆中加入一个元素
void Heap::pushHeap(int addValue)
{
heapData.push_back(addValue);
++heapSize;
adjustHeap(heapSize - 1, heapData[heapSize - 1]);
}

//往堆中取出一个元素
void Heap::popHeap(int choose)
{
int adjustValue = heapData[heapSize-1];
heapData[heapSize - 1] = heapData[0];     //将第一个放到堆尾;
--heapSize;
if (choose==1) heapData.pop_back();
adjustHeap(0, adjustValue);             //**错过,是从上往下
}

//生成堆
void Heap::makeHeap()
{
if (heapSize < 2) return;
int holeIndex = (heapSize - 2) / 2;  //最后一个节点的parent
while (1)
{
adjustHeap(holeIndex, heapData[holeIndex]);
if (holeIndex == 0) return;
--holeIndex;
}
}

//显示堆
void Heap::display()
{
for (int i = 0; i < heapSize; i++)
cout << heapData[i] << " ";
cout << endl;
}

//排序
void Heap::sort()
{
int temp = heapSize;
while (heapSize > 0)
popHeap();
heapSize = temp;
}
#endif


#include <iostream>
#include "Heap.h"

using namespace std;

int main()
{
int a[9] = {0,1,2,3,4,8,9,3,5};
Heap heap1(a, 9);
//heap1.pushHeap(7);
//heap1.display();
//heap1.popHeap();
heap1.sort();
heap1.display();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: