給10^7個數據量的磁盤文件排序


前奏

    經過幾天的痛苦沉思,最終決定,把原程序員面試題狂想曲系列正式更名爲程序員編程藝術系列,同時,狂想曲創作組更名爲編程藝術室。之所以要改名,我們考慮到三點:1、爲面試服務不能成爲我們最終或最主要的目的,2、我更願把解答一道道面試題,ACM題等各類程序設計題目的過程,當做一種藝術來看待,3、藝術的提煉本身是一個非常非常艱難的過程,但我們樂意接受這個挑戰。

    ok,如果任何人對本編程藝術系列有任何意見,或發現了本編程藝術系列任何問題,漏洞,bug,歡迎隨時提出,我們將虛心接受並感激不盡,以爲他人創造更好的價值,更好的服務。

 

第一節、如何給磁盤文件排序
問題描述:
輸入:給定一個文件,裏面最多含有n個不重複的正整數(也就是說可能含有少於n個不重複正整數),且其中每個數都小於等於n,n=10^7。
輸出:得到按從小到大升序排列的包含所有輸入的整數的列表。
條件:最多有大約1MB的內存空間可用,但磁盤空間足夠。且要求運行時間在5分鐘以下,10秒爲最佳結果。

分析:下面咱們來一步一步的解決這個問題,
    1、歸併排序。你可能會想到把磁盤文件進行歸併排序,但題目要求你只有1MB的內存空間可用,所以,歸併排序這個方法不行。
    2、位圖方案。熟悉位圖的朋友可能會想到用位圖來表示這個文件集合。例如正如編程珠璣一書上所述,用一個20位長的字符串來表示一個所有元素都小於20的簡單的非負整數集合,邊框用如下字符串來表示集合{1,2,3,5,8,13}:

0 1 1 1 0 1 0 0 1 0 0 0 0 1 0 0 0 0 0 0

上述集合中各數對應的位置則置1,沒有對應的數的位置則置0。

    參考編程珠璣一書上的位圖方案,針對我們的10^7個數據量的磁盤文件排序問題,我們可以這麼考慮,由於每個7位十進制整數表示一個小於1000萬的整數。我們可以使用一個具有1000萬個位的字符串來表示這個文件,其中,當且僅當整數i在文件中存在時,第i位爲1。採取這個位圖的方案是因爲我們面對的這個問題的特殊性:1、輸入數據限制在相對較小的範圍內,2、數據沒有重複,3、其中的每條記錄都是單一的整數,沒有任何其它與之關聯的數據。
    所以,此問題用位圖的方案分爲以下三步進行解決:

  • 第一步,將所有的位都置爲0,從而將集合初始化爲空。
  • 第二步,通過讀入文件中的每個整數來建立集合,將每個對應的位都置爲1。
  • 第三步,檢驗每一位,如果該位爲1,就輸出對應的整數。

    經過以上三步後,產生有序的輸出文件。令n爲位圖向量中的位數(本例中爲1000 0000),程序可以用僞代碼表示如下:

  1. //磁盤文件排序位圖方案的僞代碼  
  2. //copyright@ Jon Bentley  
  3. //July、updated,2011.05.29。  
  4.   
  5. //第一步,將所有的位都初始化爲0  
  6. for i ={0,....n}      
  7.    bit[i]=0;  
  8. //第二步,通過讀入文件中的每個整數來建立集合,將每個對應的位都置爲1。  
  9. for each i in the input file     
  10.    bit[i]=1;  
  11.   
  12. //第三步,檢驗每一位,如果該位爲1,就輸出對應的整數。  
  13. for i={0...n}      
  14.   if bit[i]==1        
  15.     write i on the output file  

    上面只是爲了簡單介紹下位圖算法的僞代碼之抽象級描述。顯然,咱們面對的問題,可不是這麼簡單。下面,我們試着針對這個要分兩趟給磁盤文件排序的具體問題編寫完整代碼,如下。

  1. //copyright@ yansha  
  2. //July、2010.05.30。  
  3. //位圖方案解決10^7個數據量的文件的排序問題  
  4. //如果有重複的數據,那麼只能顯示其中一個 其他的將被忽略  
  5. #include <iostream>  
  6. #include <bitset>  
  7. #include <assert.h>  
  8. #include <time.h>  
  9. using namespace std;  
  10.   
  11. const int max_each_scan = 5000000;  
  12.   
  13. int main()  
  14. {  
  15.     clock_t begin = clock();  
  16.     bitset<max_each_scan> bit_map;  
  17.     bit_map.reset();  
  18.       
  19.     // open the file with the unsorted data  
  20.     FILE *fp_unsort_file = fopen("data.txt""r");  
  21.     assert(fp_unsort_file);  
  22.     int num;  
  23.   
  24.     // the first time scan to sort the data between 0 - 4999999  
  25.     while (fscanf(fp_unsort_file, "%d ", &num) != EOF)  
  26.     {  
  27.         if (num < max_each_scan)  
  28.             bit_map.set(num, 1);  
  29.     }  
  30.       
  31.     FILE *fp_sort_file = fopen("sort.txt""w");  
  32.     assert(fp_sort_file);  
  33.     int i;  
  34.       
  35.     // write the sorted data into file  
  36.     for (i = 0; i < max_each_scan; i++)  
  37.     {  
  38.         if (bit_map[i] == 1)  
  39.             fprintf(fp_sort_file, "%d ", i);  
  40.     }  
  41.       
  42.     // the second time scan to sort the data between 5000000 - 9999999  
  43.     int result = fseek(fp_unsort_file, 0, SEEK_SET);  
  44.     if (result)  
  45.         cout << "fseek failed!" << endl;  
  46.     else  
  47.     {  
  48.         bit_map.reset();  
  49.         while (fscanf(fp_unsort_file, "%d ", &num) != EOF)  
  50.         {  
  51.             if (num >= max_each_scan && num < 10000000)  
  52.             {  
  53.                 num -= max_each_scan;  
  54.                 bit_map.set(num, 1);  
  55.             }  
  56.         }  
  57.         for (i = 0; i < max_each_scan; i++)  
  58.         {  
  59.             if (bit_map[i] == 1)  
  60.                 fprintf(fp_sort_file, "%d ", i + max_each_scan);  
  61.         }  
  62.     }  
  63.       
  64.     clock_t end = clock();  
  65.     cout<<"用位圖的方法,耗時:"<<endl;  
  66.     cout << (end - begin) / CLK_TCK << "s" << endl;  
  67.     fclose(fp_sort_file);  
  68.     fclose(fp_unsort_file);  
  69.     return 0;  
  70. }  

 而後測試了一下上述程序的運行時間,採取位圖方案耗時14s,即14000ms:

