编程珠玑第1章的算法实现

断断续续看了几天,在实现几个算法后,总算把这个代码写出来了,测试耗时在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);
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值