优先队列可以用以O(NlogN)时间进行排序,基于该思想的算法叫做堆排序。它给出我们至今所见到的最佳的大O运行时间。
编码实现如下:
#include <iostream>
#include <vector>
using namespace std;
template <typename Comparable>
void heapsort( vector<Comparable> &a )
{
for ( int i = a.size() / 2 ; i >= 0 ; i-- ) //buildHeap
percDown( a,i,a.size() );
for ( int j = a.size() - 1 ; j > 0 ; j-- ){ //deleteMax
swap( a[0],a[j] );
percDown( a,0,j );
}
}
inline int leftChild( int i )
{
return 2 * i;
}
template <typename Comparable>
void percDown( vector<Comparable> &a,int i,int n ) //进行下滤
{
int child;
Comparable tmp;
for ( tmp = a[i] ; leftChild(i) < n ; i = child ){
child = leftChild( i );
if ( child != n - 1 && a[child] < a[ child + 1 ] )
child++;
if ( tmp < a[child] )
a[i] = a[child];
else
break;
}
a[i] = tmp;
}
int main()
{
cout << "请输入一些数据:" << endl;
vector<int> vec;
int temp;
while ( cin >> temp )
vec.push_back( temp );
heapsort( vec );
cout << "按降序排列过的数据如下:" << endl;
vector<int>::iterator iter = vec.begin();
while( iter != vec.end() )
cout << *iter++ << endl;
return 0;
}