本章中,生成大數據量(1000w)的程序如下,下文第二節的多路歸併算法的c++實現和第三節的磁盤文件排序的編程實現中,生成的1000w數據量也是用本程序產生的,且本章內生成的1000w數據量的數據文件統一命名爲“data.txt”。

  1. //purpose:  生成隨機的不重複的測試數據  
  2. //copyright@ 2011.04.19 yansha  
  3. //1000w數據量,要保證生成不重複的數據量,一般的程序沒有做到。  
  4. //但,本程序做到了。  
  5. //July、2010.05.30。  
  6. #include <iostream>  
  7. #include <time.h>  
  8. #include <assert.h>  
  9. using namespace std;  
  10.   
  11. const int size = 10000000;  
  12. int num[size];  
  13.   
  14. int main()  
  15. {  
  16.     int n;  
  17.     FILE *fp = fopen("data.txt""w");  
  18.     assert(fp);  
  19.   
  20.     for (n = 1; n <= size; n++)    
  21.         //之前此處寫成了n=0;n<size。導致下面有一段小程序的測試數據出現了0,特此訂正。  
  22.         num[n] = n;  
  23.     srand((unsigned)time(NULL));  
  24.     int i, j;  
  25.   
  26.     for (n = 0; n < size; n++)  
  27.     {  
  28.         i = (rand() * RAND_MAX + rand()) % 10000000;  
  29.         j = (rand() * RAND_MAX + rand()) % 10000000;  
  30.         swap(num[i], num[j]);  
  31.     }  
  32.   
  33.     for (n = 0; n < size; n++)  
  34.         fprintf(fp, "%d ", num[n]);  
  35.     fclose(fp);  
  36.     return 0;  
  37. }  

    不過很快,我們就將意識到,用此位圖方法,嚴格說來還是不太行,空間消耗10^7/8還是大於1M(1M=1024*1024空間,小於10^7/8)。
    既然如果用位圖方案的話,我們需要約1.25MB(若每條記錄是8位的正整數的話,則10000000/(1024*1024*8) ~= 1.2M)的空間,而現在只有1MB的可用存儲空間,那麼究竟該作何處理呢?

updated && correct:

   @yansha: 上述的位圖方案,共需要掃描輸入數據兩次,具體執行步驟如下:

  • 第一次,只處理1—4999999之間的數據,這些數都是小於5000000的,對這些數進行位圖排序,只需要約5000000/8=625000Byte,也就是0.625M,排序後輸出。
  • 第二次,掃描輸入文件時,只處理4999999-10000000的數據項,也只需要0.625M(可以使用第一次處理申請的內存)。
    因此,總共也只需要0.625M

位圖的的方法有必要強調一下,就是位圖的適用範圍爲針對不重複的數據進行排序,若數據有重複,位圖方案就不適用了。

    3、多路歸併。誠然,在面對本題時,還可以通過計算分析出可以用如2的位圖法解決,但實際上,很多的時候,我們都面臨着這樣一個問題,文件太大,無法一次性放入內存中計算處理,那這個時候咋辦呢?分而治之,大而化小,也就是把整個大文件分爲若干大小的幾塊,然後分別對每一塊進行排序,最後完成整個過程的排序。k趟算法可以在kn的時間開銷內和n/k的空間開銷內完成對最多n個小於n的無重複正整數的排序。

    比如可分爲2塊(k=2,1趟反正佔用的內存只有1.25/2M),1~4999999,和5000000~9999999。先遍歷一趟,首先排序處理1~4999999之間的整數(用5000000/8=625000個字的存儲空間來排序0~4999999之間的整數),然後再第二趟,對5000001~1000000之間的整數進行排序處理。在稍後的第二節、第三節、第四節,我們將詳細闡述並實現這種多路歸併排序磁盤文件的方案。
    4、讀者思考。經過上述思路3的方案之後,現在有兩個局部有序的數組了,那麼要得到一個完整的排序的數組,接下來改怎麼做呢?或者說,如果是K路歸併,得到k個排序的子數組,把他們合併成一個完整的排序數組,如何優化?或者,我再問你一個問題,K路歸併用敗者樹 和 勝者樹 效率有什麼差別?這些問題,請讀者思考。

 

第二節、多路歸併算法的c++實現

    本節咱們暫拋開咱們的問題,闡述下有關多路歸併算法的c++實現問題。在稍後的第三節,咱們再來具體針對咱們的磁盤文件排序問題闡述與實現。

    在瞭解多路歸併算法之前,你還得了解歸併排序的過程,因爲下面的多路歸併算法就是基於這個流程的。其實歸併排序就是2路歸併,而多路歸併算法就是把2換成了k,即多(k)路歸併。下面,舉個例子來說明下此歸併排序算法,如下圖所示,我們對數組8 3 2 6 7 1 5 4進行歸併排序:

    歸併排序算法簡要介紹:
一、思路描述:
    設兩個有序的子文件(相當於輸入堆)放在同一向量中相鄰的位置上:R[low..m],R[m+1..high],先將它們合併到一個局部的暫存向量R1(相當於輸出堆)中,待合併完成後將R1複製回R[low..high]中。
     
    二路歸併排序的過程是:
    (1)把無序表中的每一個元素都看作是一個有序表,則有n個有序子表;
    (2)把n個有序子表按相鄰位置分成若干對(若n爲奇數,則最後一個子表單獨作爲一組),每對中的兩個子表進行歸併,歸併後子表數減少一半;
    (3)反覆進行這一過程,直到歸併爲一個有序表爲止。

    二路歸併排序過程的核心操作是將一維數組中相鄰的兩個有序表歸併爲一個有序表。

二、分類:
    歸併排序可分爲:多路歸併排序、兩路歸併排序 。
    若歸併的有序表有兩個,叫做二路歸併。一般地,若歸併的有序表有k個,則稱爲k路歸併。二路歸併最爲簡單和常用,既適用於內部排序,也適用於外部排序。本文着重討論外部排序下的多(K)路歸併算法。

