超大文件排序 ----C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

int main() //创建文件数据: 不大于256的随机整数
{
    srand((unsigned int)time(NULL));
    FILE *p = fopen("a.txt", "w");
    if (p)
    {
        int i;
        for (i = 0; i < 100000000; i++)
        {
            int seq = rand() % 256; // 任何整数与256的余数都不大于256
            char buf[100] = { 0 };
            if (i == 99999999)
            {
                sprintf(buf, "%d", seq);
            }
            else 
            {
                sprintf(buf, "%d\n", seq);
            }
            fputs(buf, p);
        }
    }
    fclose(p);
    return 0;
}

void swap(int *a, int *b) // 交换两个整数
{
    int tmp = *a;
    *a= *b;
    *b = tmp;
}

void bubble(int *a, int n) // 冒泡排序
{
    int i, j;
    for (i = 0; i < n; i++)
    {
        for (j = 1; j < n - i; j++)
        {
            if (a[j - 1] > a[j])
            {
                swap(&a[j - 1], a[j]);
            }
        }
    }
}


int main() // 数据量小时,适合采用冒泡排序:将数据全部读取出,进行排序
{
    FILE *p = fopen("a.txt", "r");
    if (p == NULL)
    {
        printf("error");
        return 0;
    }

    int array[100] = { 0 };
    int index = 0;
    while (!feof(p))
    {
        char buf[100] = { 0 };
        fgets(buf, sizeof(buf), p);
        array[index] = atoi(buf);
        index++;
    }
    fclose(p);

    //sort
    bubble(array, 100);

    p = fopen("a.txt", "w");
    int i;
    for (i = 0; i < 100; i++)
    {
        char buf[1024] = { 0 };
        sprintf(buf, "%d\n", array[i]);
        fputs(buf, p);
    }
    fclose(p);
    return 0;
}

int main() // 数据量大时,采用将数据映射到一个256长度的数组中,a[0]= 3代表0出现了3次,以此类推
{
    FILE *p = fopen("a.txt", "r");
    int array[256] = { 0 };
    while (!feof(p))
    {
        char buf[1024] = { 0 };
        fgets(buf, sizeof(buf), p);
        int a = atoi(buf);
        array[a]++;
    }
    fclose(p);

    p = fopen("a.txt", "w");
    int i, j;
    for (i = 0; i < 256; i++)
    {
        for (j = 0; j < array[i]; j++)
        {
            char buf[100] = { 0 };
            sprintf(buf, "%d\n", i);
            fputs(buf, p);
        }
    }
    fclose(p);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/miracle_8/article/details/80803948