您的位置:首页 > 编程语言 > C语言/C++

关于堆排序的c++算法

2010-01-04 08:13 417 查看
#include<iostream>
#include<cstdlib>
#include<deque>
using namespace std;
class proqueue
{
private:
deque<int> heap;
const int Min;
protected:
int left(int i){ return 2*i;}
int right(int i) { return 2*i+1;}
int parent(int i)
{
if( i == 0 || i == 1 )
{
cout<<" root error"<<endl;
exit(1);
}
return i/2;
}
void swap(int &m, int &n );
void Max_Heapify( int i);
public:
proqueue():Min(-100000){heap.push_back(0);}
int Heap_Maximum(){ return heap.at(1);}
int Heap_Extract_Max();
void Heap_Increase_Key(int i, int k);
void Max_Heap_Insert( int key);
void Heap_Show();
};

void proqueue::swap(int &m,int &n)
{
int tmp;
tmp=m;
m=n;
n=tmp;
}
void proqueue::Max_Heapify(int i)
{
int l=left(i);
int r=right(i);
int large;
if( l< heap.size() && heap.at(i)<heap.at(l))
large=l;
else
large=i;
if( r<heap.size() && heap.at(large)<heap.at(r))
large=r;
if( large != i )
{
swap( heap.at(i), heap.at(large));
Max_Heapify(large);
}
}

int proqueue::Heap_Extract_Max()
{
if( heap.size() < 1 )
{
cout<<"heap overflow"<<endl;
exit(1);
}
int max;
max=heap.at(1);
swap(heap.at(1),*(heap.end()-1));
heap.pop_back();
Max_Heapify(1);
return max;
}
void proqueue::Heap_Increase_Key( int i , int key)
{
if( heap.at(i) > key )
{
cout<<" new key is smaller than current key"<<endl;
exit(1);
}
heap.at(i)=key;
while( i>1 && heap.at(parent(i))<heap.at(i))
{
swap( heap.at(parent(i)),heap.at(i));
i=parent(i);
}
}

void proqueue::Max_Heap_Insert( int key)
{
heap.push_back(Min);
Heap_Increase_Key( heap.size()-1,key);
}
void proqueue::Heap_Show()
{
deque<int>::iterator it;
for( it=heap.begin()+1; it!=heap.end();it++)
cout<<*it<<" ";
cout<<endl;
}
int main()
{
proqueue p;
p.Max_Heap_Insert(15);
p.Max_Heap_Insert(13);
p.Max_Heap_Insert(9);
p.Max_Heap_Insert(5);
p.Max_Heap_Insert(12);
p.Max_Heap_Insert(8);
p.Max_Heap_Insert(7);
p.Max_Heap_Insert(4);
p.Max_Heap_Insert(0);
p.Max_Heap_Insert(6);
p.Max_Heap_Insert(2);
p.Max_Heap_Insert(1);
p.Heap_Show();
for( int i=0;i<12;i++)
{
cout<<p.Heap_Extract_Max()<<endl;
p.Heap_Show();
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ insert iterator 算法