三、算法分析: 
    1、穩定性:歸併排序是一種穩定的排序。
    2、存儲結構要求:可用順序存儲結構。也易於在鏈表上實現。
    3、時間複雜度: 對長度爲n的文件,需進行lgn趟二路歸併,每趟歸併的時間爲O(n),故其時間複雜度無論是在最好情況下還是在最壞情況下均是O(nlgn)。。
    4、空間複雜度:需要一個輔助向量來暫存兩有序子文件歸併的結果,故其輔助空間複雜度爲O(n),顯然它不是就地排序。
       注意:若用單鏈表做存儲結構,很容易給出就地的歸併排序。
    
    總結:與快速排序相比,歸併排序的最大特點是,它是一種穩定的排序方法。歸併排序一般多用於外排序。但它在內排方面也佔有重要地位,因爲它是基於比較的時間複雜度爲O(N*Log(N))的排序算法中唯一穩定的排序,所以在需要穩定內排序時通常會選擇歸併排序。歸併排序不要求對序列可以很快地進行隨機訪問,所以在鏈表排序的實現中很受歡迎。

    好的,介紹完了歸併排序後,回到咱們的問題。由第一節,我們已經知道,當數據量大到不適合在內存中排序時,可以利用多路歸併算法對磁盤文件進行排序。

    我們以一個包含很多個整數的大文件爲例,來說明多路歸併的外排序算法基本思想。假設文件中整數個數爲N(N是億級的),整數之間用空格分開。首先分多次從該文件中讀取M(十萬級)個整數,每次將M個整數在內存中使用快速排序之後存入臨時文件,然後使用多路歸併將各個臨時文件中的數據再次整體排好序後存入輸出文件。顯然,該排序算法需要對每個整數做2次磁盤讀和2次磁盤寫。以下是本程序的流程圖:

    本程序是基於以上思想對包含大量整數文件的從小到大排序的一個簡單實現,這裏沒有使用內存緩衝區,在歸併時簡單使用一個數組來存儲每個臨時文件的第一個元素。下面是多路歸併排序算法的c++實現代碼(在第四節,將給出多路歸併算法的c實現): 

  1. //copyright@ 純淨的天空 && yansha    
  2. //5、July,updated,2010.05.28。    
  3. #include <iostream>    
  4. #include <ctime>    
  5. #include <fstream>    
  6. //#include "ExternSort.h"using namespace std;    
  7. //使用多路歸併進行外排序的類    
  8. //ExternSort.h    
  9. /** 大數據量的排序* 多路歸併排序* 以千萬級整數從小到大排序爲例* 一個比較簡單的例子,沒有建立內存緩衝區*/    
  10. #ifndef EXTERN_SORT_H    
  11. #define EXTERN_SORT_H    
  12.   
  13. #include <cassert>class ExternSort    
  14. {    
  15. public:    
  16.     void sort()    
  17.     {    
  18.         time_t start = time(NULL);    
  19.         //將文件內容分塊在內存中排序,並分別寫入臨時文件      
  20.         int file_count = memory_sort();    
  21.         //歸併臨時文件內容到輸出文件    
  22.         merge_sort(file_count);    
  23.         time_t end = time(NULL);printf("total time:%f/n", (end - start) * 1000.0/ CLOCKS_PER_SEC);    
  24.     }    
  25.       
  26.     //input_file:輸入文件名    
  27.     //out_file:輸出文件名    
  28.     //count: 每次在內存中排序的整數個數    
  29.     ExternSort(const char *input_file, const char * out_file, int count)    
  30.     {    
  31.         m_count = count;    
  32.         m_in_file = new char[strlen(input_file) + 1];    
  33.         strcpy(m_in_file, input_file);    
  34.         m_out_file = new char[strlen(out_file) + 1];    
  35.         strcpy(m_out_file, out_file);    
  36.     }    
  37.     virtual ~ExternSort()    
  38.     {    
  39.         delete [] m_in_file;    
  40.         delete [] m_out_file;    
  41.     }    
  42. private:    
  43.     int m_count;     
  44.     //數組長度char *m_in_file;      
  45.     //輸入文件的路徑    
  46.     char *m_out_file;     
  47.     //輸出文件的路徑    
  48. protected:    
  49.     int read_data(FILE* f, int a[], int n)    
  50.     {    
  51.         int i = 0;    
  52.         while(i < n && (fscanf(f, "%d", &a[i]) != EOF))     
  53.             i++;    
  54.         printf("read:%d integer/n", i);    
  55.         return i;    
  56.     }    
  57.     void write_data(FILE* f, int a[], int n)    
  58.     {    
  59.         for(int i = 0; i < n; ++i)    
  60.             fprintf(f, "%d ", a[i]);    
  61.     }    
  62.     char* temp_filename(int index)    
  63.     {    
  64.         char *tempfile = new char[100];    
  65.         sprintf(tempfile, "temp%d.txt", index);    
  66.         return tempfile;    
  67.     }    
  68.     static int cmp_int(const void *a, const void *b)    
  69.     {    
  70.         return *(int*)a - *(int*)b;    
  71.     }    
  72.   
  73.     int memory_sort()    
  74.     {    
  75.         FILE* fin = fopen(m_in_file, "rt");    
  76.         int n = 0, file_count = 0;int *array = new int[m_count];    
  77.           
  78.         //每讀入m_count個整數就在內存中做一次排序,並寫入臨時文件    
  79.         while(( n = read_data(fin, array, m_count)) > 0)    
  80.         {    
  81.             qsort(array, n, sizeof(int), cmp_int);   //這裏,調用了庫函數阿,在第四節的c實現裏,不再調qsort。      
  82.             char *fileName = temp_filename(file_count++);    
  83.             FILE *tempFile = fopen(fileName, "w");    
  84.             free(fileName);    
  85.             write_data(tempFile, array, n);    
  86.             fclose(tempFile);    
  87.         }    
  88.         delete [] array;    
  89.         fclose(fin);    
  90.         return file_count;    
  91.     }    
  92.       
  93.     void merge_sort(int file_count)    
  94.     {    
  95.         if(file_count <= 0)     
  96.             return;    
  97.         //歸併臨時文件FILE *fout = fopen(m_out_file, "wt");    
  98.         FILE* *farray = new FILE*[file_count];    
  99.         int i;    
  100.         for(i = 0; i < file_count; ++i)    
  101.         {    
  102.             char* fileName = temp_filename(i);    
  103.             farray[i] = fopen(fileName, "rt");    
  104.             free(fileName);    
  105.         }    
  106.         int *data = new int[file_count];    
  107.         //存儲每個文件當前的一個數字    
  108.         bool *hasNext = new bool[file_count];    
  109.         //標記文件是否讀完    
  110.         memset(data, 0, sizeof(int) * file_count);    
  111.         memset(hasNext, 1, sizeof(bool) * file_count);    
  112.         for(i = 0; i < file_count; ++i)    
  113.         {    
  114.             if(fscanf(farray[i], "%d", &data[i]) == EOF)    
  115.                 //讀每個文件的第一個數到data數組    
  116.                 hasNext[i] = false;    
  117.         }    
  118.   
  119.         while(true)    
  120.         {    
  121.             //求data中可用的最小的數字,並記錄對應文件的索引    
  122.             int min = data[0];    
  123.             int j = 0;    
  124.             while (j < file_count && !hasNext[j])    
  125.                 j++;    
  126.             if (j >= file_count)      
  127.                 //沒有可取的數字,終止歸併    
  128.                 break;    
  129.             for(i = j + 1; i < file_count; ++i)    
  130.             {    
  131.                 if(hasNext[i] && min > data[i])    
  132.                 {    
  133.                     min = data[i];    
  134.                     j = i;    
  135.                 }    
  136.             }    
  137.             if(fscanf(farray[j], "%d", &data[j]) == EOF)     
  138.                 //讀取文件的下一個元素    
  139.                 hasNext[j] = false;    
  140.             fprintf(fout, "%d ", min);    
  141.         }    
  142.   
  143.         delete [] hasNext;    
  144.         delete [] data;    
  145.         for(i = 0; i < file_count; ++i)    
  146.         {    
  147.             fclose(farray[i]);    
  148.         }  
  149.         delete [] farray;    
  150.         fclose(fout);    
  151.     }    
  152. };    
  153. #endif    
  154.   
  155. //測試主函數文件    
  156. /** 大文件排序* 數據不能一次性全部裝入內存* 排序文件裏有多個整數,整數之間用空格隔開*/    
  157.   
  158. const unsigned int count = 10000000;     
  159. // 文件裏數據的行數const unsigned int number_to_sort = 1000000;     
  160. //在內存中一次排序的數量    
  161. const char *unsort_file = "unsort_data.txt";     
  162. //原始未排序的文件名    
  163. const char *sort_file = "sort_data.txt";     
  164. //已排序的文件名    
  165. void init_data(unsigned int num);     
  166.   
  167. //隨機生成數據文件    
  168.   
  169. int main(int argc, char* *argv)    
  170. {    
  171.     srand(time(NULL));    
  172.     init_data(count);    
  173.     ExternSort extSort(unsort_file, sort_file, number_to_sort);    
  174.     extSort.sort();    
  175.     system("pause");    
  176.     return 0;    
  177. }    
  178.   
  179. void init_data(unsigned int num)    
  180. {    
  181.     FILE* f = fopen(unsort_file, "wt");    
  182.     for(int i = 0; i < num; ++i)    
  183.         fprintf(f, "%d ", rand());    
  184.     fclose(f);    
  185. }   

