题目就不多说了,开篇第一个题目。

大意就是在给定内存1.25M以内,给最多包含n个正整数的文件数据排序的问题,n=10^7

1.

首先是生成一个该文件的问题,类似于洗牌算法得到一组随机不重复的数字。

/*
 * =====================================================================================
 *       Filename:  creatDataFile.c
 *    Description:  create random digital repeatable data
 *        Created:  03/17/2012 01:11:38 AM
 *       Compiler:  gcc
 *
 *         Author:  zhy (), [email protected]
 *        Company:  
 * =====================================================================================
 */

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

#define N 100/*00000*/
#define k 10/*00000*/

int main()
{
    unsigned int i = 0;
    srand(time(NULL));
    unsigned int *array = (unsigned int*)malloc(sizeof(unsigned int)*N);

    for ( i=0; i<N; ++i)
        array[i] = i;


    for ( i=0; i<k; ++i) {
        unsigned temp = array[i];
        unsigned randomIndex = rand()%(N-i)+i;
        array[i] = array[randomIndex];
        array[randomIndex] = temp;
    }

    FILE* fp;
    fp = fopen("data","w+");
    for ( i=0; i<k; ++i)
        fprintf(fp,"%d\n",array[i]);
    free(array);

    return 0;
}

代码里N即为数字可能的最大值,k为生成的个数。为了方便表示结果,N=100,k=10;

生成的data数据:

79
93
83
16
29
9
80
3
5
15

2.

接下来就是位图表示并排序。

/*
 * =====================================================================================
 *       Filename:  sortDataByBitMap.c
 *        Created:  03/20/2012 12:17:46 PM
 *       Compiler:  gcc
 *
 *         Author:  zhy (), [email protected]
 *        Company:  
 * =====================================================================================
 */

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

#define N 100/*00000*/
#define k 10/*00000*/

#define BITSPERWORD 32

int main()
{
    int array[N/BITSPERWORD+1];
    memset(array,0,sizeof(array));

    FILE* fp = fopen("data","r");
    unsigned int ui,i=0;
    for( i=0; i<k; ++i) {
        fscanf(fp,"%d",&ui);
        if ((array[ui/BITSPERWORD]>>(ui%BITSPERWORD) & 1) == 1)
            printf("digits repeated!?\n");
        else
            array[ui/BITSPERWORD] |= 1<<ui%BITSPERWORD;
    }
    fclose(fp);

    fp = fopen("sortdata","w");
    int j = 0;
    for ( i=0; i<N; ++i)
        if ((array[i/BITSPERWORD]>>i%BITSPERWORD & 1)==1) {
            fprintf(fp,"%d\n",i);
            ++j;
        }
    fclose(fp);

    return 0;
}

注意N,k与前一个要一致。

sortData内容:

3
5
9
15
16
29
79
80
83
93