堆排序_C实现

#include<stdio.h>

//向下调整 
void HeapAdjust(int A[], int low, int high){
    int i, temp = A[low];
    for(i = low * 2; i < high; i *= 2){
        if(i < high && A[i] < A[i+1])
            i++;
        if(A[i] <= temp)
            break;
        else{
            A[low] = A[i];
            low = i;
        }
    }
    A[low] = temp;
}

void HeapSort(int A[], int n){
    int i, temp;
    //建堆 
    for(i = n/2; i > 0; i--)
        HeapAdjust(A, i, n);
    //将最大值放至数组末端 
    for(i = n-1; i > 0; i--){
        temp = A[1];
        A[1] = A[i+1];
        A[i+1] = temp;
        HeapAdjust(A, 1 ,i);
    }
}

int main(){
    int A[16]={0,5,6,4,3,2,6,4,4,6,5,3,22,6,1,-23};
    HeapSort(A, 16);
    for(int i=1; i<=15; i++)
        printf("%d ", A[i]);
    return 0;
} 

猜你喜欢

转载自www.cnblogs.com/exciting/p/10061866.html