程序測試:讀者可以繼續用小文件小數據量進一步測試。

 

第三節、磁盤文件排序的編程實現

    ok,接下來,我們來編程實現上述磁盤文件排序的問題,本程序由兩部分構成:
1、內存排序
由於要求的可用內存爲1MB,那麼每次可以在內存中對250K的數據進行排序,然後將有序的數寫入硬盤。
那麼10M的數據需要循環40次,最終產生40個有序的文件。
2、歸併排序

  1. 將每個文件最開始的數讀入(由於有序,所以爲該文件最小數),存放在一個大小爲40的first_data數組中;
  2. 選擇first_data數組中最小的數min_data,及其對應的文件索引index;
  3. 將first_data數組中最小的數寫入文件result,然後更新數組first_data(根據index讀取該文件下一個數代替min_data);
  4. 判斷是否所有數據都讀取完畢,否則返回2。

所以,本程序按順序分兩步,第一步、Memory Sort,第二步、Merge Sort。程序的流程圖,如下圖所示(感謝F的繪製)。

然後,編寫的完整代碼如下:

  1. //copyright@ yansha  
  2. //July、updated,2011.05.28。  
  3. #include <iostream>  
  4. #include <string>  
  5. #include <algorithm>  
  6. #include <time.h>  
  7. using namespace std;  
  8.   
  9. int sort_num = 10000000;  
  10. int memory_size = 250000;    
  11.   
  12. //每次只對250k個小數據量進行排序  
  13. int read_data(FILE *fp, int *space)  
  14. {  
  15.     int index = 0;  
  16.     while (index < memory_size && fscanf(fp, "%d ", &space[index]) != EOF)  
  17.         index++;  
  18.     return index;  
  19. }  
  20.   
  21. void write_data(FILE *fp, int *space, int num)  
  22. {  
  23.     int index = 0;  
  24.     while (index < num)  
  25.     {  
  26.         fprintf(fp, "%d ", space[index]);  
  27.         index++;  
  28.     }  
  29. }  
  30.   
  31. // check the file pointer whether valid or not.  
  32. void check_fp(FILE *fp)  
  33. {  
  34.     if (fp == NULL)  
  35.     {  
  36.         cout << "The file pointer is invalid!" << endl;  
  37.         exit(1);  
  38.     }  
  39. }  
  40.   
  41. int compare(const void *first_num, const void *second_num)  
  42. {  
  43.     return *(int *)first_num - *(int *)second_num;  
  44. }  
  45.   
  46. string new_file_name(int n)  
  47. {  
  48.     char file_name[20];  
  49.     sprintf(file_name, "data%d.txt", n);  
  50.     return file_name;  
  51. }  
  52.   
  53. int memory_sort()  
  54. {  
  55.     // open the target file.  
  56.     FILE *fp_in_file = fopen("data.txt""r");  
  57.     check_fp(fp_in_file);  
  58.     int counter = 0;  
  59.     while (true)  
  60.     {  
  61.         // allocate space to store data read from file.  
  62.         int *space = new int[memory_size];  
  63.         int num = read_data(fp_in_file, space);  
  64.         // the memory sort have finished if not numbers any more.  
  65.         if (num == 0)  
  66.             break;  
  67.   
  68.         // quick sort.  
  69.         qsort(space, num, sizeof(int), compare);  
  70.         // create a new auxiliary file name.  
  71.         string file_name = new_file_name(++counter);  
  72.         FILE *fp_aux_file = fopen(file_name.c_str(), "w");  
  73.         check_fp(fp_aux_file);  
  74.   
  75.         // write the orderly numbers into auxiliary file.  
  76.         write_data(fp_aux_file, space, num);  
  77.         fclose(fp_aux_file);  
  78.         delete []space;  
  79.     }  
  80.     fclose(fp_in_file);  
  81.   
  82.     // return the number of auxiliary files.  
  83.     return counter;  
  84. }  
  85.   
  86. void merge_sort(int file_num)  
  87. {  
  88.     if (file_num <= 0)  
  89.         return;  
  90.     // create a new file to store result.  
  91.     FILE *fp_out_file = fopen("result.txt""w");  
  92.     check_fp(fp_out_file);  
  93.   
  94.     // allocate a array to store the file pointer.  
  95.     FILE **fp_array = new FILE *[file_num];  
  96.     int i;  
  97.     for (i = 0; i < file_num; i++)  
  98.     {  
  99.         string file_name = new_file_name(i + 1);  
  100.         fp_array[i] = fopen(file_name.c_str(), "r");  
  101.         check_fp(fp_array[i]);  
  102.     }  
  103.   
  104.     int *first_data = new int[file_num];     
  105.     //new出個大小爲0.1億/250k數組,由指針first_data指示數組首地址  
  106.     bool *finish = new bool[file_num];  
  107.     memset(finish, falsesizeof(bool) * file_num);  
  108.   
  109.     // read the first number of every auxiliary file.  
  110.     for (i = 0; i < file_num; i++)  
  111.         fscanf(fp_array[i], "%d ", &first_data[i]);  
  112.     while (true)  
  113.     {  
  114.         int index = 0;  
  115.         while (index < file_num && finish[index])  
  116.             index++;  
  117.   
  118.         // the finish condition of the merge sort.  
  119.         if (index >= file_num)  
  120.             break;  
  121.         //主要的修改在上面兩行代碼,就是merge sort結束條件。  
  122.         //要保證所有文件都讀完,必須使得finish[0]...finish[40]都爲真  
  123.         //July、yansha,555,2011.05.29。  
  124.   
  125.         int min_data = first_data[index];  
  126.         // choose the relative minimum in the array of first_data.  
  127.         for (i = index + 1; i < file_num; i++)  
  128.         {  
  129.             if (min_data > first_data[i] && !finish[i])     
  130.                 //一旦發現比min_data更小的數據first_data[i]  
  131.             {  
  132.                 min_data = first_data[i];      
  133.                 //則置min_data<-first_data[i]index = i;                     
  134.                 //把下標i 賦給index。  
  135.             }  
  136.         }  
  137.   
  138.         // write the orderly result to file.  
  139.         fprintf(fp_out_file, "%d ", min_data);  
  140.         if (fscanf(fp_array[index], "%d ", &first_data[index]) == EOF)  
  141.             finish[index] = true;  
  142.     }  
  143.   
  144.     fclose(fp_out_file);  
  145.     delete []finish;  
  146.     delete []first_data;  
  147.     for (i = 0; i < file_num; i++)  
  148.         fclose(fp_array[i]);  
  149.     delete [] fp_array;  
  150. }  
  151.   
  152. int main()  
  153. {  
  154.     clock_t start_memory_sort = clock();  
  155.     int aux_file_num = memory_sort();  
  156.     clock_t end_memory_sort = clock();  
  157.     cout << "The time needs in memory sort: " << end_memory_sort - start_memory_sort << endl;  
  158.     clock_t start_merge_sort = clock();  
  159.     merge_sort(aux_file_num);  
  160.     clock_t end_merge_sort = clock();  
  161.     cout << "The time needs in merge sort: " << end_merge_sort - start_merge_sort << endl;  
  162.     system("pause");  
  163.     return 0;  
  164. }  

