您的位置:首页 > 其它

HeapSort(堆排序)

2015-03-28 16:37 483 查看
#include<iostream>
using namespace std;
void exch( int* x, int* y )
{
int temp = *x;
*x =*y;
*y = temp;
}

void HeapSort( int* array, int n )//array[0]不存放元素
{
for( int i = (n-1)/2; i > 0; i-- )
{
if( array[2*i] > array[i] )
exch( &array[2*i], &array[i] );
if( array[2*i+1] > array[i] && (2*i+1) < n)
exch( &array[2*i+1], &array[i] );
}
}
void OutPut( int* array, int n )
{
for( int i = 1; i < n; i++ )
{
cout<<array[i]<<"  ";
}
cout<<endl;
}
int main()
{
const int N = 12;
int a
= {0,13,2,3,4,16,336,3,8,9,10,11};
int size = N;
OutPut( a, N);
while( size > 1 )
{
HeapSort( a, size );
exch( &a[1], &a[size-1] );
size--;
}
OutPut( a, N);
return 0;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  HeapSort