//通过makeHeap实现建堆
//pushHeap往堆中添加元素
//popHeap移除堆顶元素
#include<iostream>
#include<vector>
using namespace std;
//大根堆实现
void makeHeap(vector<int>&data)
{
int len = data.size()+1;
for (int i = len / 2; i >= 1; --i)
{
//找到最大值
int left = 2 * i;
int right = 2 * i + 1;
int maxPos = i;
if (left <= len)
{
if (data[maxPos] < data[left])
maxPos = left;
}
if (right <=len)
{
if (data[maxPos] < data[right])
maxPos = right;
}
//相下调整元素
if (maxPos != i)
{
int temp = data[i];
data[i] = data[maxPos];
int j = maxPos;
while (j <= len)
{
int left = 2 * j;
int right = 2 * j + 1;
int maxPos = j;
//1左右还在均存在
if (left <= len&&right<=len)
{
if (temp >= data[left] && temp >= data[right])
{
data[j] = temp;
break;
}
else if (data[left] > temp&&data[left] >= data[right])
{
data[j] = data[left];
j = left;
continue;
}
else
{
data[j] = data[right];
j = right;
continue;
}
}
//2左还在存在
else if (left<= len)
{
if (data[left] > temp)
{
data[j] = data[left];
j = left;
continue;
}
else{
data[j] = temp;
break;
}
}
//3 无还在节点
else
{
data[j] = temp;
break;
}
}
}
}
}
//往堆里添加元素
void pushHeap(vector<int>&data)
{
int len = data.size();
int temp = data[len-1];
int i = (len-1) / 2;
int pos = len-1;
while (true)
{
if (temp > data[i])
{
data[pos]= data[i];
pos = i;
i = i / 2;
if (i == 0)
{
data[i + 1] = temp;
break;
}
}
else
{
data[i] = temp;
break;
}
}
}
//删除堆里面的元素
void popHeap(vector<int>&data,int len)
{
if (len<= 1)
return;
swap(data[len],data[1]);
int i = 1;
int temp = data[1];
while (i <= len-1)
{
int left = 2 * i ;
int right = 2 * i + 1;
//不断相下移动元素
if (left <= len-1 && right <= len-1 )
{
if (temp >= data[left] && temp >= data[right])
{
data[i] = temp;
break;
}
else if (data[left] > temp&&data[left] >= data[right])
{
data[i] = data[left];
i = left;
}
else if (data[right] > temp&&data[right] >= data[left])
{
data[i] = data[right];
i = right;
}
}
else if (left <= len-1 )
{
if (temp >= data[left])
{
data[i] = temp;
break;
}
else
{
data[i] = data[left];
i = left;
}
}
else
{
data[i] = temp;
break;
}
}
}
int main()
{
vector<int> data = { 0, 3, 4, 1, 5, 56, 1 };
makeHeap(data);
for (auto i : data)
cout << i << " ";
cout << endl;
//插入元素
data.push_back(100);
pushHeap(data);
for (auto i : data)
cout << i << " ";
cout << endl;
//堆排序实现
for (int i = data.size() - 1; i >= 1; --i)
popHeap(data,i);
for (auto i : data)
cout << i << " ";
cout << endl;
system("pause");
}