其中,生成數據文件data.txt的代碼在第一節已經給出。

程序測試

    1、咱們對1000W數據進行測試,打開半天沒看到數據,

    2、編譯運行上述程序後,data文件先被分成40個小文件data[1....40],然後程序再對這40個小文件進行歸併排序,排序結果最終生成在result文件中,自此result文件中便是由data文件的數據經排序後得到的數據。

    3、且,我們能看到,data[i],i=1...40的每個文件都是有序的,如下圖:

    4、最終的運行結果,如下,單位統一爲ms:

    由上觀之,我們發現,第一節的位圖方案的程序效率是最快的,約爲14s,而採用上述的多路歸併算法的程序運行時間約爲25s。時間主要浪費在讀寫磁盤IO上,且程序中用的庫函數qsort也耗費了不少時間。所以,總的來說,採取位圖方案是最佳方案。

小數據量測試:

    我們下面針對小數據量的文件再測試一次,針對20個小數據,每趟對4個數據進行排序,即5路歸併,程序的排序結果如下圖所示。

運行時間:

0ms,可以忽略不計了,畢竟是對20個數的小數據量進行排序:

沙海拾貝:

    我們不在乎是否能把一個軟件產品或一本書最終完成,我們更在乎的是,在完成這個產品或創作這本書的過程中,讀者學到了什麼,能學到什麼?所以,不要一味的馬上就想得到一道題目的正確答案,請跟着我們一起逐步走向山巔。

