線性建堆法與堆排序

魚7s later 재생發表於2020-11-30
#include <stdio.h>
#include <time.h>
#include <stdlib.h>

#define swap(a,b) {\
    __typeof(a) temp = a;\
    a = b; b = temp;\
}

void update(int num[],int begin,int end){
    int cur = begin,max = begin;
    if(cur * 2 <= end && num[max] < num[cur*2]) max = cur * 2;
    if(cur * 2+1 <= end && num[max] < num[cur*2+1]) max = cur*2+1;

    while(max <= end && num[max] > num[cur]){
        swap(num[cur],num[max]);
        cur = max;
        if(cur * 2 <= end && num[max] < num[cur*2]) max = cur*2;
        if(cur * 2+1 <= end && num[max] < num[cur*2+1]) max = cur*2+1;
    }
}

void sort(int num[],int size){
    if(num == NULL) return ;
    --num;
    
   for(int i = size/2; i > 0; --i){
        update(num,i,size);
   }
   
   for(int i = size; i > 1; --i){
       swap(num[i],num[1]);
       update(num,1,i-1);
   }
}

int main(){
    #define N 10
    int num[N];
    srand(time(0));

    for(int i=0; i<N; ++i) num[i] = rand() % 100;
    for(int i=0; i<N; ++i) printf("%d ",num[i]);
    printf("\n");
    sort(num,N);
    for(int i=0; i<N; ++i) printf("%d ",num[i]);
    printf("\n");
    #undef N
    return 0;
}

相關文章