堆排序(6)

1.理论参见:http://blog.csdn.net/genios/article/details/8157031

2.c代码:

/*************************************************************************
	> File Name: headSort.c
	> Author: NULL
	> Mail: 574889524@qq.com
	> Created Time: Mon 13 Oct 2014 08:46:11 PM CST
 ************************************************************************/

#include<stdio.h>
#define ARRSIZE 10
/*************************************************/
void ExChangeInt(int *a,int *b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}

int Leaf(int i)
{
    return 2*i+1;
}

int Right(int i)
{
    return 2*i+2;
}
void PrintArr(int A[],int iLarg)
{
    int i;
    for(i = 0; i < iLarg;++i)
        printf("%d ",A[i]);
    printf("\n");

}
/***********************************************/
static int giHeapSize = ARRSIZE - 1;;
void MaxHeapIfy(int *A,int i)
{
    int iLargest;
    int iL = Leaf(i);
    int iR = Right(i);
    
    if((iL<=giHeapSize) && (A[iL] > A[i]))
        iLargest = iL;
    else
        iLargest = i;

    if((iR <=giHeapSize) && (A[iR] > A[iLargest]))
        iLargest = iR;

    if(iLargest != i){
        ExChangeInt(&A[i],&A[iLargest]);
        MaxHeapIfy(A,iLargest);
    }
}

void BuildMaxHeap(int *A)
{
    int i;
    for(i =(ARRSIZE-1)/2;i>=0;--i)
        MaxHeapIfy(A,i);
}

void HeapSort(int *A)
{
    int i,iSize = ARRSIZE-1;
    BuildMaxHeap(A);
    for(i = iSize;i>=1;--i){
        ExChangeInt(&A[0],&A[i]);
        giHeapSize--;
        MaxHeapIfy(A,0);
    }
}


/***********************************************/

int main()
{
    int i,A[ARRSIZE] = {4,1,2,3,16,9,10,14,8,7};
    
    HeapSort(A);
    PrintArr(A,ARRSIZE); 
    
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

byd yes

你的鼓励是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值