第四節、多路歸併算法的c實現

    本多路歸併算法的c實現原理與上述c++實現一致,不同的地方體現在一些細節處理上,且對臨時文件的排序,不再用系統提供的快排,即上面的qsort庫函數,是採用的三數中值的快速排序(個數小於3用插入排序)的。而我們知道,純正的歸併排序其實就是比較排序,在歸併過程中總是不斷的比較,爲了從兩個數中挑小的歸併到最終的序列中。ok,此程序的詳情請看:

  1. //copyright@ 555  
  2. //July、2011.05.29。  
  3. #include <assert.h>  
  4. #include <time.h>   
  5. #include <stdio.h>     
  6. #include <memory.h>  
  7. #include <stdlib.h>  
  8.   
  9. void swap_int(int* a,int* b)  
  10. {      
  11.     int c;      
  12.     c = *a;      
  13.     *a = *b;      
  14.     *b = c;  
  15. }  
  16.   
  17. //插入排序  
  18. void InsertionSort(int A[],int N)  
  19. {      
  20.     int j,p;      
  21.     int tmp;     
  22.     for(p = 1; p < N; p++)      
  23.     {         
  24.         tmp = A[p];  
  25.         for(j = p;j > 0 && A[j - 1] >tmp;j--)          
  26.         {              
  27.             A[j] = A[j - 1];          
  28.         }         
  29.           
  30.         A[j] = tmp;     
  31.     }  
  32. }  
  33.   
  34. //三數取中分割法  
  35. int Median3(int A[],int Left,int Right)  
  36. {  
  37.     int Center = (Left + Right) / 2;  
  38.     if (A[Left] > A[Center])  
  39.         swap_int(&A[Left],&A[Center]);  
  40.     if (A[Left] > A[Right])  
  41.         swap_int(&A[Left],&A[Right]);  
  42.     if (A[Center] > A[Right])  
  43.         swap_int(&A[Center],&A[Right]);  
  44.     swap_int(&A[Center],&A[Right - 1]);  
  45.     return A[Right - 1];  
  46. }  
  47.   
  48. //快速排序  
  49. void QuickSort(int A[],int Left,int Right)  
  50. {  
  51.     int i,j;  
  52.     int Pivot;  
  53.     const int Cutoff = 3;  
  54.     if (Left + Cutoff <= Right)  
  55.     {  
  56.         Pivot = Median3(A,Left,Right);  
  57.         i = Left;  
  58.         j = Right - 1;  
  59.         while (1)  
  60.         {  
  61.             while(A[++i] < Pivot){;}  
  62.             while(A[--j] > Pivot){;}  
  63.             if (i < j)  
  64.                 swap_int(&A[i],&A[j]);  
  65.             else  
  66.                 break;  
  67.         }  
  68.         swap_int(&A[i],&A[Right - 1]);   
  69.           
  70.         QuickSort(A,Left,i - 1);  
  71.         QuickSort(A,i + 1,Right);  
  72.     }  
  73.     else  
  74.     {  
  75.         InsertionSort(A+Left,Right - Left + 1);  
  76.     }  
  77. }  
  78.   
  79. //const int  KNUM  = 40;          
  80. //分塊數  
  81. const int  NUMBER = 10000000;   
  82. //輸入文件最大讀取的整數的個數  
  83. //爲了便於測試,我決定改成小文件小數據量進行測試。  
  84. const int  KNUM  = 4;          
  85. //分塊數const int  NUMBER = 100;   
  86. //輸入文件最大讀取的整數的個數  
  87. const char *in_file = "infile.txt";  
  88. const char *out_file = "outfile.txt";  
  89. //#define OUTPUT_OUT_FILE_DATA  
  90. //數據量大的時候,沒必要把所有的數全部打印出來,所以可以把上面這句註釋掉。  
  91. void  gen_infile(int n)  
  92. {  
  93.     int i;  
  94.     FILE *f = fopen(in_file, "wt");   
  95.     for(i = 0;i < n; i++)  
  96.         fprintf(f,"%d ",rand());  
  97.     fclose(f);  
  98. }  
  99.   
  100. int  read_data(FILE *f,int a[],int n)  
  101. {  
  102.     int i = 0;  
  103.     while ((i < n) && (fscanf(f,"%d",&a[i]) != EOF))    
  104.         i++;  
  105.     printf("read: %d integer/n",i);  
  106.     return i;  
  107. }  
  108.   
  109. void  write_data(FILE *f,int a[],int n)  
  110. {  
  111.     int i;for(i = 0; i< n;i++)  
  112.         fprintf(f,"%d ",a[i]);  
  113. }  
  114.   
  115. char* temp_filename(int index)  
  116. {  
  117.     char *tempfile = (char*) malloc(64*sizeof(char));  
  118.     assert(tempfile);  
  119.     sprintf(tempfile, "temp%d.txt", index);  
  120.     return tempfile;  
  121. }  
  122.   
  123. //K路串行讀取  
  124. void k_num_read(void)  
  125. {  
  126.     char* filename;  
  127.     int i,cnt,*array;  
  128.     FILE* fin;  
  129.     FILE* tmpfile;  
  130.     //計算knum,每路應讀取的整數個數int n = NUMBER/KNUM;  
  131.     if (n * KNUM < NUMBER)n++;  
  132.   
  133.     //建立存儲分塊讀取的數據的數組  
  134.     array = (int*)malloc(n * sizeof(int));assert(array);  
  135.     //打開輸入文件  
  136.     fin = fopen(in_file,"rt");  
  137.     i = 0;  
  138.       
  139.     //分塊循環讀取數據,並寫入硬盤上的臨時文件  
  140.     while ( (cnt = read_data(fin,array,n))>0)  
  141.     {  
  142.         //對每次讀取的數據,先進行快速排序,然後寫入硬盤上的臨時文件  
  143.         QuickSort(array,0,cnt - 1);  
  144.         filename = temp_filename(i++);  
  145.         tmpfile = fopen(filename,"w");  
  146.         free(filename);  
  147.         write_data(tmpfile,array,cnt);  
  148.         fclose(tmpfile);  
  149.     }  
  150.     assert(i == KNUM);  
  151.     //沒有生成K路文件時進行診斷  
  152.     //關閉輸入文件句柄和臨時存儲數組  
  153.     fclose(fin);  
  154.     free(array);  
  155. }  
  156.   
  157. //k路合併(敗者樹)  
  158. void k_num_merge(void)  
  159. {  
  160.     FILE *fout;  
  161.     FILE **farray;  
  162.     char *filename;  
  163.     int  *data;  
  164.     char *hasNext;  
  165.     int i,j,m,min;  
  166. #ifdef OUTPUT_OUT_FILE_DATAint id;  
  167. #endif  
  168.     //打開輸出文件  
  169.     fout = fopen(out_file,"wt");  
  170.     //打開各路臨時分塊文件  
  171.     farray = (FILE**)malloc(KNUM*sizeof(FILE*));  
  172.     assert(farray);  
  173.     for(i = 0; i< KNUM;i++)  
  174.     {  
  175.         filename = temp_filename(i);  
  176.         farray[i] = fopen(filename,"rt");  
  177.         free(filename);  
  178.     }  
  179.       
  180.     //建立KNUM個元素的data,hasNext數組,存儲K路文件的臨時數組和讀取結束狀態  
  181.     data = (int*)malloc(KNUM*sizeof(int));  
  182.     assert(data);  
  183.     hasNext = (char*)malloc(sizeof(char)*KNUM);  
  184.     assert(hasNext);  
  185.     memset(data, 0, sizeof(int) * KNUM);  
  186.     memset(hasNext, 1, sizeof(char) * KNUM);  
  187.       
  188.     //讀K路文件先讀取第一組數據,並對讀取結束的各路文件設置不可再讀狀態  
  189.     for(i = 0; i < KNUM; i++)  
  190.     {  
  191.         if(fscanf(farray[i], "%d", &data[i]) == EOF)  
  192.         {  
  193.             hasNext[i] = 0;  
  194.         }  
  195.     }  
  196.       
  197.     //讀取各路文件,利用敗者樹從小到大輸出到輸出文件  
  198. #ifdef OUTPUT_OUT_FILE_DATAid = 0;  
  199. #endif  
  200.       
  201.     j  = 0;F_LOOP:  
  202.     if (j < KNUM)      
  203.         //以下這段代碼嵌套過深,日後應儘量避免此類問題。  
  204.     {  
  205.         while(1==1)  
  206.         {  
  207.             min = data[j];  
  208.             m = j;  
  209.             for(i = j+1; i < KNUM; i++)  
  210.             {  
  211.                 if(hasNext[i] == 1  && min > data[i])  
  212.                 {  
  213.                     min = data[i];m = i;  
  214.                 }  
  215.             }  
  216.   
  217.             if(fscanf(farray[m], "%d", &data[m]) == EOF)   
  218.             {  
  219.                 hasNext[m] = 0;  
  220.             }  
  221.             fprintf(fout, "%d ", min);  
  222. #ifdef OUTPUT_OUT_FILE_DATAprintf("fout :%d  %d/n",++id,min);  
  223. #endif  
  224.             if (m == j && hasNext[m] == 0)  
  225.             {  
  226.                 for (i = j+1; i < KNUM; i++)  
  227.                 {  
  228.                     if (hasNext[m] != hasNext[i])  
  229.                     {  
  230.                         m = i;  
  231.                         //第i個文件未讀完,從第i個繼續往下讀  
  232.                         break;  
  233.                     }  
  234.                 }  
  235.                 if (m != j)  
  236.                 {  
  237.                     j = m;  
  238.                     goto F_LOOP;  
  239.                 }  
  240.                 break;  
  241.             }  
  242.         }  
  243.     }  
  244.       
  245.     //關閉分配的數據和數組      
  246.     free(hasNext);     
  247.     free(data);         
  248.     for(i = 0; i < KNUM; ++i)     
  249.     {          
  250.         fclose(farray[i]);     
  251.     }     
  252.     free(farray);      
  253.     fclose(fout);  
  254. }  
  255.   
  256. int main()      
  257. {     
  258.     time_t start = time(NULL),end,start_read,end_read,start_merge,end_merge;  
  259.     gen_infile(NUMBER);      
  260.     end = time(NULL);     
  261.     printf("gen_infile data time:%f/n", (end - start) * 1000.0/ CLOCKS_PER_SEC);  
  262.     start_read = time(NULL);k_num_read();      
  263.     end_read = time(NULL);     
  264.     printf("k_num_read time:%f/n", (end_read - start_read) * 1000.0/ CLOCKS_PER_SEC);  
  265.     start_merge = time(NULL);  
  266.     k_num_merge();      
  267.     end_merge = time(NULL);      
  268.     printf("k_num_merge time:%f/n", (end_merge - start_merge) * 1000.0/ CLOCKS_PER_SEC);     
  269.     end = time(NULL);     
  270.     printf("total time:%f/n", (end - start) * 1000.0/ CLOCKS_PER_SEC);      
  271.     return 0;    
  272. }    

