断断续续看了几天,在实现几个算法后,总算把这个代码写出来了,测试耗时在10s 算法真强大:)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define MAX 1024*1024*1024
typedef unsigned char BYTE;
/*enum bool {1,0};*/
int main()
{
char str[10] = "\0";
bool *j;
j = (bool *)malloc(MAX);
for(int i=0;i<MAX;i++) {
j[i] = 0;
}
int i=0;
FILE *fp, *out_fp;
fp = fopen("./input.txt", "r");
while (fgets(str, 10, fp) != NULL) {
i = atoi(str);
j[i] = 1;
}
out_fp = fopen("./output.txt", "w");
for(int i=0; i<MAX; i++) {
if(j[i]>0) {
fprintf(out_fp, "%d\n", i);
}
}
fclose(fp);
fclose(out_fp);
free(j);
exit(0);
}
编译需要用到C99,算法中在处理bit数组的时候发现老版C实现很头痛,也不知道用enum怎么处理,有时间再看看其他方式
gcc num_in_str.c -std=c99
time ./a.out
real 0m10.371s
user 0m9.333s
sys 0m0.944s
生成100万随机数据文件的程序
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <time.h>
#define START 1000000
#define END 9999999
int main()
{
FILE *fp = fopen("./input.txt", "w");
if (fp == NULL) {
printf("Can't open file input.txt");
exit(-1);
}
int i=0, j=0;
srand((int)time(0));
while(1) {
j = (unsigned int)(rand() %(END-START));
if (j < START || j > END) continue;
fprintf(fp, "%d\n", j);
i++;
if (i == (END-START)) break;
}
fclose(fp);
}