編程珠璣第1章的演算法實現

來源:互聯網
上載者:User

斷斷續續看了幾天,在實現幾個演算法後,總算把這個代碼寫出來了,測試耗時在10s 演算法真強大:)

#include <stdio.h>#include <stdlib.h>#include <string.h>#include <stdbool.h> #define MAX 1024*1024*1024typedef 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 9999999int 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);}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.