堆排序

 C代码:

#include <stdio.h>

void printArray(int a[], int len)
{
    for(int i=0; i<len; ++i)
    {
        if(0==i)
            printf("[%d,",a[i]);
        else if(i < len-1)
            printf("%d,",a[i]);
        else
            printf("%d]\n",a[i]);
    }
}

//将一个整型数组中的元素调整为大根堆
void HeadAdjust(int data[], int s, int m)
{
    int tmp, j;
    tmp = data[s];
    for(j=2*s+1; j<=m; j=j*2+1){
        if(j<m && data[j] < data[j+1])
            ++j;
        if( tmp >= data[j] )
            break;
        data[s] = data[j];
        s = j;
    }
    data[s] = tmp;
}

void HeadSort(int data[], int n)
{
    int i, tmp;
    //将data[0...n-1]调整为大根堆
    for(i=n/2-1; i>=0; --i)
    {
        HeadAdjust(data,i,n-1);
    }
    for(i=n-1; i>0; --i){
        tmp = data[0];
        data[0] = data[i];
        data[i] = tmp;
        HeadAdjust(data, 0, i-1);
    }
}

int main(){
    int a[] = {4,10,55,23,5,22,32,12,3,2};
    int len = sizeof(a)/sizeof(a[0]);
    printArray(a,len);
    //HeadAdjust(a,0,len-1);
    HeadSort(a, len);
    printArray(a,len);
    
    return 0;
}
View Code

 

 

**

posted @ 2022-12-19 12:17  htj10  阅读(12)  评论(0编辑  收藏  举报
TOP