归并排序

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#define MAX_SIZE 20000
// 生成不重复的随机数序列写入文件
void gen_test_data(uint32_t cnt)
{
    if( cnt >= MAX_SIZE){printf("cnt too largr
");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!
",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
");return;}
    snprintf(file_name,256,"test_data_%d.txt",data_cnt);
    fp = fopen(file_name,"r");
    if(NULL == fp){printf("open %s error!
",file_name);return;}
    while(!feof(fp) && *cnt < size)
    {
        fscanf(fp,"%d ",&arr[*cnt]);
        (*cnt)++;
    }
    fclose(fp);
}

void merge(int32_t arr[], int32_t p, int32_t q, int32_t r,int32_t temp[],const int32_t temp_size)
{
    int32_t i = p, j = 0,k = 0;
    for (; i <= r && i < temp_size; ++i)
    {
        temp[i] = arr[i];
    }
    i = p; j = q + 1; k = p;
    while (i <= q && j <= r)
    {
        if (temp[i] >= temp[j]){arr[k++] = temp[i++];}
        else{arr[k++] = temp[j++];}
    }
    while (i <= q)arr[k++] = temp[i++];
    while (j <= r)arr[k++] = temp[j++];
}

void merge_sort(int32_t arr[], int32_t low, int32_t high, int32_t temp[], const int32_t temp_size)
{
    if (low < high)
    {
        int32_t mid = (low + high) / 2;
        merge_sort(arr, low, mid, temp, temp_size);
        merge_sort(arr, mid + 1, high, temp, temp_size);
        merge(arr, low, mid, high, temp, temp_size);
    }
}


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

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("
");
}

int32_t main(int32_t argc, char *argv[])
{
    int32_t data_cnt = 10000;
    int32_t arr[MAX_SIZE],temp[MAX_SIZE];
    uint32_t cnt = 0;
    gen_test_data(data_cnt);
    read_data(arr, MAX_SIZE, &cnt, data_cnt);
    merge_sort(arr, 0, data_cnt - 1, temp, MAX_SIZE);
    dump1(arr, data_cnt);
    getchar();
    return 0;
}
原文地址:https://www.cnblogs.com/tangxin-blog/p/5618423.html