对排序的过程:
建立堆
执行n-1次DeleteHeap操作
堆排序与直接插入排序的区别:
直接选择排序中,为了从R[1..n]中选出关键字最小的记录,必须进行n-1次比较,然后在R[2..n]中选出关键字最小的记录,又需要做n-2次比较。事实上,后面的n-2次比较中,有许多比较可能在前面的n-1次比较中已经做过,但由于前一趟排序时未保留这些比较结果,所以后一趟排序时又重复执行了这些比较操作。堆排序可通过树形结构保存部分比较结果,可减少比较次数。
代码:
void
InsertHeap(
int
a[],
int
n,
int
data)
{
if (a == NULL)
return ;
a[n] = data;
int pos = n;
while (pos >= 0 )
{
int parent = (pos - 1 ) / 2 ;
if (parent >= 0 && a[parent] < a[pos])
{
Swap(a[parent], a[pos]);
pos = parent;
}
else
break ;
}
}
void BuildHeap( int a[], int n)
{
for ( int i = 1 ; i < n; ++ i)
InsertHeap(a, i, a[i]);
}
int DeleteHeap( int a[], int n)
{
int r = a[ 0 ];
int pos = 0 ;
while ( 2 * pos < n - 1 )
{
int child = 2 * pos + 1 ;
if (child < n - 1 && a[child + 1 ] > a[child])
++ child;
if (a[n - 1 ] < a[child])
{
a[pos] = a[child];
pos = child;
}
else
break ;
}
a[pos] = a[n - 1 ];
return r;
}
void HeapSort( int a[], int n)
{
if (a == NULL)
return ;
BuildHeap(a, n);
for ( int i = n - 1 ; i > 0 ; -- i)
{
a[i] = DeleteHeap(a, i + 1 );
}
}
{
if (a == NULL)
return ;
a[n] = data;
int pos = n;
while (pos >= 0 )
{
int parent = (pos - 1 ) / 2 ;
if (parent >= 0 && a[parent] < a[pos])
{
Swap(a[parent], a[pos]);
pos = parent;
}
else
break ;
}
}
void BuildHeap( int a[], int n)
{
for ( int i = 1 ; i < n; ++ i)
InsertHeap(a, i, a[i]);
}
int DeleteHeap( int a[], int n)
{
int r = a[ 0 ];
int pos = 0 ;
while ( 2 * pos < n - 1 )
{
int child = 2 * pos + 1 ;
if (child < n - 1 && a[child + 1 ] > a[child])
++ child;
if (a[n - 1 ] < a[child])
{
a[pos] = a[child];
pos = child;
}
else
break ;
}
a[pos] = a[n - 1 ];
return r;
}
void HeapSort( int a[], int n)
{
if (a == NULL)
return ;
BuildHeap(a, n);
for ( int i = n - 1 ; i > 0 ; -- i)
{
a[i] = DeleteHeap(a, i + 1 );
}
}