堆排序(6)

来源:互联网 发布:三星手机数据更新 编辑:程序博客网 时间:2024/06/06 10:40

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
原创粉丝点击