堆排序

#include<stdio.h>

int left(int i) //返回做儿子下标
{
    return (i<<1)+1;
}

int right(int i) //返回右儿子下标
{
    return (i<<1)+2;
}

void maxheapify(int *A,int heapsize,int i) //维持最大堆性质
{
    int largest;
    int leftIdx = left(i);
    if(leftIdx<heapsize && A[i]<A[leftIdx])
    {
        largest = leftIdx;
    }
    else
    {
        largest = i;
    }
    int rightIdx = right(i);
    if(rightIdx<heapsize && A[largest]<A[rightIdx])
    {
        largest = rightIdx;
    }
    if(largest != i)
    {
        int temp = A[i];
        A[i] = A[largest];
        A[largest] = temp;
        maxheapify(A,heapsize,largest);
    }
}

void buildheap(int *A,int len) //建堆
{
    if(len==1 || len==0)
    {
        return;
    }
    for(int i=len/2-1;i>=0;i--)
    {
        maxheapify(A,len,i);
    }
}

void heapsort(int *A,int len) //排序
{
    buildheap(A,len);
    for(int i=len-1;i>0;i--)
    {
        int temp = A[i];
        A[i] = A[0];
        A[0] = temp;
        maxheapify(A,i,0);
    }
}

int main()
{
    int buf[]={2,4,1,5,7,4,6,8,10};
    int len = sizeof(buf)/sizeof(int);
    heapsort(buf,len);
    for(int i=0;i<len-1;i++)
    {
        printf("%d ",buf[i]);
    }
    printf("%d\n",buf[len-1]);
    return 0;
}

 

posted @ 2014-08-22 16:40  米其林轮船  阅读(137)  评论(0编辑  收藏  举报