堆排序

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#define MAX_SIZE 20000

#define PARENT(i) (i/2)
#define RIGHT(i) (i*2 + 1)
#define LEFT(i) (i*2)
#define EXCHANGE(a,b,t) do{t=a;a=b;b=t;}while(0)

// 生成不重复的随机数序列写入文件
void gen_test_data(uint32_t cnt)
{
    if( cnt >= MAX_SIZE){printf("cnt too largr\n");return;}
    uint32_t i = 0;
    char buf[MAX_SIZE];
    for(;i < cnt;++i){buf[i] = 1;}
    uint32_t n = 0;
    char file_name[256];
    snprintf(file_name,256,"test_data_%d.txt",cnt);
    FILE *fp = fopen(file_name,"w");
    if(NULL == fp){printf("open %s error!\n",file_name);return;}
    while(n < cnt)
    {
        int32_t nRand = rand() % cnt;
        while(buf[nRand] == 0)nRand = (nRand + 1)%cnt;
        buf[nRand] = 0;
        fprintf(fp,"%d ",nRand);
        ++n;
    }
    fclose(fp);
}

// 读取文件
void read_data(int32_t arr[],const uint32_t size,uint32_t *cnt,const int32_t data_cnt)
{
    FILE *fp = NULL;
    char file_name[256];
    if(data_cnt > size){printf("data_cnt too largr\n");return;}
    snprintf(file_name,256,"test_data_%d.txt",data_cnt);
    fp = fopen(file_name,"r");
    if(NULL == fp){printf("open %s error!\n",file_name);return;}
    while(!feof(fp) && *cnt < size)
    {
        fscanf(fp,"%d ",&arr[*cnt]);
        (*cnt)++;
    }
    fclose(fp);
}

void max_heapify(int32_t arr[],const uint32_t size,uint32_t i)
{
    int32_t left = LEFT(i),right = RIGHT(i),largest = 0,tmp = 0;
    if(left<size && arr[left] > arr[i])largest = left;
    else largest = i;
    if(right<size && arr[right] > arr[largest])largest = right;
    if(largest != i)
    {
        EXCHANGE(arr[i],arr[largest],tmp);
        max_heapify(arr,size,largest);
    }
}

void heap_sort(int32_t arr[], uint32_t size)
{
    int32_t i = size / 2,tmp = 0;
    while(i>=0)max_heapify(arr,size,i--);
    for (i = size - 1; i > 0; --i)
    {
        EXCHANGE(arr[0], arr[i], tmp);
        --size;
        max_heapify(arr, size, 0);
    }
}

void dump1(int32_t arr[],const uint32_t cnt)
{
    uint32_t i = 0;
    for(;i < cnt;++i)
    {
        printf("%4d ",arr[i]);
    }
    printf("\n");
}



void dump2(int32_t arr[],const uint32_t start,const int32_t end)
{
    uint32_t i = start;
    for(;i < end;++i)
    {
        printf("%4d ",arr[i]);
    }
    printf("\n");
}

int32_t main(int32_t argc, char *argv[])
{
    uint32_t data_cnt = 10000;
    int32_t arr[MAX_SIZE];
    uint32_t cnt = 0;
    gen_test_data(data_cnt);
    read_data(arr, MAX_SIZE, &cnt, data_cnt);
    heap_sort(arr,cnt);
    dump1(arr, data_cnt);
    return 0;
}

 

posted @ 2016-06-26 21:56  你好阿汤哥  Views(195)  Comments(0Edit  收藏  举报