程序測試:

在此,我們先測試下對10000000個數據的文件進行40趟排序,然後再對100個數據的文件進行4趟排序(讀者可進一步測試)。如弄幾組小點的數據,輸出ID和數據到屏幕,再看程序運行效果。

  1. 10個數, 4組
  2. 40個數, 5組
  3. 55個數, 6組
  4. 100個數, 7組

 

(備註:1、以上所有各節的程序運行環境爲windows xp + vc6.0 + e5200 cpu 2.5g主頻,2、感謝5爲本文程序所作的大量測試工作)

全文總結:

1、關於本章中位圖和多路歸併兩種方案的時間複雜度及空間複雜度的比較,如下:

              時間複雜度       空間複雜度
位圖         O(N)               0.625M
多位歸併   O(Nlogn)        1M   

(多路歸併,時間複雜度爲O(k*n/k*logn/k ),嚴格來說,還要加上讀寫磁盤的時間,而此算法絕大部分時間也是浪費在這上面)

2、bit-map

適用範圍:可進行數據的快速查找,判重,刪除,一般來說數據範圍是int的10倍以下
基本原理及要點:使用bit數組來表示某些元素是否存在,比如8位電話號碼
擴展:bloom filter可以看做是對bit-map的擴展

問題實例:
1)已知某個文件內包含一些電話號碼,每個號碼爲8位數字,統計不同號碼的個數。
8位最多99 999 999,大概需要99m個bit,大概10幾m字節的內存即可。
2)2.5億個整數中找出不重複的整數的個數,內存空間不足以容納這2.5億個整數。

將bit-map擴展一下,用2bit表示一個數即可,0表示未出現,1表示出現一次,2表示出現2次及以上。或者我們不用2bit來進行表示,我們用兩個bit-map即可模擬實現這個2bit-map。

3、[外排序適用範圍]大數據的排序,去重基本原理及要點:外排序的歸併方法,置換選擇敗者樹原理,最優歸併樹擴展。問題實例:1).有一個1G大小的一個文件,裏面每一行是一個詞,詞的大小不超過16個字節,內存限制大小是1M。返回頻數最高的100個詞。這個數據具有很明顯的特點,詞的大小爲16個字節,但是內存只有1m做hash有些不夠,所以可以用來排序。內存可以當輸入緩衝區使用。 

4、海量數據處理

    有關海量數據處理的方法或面試題可參考此文,十道海量數據處理面試題與十個方法大總結。日後,會逐步實現這十個處理海量數據的方法。同時,送給各位一句話,解決問題的關鍵在於熟悉一個算法,而不是某一個問題。熟悉了一個算法,便通了一片題目。

本章完。

    updated:有一讀者朋友針對本文寫了一篇文章爲,海量數據多路歸併排序的c++實現(歸併時利用了敗者樹),地址爲:http://www.cnblogs.com/harryshayne/archive/2011/07/02/2096196.html。謝謝,歡迎參考。





以下是自己已編譯OK 的程序代碼,(可能與上面的有衝突的地方)


