#include <cstdlib>
#include <iostream>
#include <vector>
using namespace std;
void input(vector<int> &v)
{
cout<<"please enter the array:"<<endl;
int data;
while(cin>>data)
v.push_back(data);
}
void max_heap(vector<int> &v,int i)
{
if(i>v.size())
{
cout<<"overflow"<<endl;
exit(0);
}
int largest=i;
int heap_len=v.size()-1;
if((2*i<=heap_len) && (v[largest]<v[2*i]))
largest=2*i;
if((2*i+1<=heap_len) && (v[largest]<v[2*i+1]))
largest=2*i+1;
if(largest!=i)
{
int temp=v[i];
v[i]=v[largest];
v[largest]=temp;
max_heap(v,largest); //递归调用,调整以便满足最大堆的性质
}
}
void max_heap_effective(vector<int> &v,int i) //不采用递归,更加高效的方法
{
int heap_len=v.size();
while(i<heap_len)
{
int largest=i;
if((2*i<=heap_len) && (v[largest]<v[2*i]))
largest=2*i;
if((2*i+1<=heap_len) && (v[largest]<v[2*i+1]))
largest=2*i+1;
if(largest!=i)
{
int temp=v[i];
v[i]=v[largest];
v[largest]=temp;
i=largest;
}
else break;
}
}
void output(const vector<int> &v)
{
for(vector<int>::const_iterator iter=v.begin();iter!=v.end();++iter)
cout<<*iter<<" ";
cout<<endl;
}
int main(int argc, char *argv[])
{
vector<int> v;
input(v);
cin.clear();
cin.sync();
cout<<"the sort root: ";
int i;
cin>>i;
max_heap_effective(v,i);
output(v);
system("PAUSE");
return EXIT_SUCCESS;
}
6.2 保持堆的性质
最新推荐文章于 2024-02-05 23:58:17 发布