堆排序代码

对排序的过程:
 建立堆
 执行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 );
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值