[html] view plaincopy
  1. /*=====================================  
  2. Filename:  
  3.     sortfile.c  
  4.   
  5. Copyright (C) 2006 caicai  
  6.     All rights reserved.  
  7.   
  8. Description:  
  9.     This file is used to sort about file.  
  10.   
  11. Author/Created Date:  
  12.     Lumi-liu, Nov19'14  
  13.   
  14. Modification History:  
  15.   
  16. Note:  
  17.   
  18. =======================================*/  
  19.   
  20. #include <stdio.h>  
  21. #include <stdlib.h>    
  22. #include <memory.h>  
  23. #include <time.h>  
  24. #include <assert.h>  
  25.   
  26. //數據交換函數  
  27. void swap_int(int* a,int* b)  
  28. {  
  29.     int c;  
  30.     c = *a;  
  31.     *a = *b;  
  32.     *b = c;  
  33. }  
  34.   
  35. //插入排序  
  36. void InsertionSort(int a[],int N)  
  37. {  
  38.     int j;  
  39.     int p;  
  40.     int tmp;  
  41.     for(p=0; p<N; p++)//p=1  
  42.     {  
  43.         tmp = a[p];  //p=0  
  44.         for(j=p;/* j>0 && */a[j-1]>tmp; j--)//  
  45.         {  
  46.             a[j] = a[j-1];  
  47.         }  
  48.         a[j] = tmp;  
  49.     }  
  50. }  
  51.   
  52. //三數取中分割法  
  53. int Median3(int a[],int Left,int Right)  
  54. {  
  55.     //if ( Left+3 >= Right )  
  56.     //  return -1;  
  57.     int Cent = (Left + Right) / 2;  
  58.     if (a[Left] > a[Cent])  
  59.         swap_int(&a[Left],&a[Cent]);  
  60.     if (a[Left] > a[Right])  
  61.         swap_int(&a[Left],&a[Right]);  
  62.     if (a[Cent] > a[Right])  
  63.         swap_int(&a[Cent],&a[Right]);  
  64.     swap_int(&a[Cent],&a[Right-1]);  
  65.     return a[Right-1];  
  66. }      
  67.   
  68. //快速排序  
  69. void QuickSort(int a[],int Left,int Right)  
  70. {  
  71.     int i;  
  72.     int j;  
  73.     int Center;  
  74.     const int Cutoff = 3;  
  75.     if (Left + Cutoff <= Right)  
  76.     {  
  77.         Center = Median3(a,Left,Right);  
  78.         i = Left;  
  79.         j = Right-1;  
  80.         while (1)//for()  
  81.         {  
  82.             while(a[++i] < Center){;}//下標右移  
  83.             while(a[--j] > Center){;}//下標左移  
  84.             if (i < j)  
  85.                 swap_int(&a[i],&a[j]);  
  86.             else  
  87.                 break;  
  88.         }  
  89.         swap_int(&a[i],&a[Right-1]);  
  90.         QuickSort(a,Left,i-1);    
  91.         QuickSort(a,i+1,Right);  
  92.     }  
  93.     else  
  94.     {  
  95.         InsertionSort(a+Left,Right-Left+1);  
  96.     }  
  97. }  
  98.   
  99. const int Num = 100000000;  
  100. //const int  Num = 10000000;//文件內整數的個數  
  101. //便於測試,可先定義Num = 1000;  
  102. const int  Knum  = 4;//分割成文件的個數  
  103. const char *Ifile = "infile.txt";//未排序的文件名  
  104. const char *Ofile = "outfile.txt";//最終的文件名  
  105.   
  106. //生成隨機數文件  
  107. void  gen_infile(int n)  
  108. {  
  109.     int i;  
  110.     FILE *fp = fopen(Ifile, "wt");  
  111.     for(i = 0;i < n; i++)  
  112.         fprintf(fp,"%d ",rand()%1000);  
  113.     fclose(fp);  
  114. }  
  115.   
  116.   
  117. //讀取臨時文件中數據的個數  
  118. int  read_data(FILE *fp,int a[],int n)  
  119. {  
  120.     int i = 0;  
  121.     while ((i < n) && (fscanf(fp,"%d",&a[i]) != EOF))  
  122.         i++;  
  123.     printf("read: %d integer\n",i);  
  124.     return i;  
  125. }  
  126.   
  127. //寫入文件  
  128. void  write_data(FILE *fp,int a[],int n)  
  129. {  
  130.     int i;  
  131.     for(i=0; i<n; i++)  
  132.         fprintf(fp,"%d ",a[i]);  
  133. }  
  134.   
  135. //臨時文件的命名  
  136. char* temp_filename(int index)  
  137. {  
  138.     char *tempfile = (char*) malloc(64*sizeof(char));  
  139.     assert(tempfile);  
  140.     sprintf(tempfile, "temp%d.txt", index+1);  
  141.     return tempfile;  
  142. }  
  143.   
  144. //k路串行讀取數據  
  145. void k_num_read(void)  
  146. {  
  147.     char* filename;  
  148.     int i;  
  149.     int cnt;  
  150.     int *arr;  
  151.     int n=Num/Knum;  
  152.     FILE* fin;  
  153.     FILE* tmpfile;  
  154.     if (n*Knum < Num)  
  155.         n++;//各個文件要讀取數據的個數  
  156.     arr = (int*)malloc(n * sizeof(int));  
  157.     assert(arr);  
  158.     fin = fopen(Ifile,"rt");  
  159.     i = 0;  
  160.       
  161.     //分塊循環讀取數據並寫入臨時文件  
  162.     while ( (cnt = read_data(fin,arr,n))>0)  
  163.     {  
  164.         //每次讀取時先進行排序  
  165.         QuickSort(arr,0,cnt-1);  
  166.         filename = temp_filename(i++);  
  167.         tmpfile = fopen(filename,"w");  
  168.         free(filename);  
  169.         write_data(tmpfile,arr,cnt);  
  170.         fclose(tmpfile);  
  171.     }  
  172.     //沒有生成k路文件時進行診斷  
  173.     assert(i == Knum);  
  174.     fclose(fin);  
  175.     free(arr);  
  176. }  
  177.   
  178.   
  179. //對臨時文件進行合併(敗者樹)  
  180. void k_num_merge(void)  
  181. {  
  182.     FILE *fout;  
  183.     FILE **farr;  
  184.     char *filename;  
  185.     int  *data;  
  186.     char *hasNext;  
  187.     int i,j,m,min;  
  188. //#ifdef OUTPUT_Ofile_DaTaint id;    
  189. //#endif  
  190.     fout = fopen(Ofile,"wt");  
  191.     //打開文件  
  192.     farr = (FILE**)malloc(Knum*sizeof(FILE*));  
  193.     assert(farr);  
  194.   
  195.     for(i = 0; i< Knum;i++)  
  196.     {  
  197.         filename = temp_filename(i);  
  198.         farr[i] = fopen(filename,"rt");  
  199.         free(filename);  
  200.     }  
  201.     //建立包含knum個元素的data,hasnext數組  
  202.     //存儲k路文件的臨時數組和讀取結束狀態  
  203.     data = (int*)malloc(Knum*sizeof(int));  
  204.     assert(data);  
  205.     hasNext = (char*)malloc(sizeof(char)*Knum);  
  206.     assert(hasNext);  
  207.     memset(data, 0, sizeof(int) * Knum);  
  208.     memset(hasNext, 1, sizeof(char) * Knum);  
  209.       
  210.     //先讀取第一組數據  
  211.     for(i = 0; i < Knum; i++)  
  212.     {  
  213.         if(fscanf(farr[i], "%d", &data[i]) == EOF)  
  214.         {  
  215.             hasNext[i] = 0;  
  216.         }  
  217.     }  
  218. //#ifdef OUTPUT_Ofile_DaTaid = 0;    
  219. //#endif  
  220.     j  = 0;  
  221. F_LOOP:  
  222.     if (j < Knum)  
  223.     {  
  224.         while(1)  
  225.         {  
  226.             min = data[j];  
  227.             m = j;  
  228.             for(i = j+1; i < Knum; i++)  
  229.             {  
  230.                 if(hasNext[i] == 1  && min > data[i])  
  231.                 {  
  232.                     min = data[i];  
  233.                     m = i;  
  234.                 }  
  235.             }  
  236.               
  237.             if(fscanf(farr[m], "%d", &data[m]) == EOF)  
  238.             {  
  239.                 hasNext[m] = 0;  
  240.             }  
  241.             fprintf(fout, "%d ", min);    
  242. //#ifdef OUTPUT_Ofile_DaTaprintf("fout :%d  %d/n",++id,min);    
  243. //#endif    
  244.             if (hasNext[m] == 0) //m == j &&  
  245.             {  
  246.                 for (i = j+1; i < Knum; i++)  
  247.                 {  
  248.                     if (hasNext[m] != hasNext[i])  
  249.                     {  
  250.                         m = i;//  
  251.                         break;  
  252.                     }  
  253.                 }  
  254.                 if (m != j)  
  255.                 {  
  256.                     j = m;  
  257.                     goto F_LOOP;  
  258.                 }  
  259.                 break;  
  260.             }  
  261.         }  
  262.     }  
  263.       
  264.       
  265.     free(hasNext);  
  266.     free(data);  
  267.     for(i = 0; i < Knum; ++i)  
  268.     {  
  269.         fclose(farr[i]);  
  270.     }  
  271.     free(farr);  
  272.     fclose(fout);  
  273. }  
  274.   
  275.   
  276. int main()  
  277. {  
  278.     time_t start = time(NULL),end,start_read,end_read,start_merge,end_merge;  
  279.     gen_infile(Num);  
  280.     end = time(NULL);  
  281.     //生成文件的時間  
  282.     printf("gen_infile data time:%f\n",   
  283.                     (end - start) * 1000.0/ CLOCKS_PER_SEC);  
  284.     start_read = time(NULL);  
  285.     k_num_read();  
  286.     end_read = time(NULL);  
  287.     //讀取文件的時間  
  288.     printf("k_num_read time:%f\n",   
  289.                     (end_read - start_read) * 1000.0/ CLOCKS_PER_SEC);  
  290.     start_merge = time(NULL);  
  291.     k_num_merge();  
  292.     end_merge = time(NULL);  
  293.     //臨時文件合併的時間  
  294.     printf("k_num_merge time:%f\n",   
  295.                     (end_merge - start_merge) * 1000.0/ CLOCKS_PER_SEC);  
  296.     end = time(NULL);  
  297.     //總時間  
  298.     printf("total time:%f\n",   
  299.                     (end - start) * 1000.0/ CLOCKS_PER_SEC);  
  300.     return 0;  
  301. }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章