標籤:style blog http color 使用 os
開始看編程珠璣了,第一個就是進行磁碟排序的問題,想到了也只是歸併排序,但題目要求1M記憶體,這個演算法不可行。編程珠璣寫到使用位元影像(分兩次操作讀寫可以成功實現,小於記憶體1M),詳情看編程珠璣第一章。
題目:給定10^7資料,對大資料進行排序。要求記憶體只有1M,時間可以接受,較短。
解決方案:1.多路歸併。2.位元影像操作。
在這裡看了july的文章,寫的真心不錯。推薦:http://blog.csdn.net/v_JULY_v/article/details/6451990
其中有個產生不同隨機數的程式附下:
1 #include <iostream> 2 #include <time.h> 3 #include <assert.h> 4 using namespace std; 5 6 const int size = 10000000; 7 int num[size]; 8 9 int main() 10 { 11 int n; 12 FILE *fp = fopen("data.txt", "w"); 13 assert(fp); 14 15 for (n = 1; n <= size; n++) 16 //之前此處寫成了n=0;n<size。導致下面有一段小程式的測試資料出現了0,特此訂正。 17 num[n] = n; 18 srand((unsigned)time(NULL)); 19 int i, j; 20 21 for (n = 0; n < size; n++) 22 { 23 i = (rand() * RAND_MAX + rand()) % 10000000; 24 j = (rand() * RAND_MAX + rand()) % 10000000; 25 swap(num[i], num[j]); 26 } 27 28 for (n = 0; n < size; n++) 29 fprintf(fp, "%d ", num[n]); 30 fclose(fp); 31 return 0; 32 }
位元影像程式實現排序,首先排前5000000(每個數字對應一個bit)個後排剩下的5000000資料(每次都小於1M),代碼如下(類比兩次):
1 #include <iostream> 2 #include <bitset> 3 #include <assert.h> 4 #include <time.h> 5 using namespace std; 6 7 const int max_each_scan = 5000000; 8 9 int main() 10 { 11 clock_t begin = clock(); 12 bitset<max_each_scan> bit_map; 13 bit_map.reset(); 14 15 // open the file with the unsorted data 16 FILE *fp_unsort_file = fopen("data.txt", "r"); 17 assert(fp_unsort_file); 18 int num; 19 20 // the first time scan to sort the data between 0 - 4999999 21 while (fscanf(fp_unsort_file, "%d ", &num) != EOF) 22 { 23 if (num < max_each_scan) 24 bit_map.set(num, 1); 25 } 26 27 FILE *fp_sort_file = fopen("sort.txt", "w"); 28 assert(fp_sort_file); 29 int i; 30 31 // write the sorted data into file 32 for (i = 0; i < max_each_scan; i++) 33 { 34 if (bit_map[i] == 1) 35 fprintf(fp_sort_file, "%d ", i); 36 } 37 38 // the second time scan to sort the data between 5000000 - 9999999 39 int result = fseek(fp_unsort_file, 0, SEEK_SET); 40 if (result) 41 cout << "fseek failed!" << endl; 42 else 43 { 44 bit_map.reset(); 45 while (fscanf(fp_unsort_file, "%d ", &num) != EOF) 46 { 47 if (num >= max_each_scan && num < 10000000) 48 { 49 num -= max_each_scan; 50 bit_map.set(num, 1); 51 } 52 } 53 for (i = 0; i < max_each_scan; i++) 54 { 55 if (bit_map[i] == 1) 56 fprintf(fp_sort_file, "%d ", i + max_each_scan); 57 } 58 } 59 60 clock_t end = clock(); 61 cout<<"用位元影像的方法,耗時:"<<endl; 62 cout << (end - begin) / CLK_TCK << "s" << endl; 63 fclose(fp_sort_file); 64 fclose(fp_unsort_file); 65 return 0; 66 }