败者树 多路平衡归并外部排序 Dreaming.O的专栏 博客频道 CSDN.NET

败者树 多路平衡归并外部排序 - Dreaming.O的专栏 - 博客频道 - CSDN.NET

败者树 多路平衡归并外部排序

分类: Algorithm 309人阅读 评论(0) 收藏 举报

一 外部排序的基本思路

假设有一个72KB的文件,其中存储了18K个整数,磁盘中物理块的大小为4KB,将文件分成18组,每组刚好4KB。

首先通过18次内部排序,把18组数据排好序,得到初始的18个归并段R1~R18,每个归并段有1024个整数。

然后对这18个归并段使用4路平衡归并排序:

第1次归并:产生5个归并段

R11   R12    R13    R14    R15

其中

R11是由{R1,R2,R3,R4}中的数据合并而来

R12是由{R5,R6,R7,R8}中的数据合并而来

R13是由{R9,R10,R11,R12}中的数据合并而来

R14是由{R13,R14,R15,R16}中的数据合并而来

R15是由{R17,R18}中的数据合并而来

把这5个归并段的数据写入5个文件:

foo_1.dat    foo_2.dat    foo_3.dat     foo_4.dat     foo_5.dat

 

第2次归并:从第1次归并产生的5个文件中读取数据,合并,产生2个归并段

R21  R22

其中R21是由{R11,R12,R13,R14}中的数据合并而来

其中R22是由{R15}中的数据合并而来

把这2个归并段写入2个文件

bar_1.dat   bar_2.dat

 

第3次归并:从第2次归并产生的2个文件中读取数据,合并,产生1个归并段

R31

R31是由{R21,R22}中的数据合并而来

把这个文件写入1个文件

foo_1.dat

此即为最终排序好的文件。

 

二 使用败者树加快合并排序

外部排序最耗时间的操作时磁盘读写,对于有m个初始归并段,k路平衡的归并排序,磁盘读写次数为

|logkm|,可见增大k的值可以减少磁盘读写的次数,但增大k的值也会带来负面效应,即进行k路合并

的时候会增加算法复杂度,来看一个例子。

把n个整数分成k组,每组整数都已排序好,现在要把k组数据合并成1组排好序的整数,求算法复杂度

u1: xxxxxxxx

u2: xxxxxxxx

u3: xxxxxxxx

.......

uk: xxxxxxxx

算法的步骤是:每次从k个组中的首元素中选一个最小的数,加入到新组,这样每次都要比较k-1次,故

算法复杂度为O((n-1)*(k-1)),而如果使用败者树,可以在O(logk)的复杂度下得到最小的数,算法复杂

度将为O((n-1)*logk), 对于外部排序这种数据量超大的排序来说,这是一个不小的提高。

 

关于败者树的创建和调整,可以参考清华大学《数据结构-C语言版》

 

三 产生二进制测试数据

打开Linux终端,输入命令

dd if=/dev/urandom of=random.dat bs=1M count=512

 这样在当前目录下产生一个512M大的二进制文件,文件内的数据是随机的,读取文件,每4个字节

看成1个整数,相当于得到128M个随机整数。

 

四 程序实现

 

C代码  收藏代码
  1. #include <assert.h>  
  2. #include <fcntl.h>  
  3. #include <stdio.h>  
  4. #include <stdlib.h>  
  5. #include <string.h>  
  6. #include <unistd.h>  
  7.   
  8. #include <sys/time.h>  
  9. #include <sys/types.h>  
  10. #include <sys/stat.h>  
  11.   
  12. #define MAX_INT ~(1<<31)  
  13. #define MIN_INT 1<<31  
  14.   
  15. //#define DEBUG  
  16.   
  17. #ifdef DEBUG  
  18. #define debug(...) debug( __VA_ARGS__)   
  19. #else  
  20. #define debug(...)  
  21. #endif  
  22.   
  23. #define MAX_WAYS 100  
  24.   
  25. typedef struct run_t {  
  26.     int *buf;       /* 输入缓冲区 */  
  27.     int length;     /* 缓冲区当前有多少个数 */  
  28.     int offset;     /* 缓冲区读到了文件的哪个位置 */  
  29.     int idx;        /* 缓冲区的指针 */  
  30. } run_t;  
  31.   
  32. static unsigned int K;              /* K路合并 */  
  33. static unsigned int BUF_PAGES;      /* 缓冲区有多少个page */  
  34. static unsigned int PAGE_SIZE;      /* page的大小 */  
  35. static unsigned int BUF_SIZE;       /* 缓冲区的大小, BUF_SIZE = BUF_PAGES*PAGE_SIZE */  
  36.   
  37. static int *buffer;                 /* 输出缓冲区 */  
  38.   
  39. static char input_prefix[] = "foo_";  
  40. static char output_prefix[] = "bar_";  
  41.   
  42. static int ls[MAX_WAYS];            /* loser tree */  
  43.   
  44. void swap(int *p, int *q);  
  45. int partition(int *a, int s, int t);  
  46. void quick_sort(int *a, int s, int t);  
  47. void adjust(run_t ** runs, int n, int s);  
  48. void create_loser_tree(run_t **runs, int n);  
  49. long get_time_usecs();  
  50. void k_merge(run_t** runs, char* input_prefix, int num_runs, int base, int n_merge);  
  51. void usage();  
  52.   
  53.   
  54. int main(int argc, char **argv)  
  55. {  
  56.     char                filename[100];  
  57.     unsigned int    data_size;  
  58.     unsigned int    num_runs;               /* 这轮迭代时有多少个归并段 */  
  59.     unsigned int    num_merges;             /* 这轮迭代后产生多少个归并段 num_merges = num_runs/K */  
  60.     unsigned int    run_length;             /* 归并段的长度,指数级增长 */  
  61.     unsigned int    num_runs_in_merge;      /* 一般每个merge由K个runs合并而来,但最后一个merge可能少于K个runs */  
  62.     int                 fd, rv, i, j, bytes;  
  63.     struct stat         sbuf;  
  64.   
  65.     if (argc != 3) {  
  66.         usage();  
  67.         return 0;  
  68.     }  
  69.     long start_usecs = get_time_usecs();  
  70.   
  71.     strcpy(filename, argv[1]);  
  72.     fd = open(filename, O_RDONLY);  
  73.     if (fd < 0) {  
  74.         printf("can't open file %s\n", filename);  
  75.         exit(0);  
  76.     }  
  77.     rv = fstat(fd, &sbuf);  
  78.     data_size = sbuf.st_size;  
  79.   
  80.     K = atoi(argv[2]);  
  81.     PAGE_SIZE = 4096;                           /* page = 4KB */  
  82.     BUF_PAGES = 32;  
  83.     BUF_SIZE = PAGE_SIZE*BUF_PAGES;  
  84.     num_runs = data_size / PAGE_SIZE;           /* 初始时的归并段数量,每个归并段有4096 byte, 即1024个整数 */  
  85.     buffer = (int *)malloc(BUF_SIZE);  
  86.   
  87.     run_length = 1;  
  88.     run_t **runs = (run_t **)malloc(sizeof(run_t *)*(K+1));  
  89.     for (i = 0; i < K; i++) {  
  90.         runs[i] = (run_t *)malloc(sizeof(run_t));  
  91.         runs[i]->buf = (int *)calloc(1, BUF_SIZE+4);  
  92.     }  
  93.     while (num_runs > 1) {  
  94.         num_merges = num_runs / K;  
  95.         int left_runs = num_runs % K;  
  96.         if(left_runs > 0) num_merges++;  
  97.         for (i = 0; i < num_merges; i++) {  
  98.             num_runs_in_merge = K;  
  99.             if ((i+1) == num_merges && left_runs > 0) {  
  100.                 num_runs_in_merge = left_runs;  
  101.             }  
  102.             int base = 0;  
  103.             printf("Merge %d of %d,%d ways\n", i, num_merges, num_runs_in_merge);  
  104.             for (j = 0; j < num_runs_in_merge; j++) {  
  105.                 if (run_length == 1) {  
  106.                     base = 1;  
  107.                     bytes = read(fd, runs[j]->buf, PAGE_SIZE);  
  108.                     runs[j]->length = bytes/sizeof(int);  
  109.                     quick_sort(runs[j]->buf, 0, runs[j]->length-1);  
  110.                 } else {  
  111.                     snprintf(filename, 20, "%s%d.dat", input_prefix, i*K+j);  
  112.                     int infd = open(filename, O_RDONLY);  
  113.                     bytes = read(infd, runs[j]->buf, BUF_SIZE);  
  114.                     runs[j]->length = bytes/sizeof(int);  
  115.                     close(infd);      
  116.                 }  
  117.                 runs[j]->idx = 0;  
  118.                 runs[j]->offset = bytes;  
  119.             }  
  120.             k_merge(runs, input_prefix, num_runs_in_merge, base, i);  
  121.         }  
  122.   
  123.         strcpy(filename, output_prefix);  
  124.         strcpy(output_prefix, input_prefix);  
  125.         strcpy(input_prefix, filename);  
  126.   
  127.         run_length *= K;  
  128.         num_runs = num_merges;  
  129.     }  
  130.   
  131.     for (i = 0; i < K; i++) {  
  132.         free(runs[i]->buf);  
  133.         free(runs[i]);  
  134.     }  
  135.     free(runs);  
  136.     free(buffer);  
  137.     close(fd);  
  138.   
  139.     long end_usecs = get_time_usecs();  
  140.     double secs = (double)(end_usecs - start_usecs) / (double)1000000;  
  141.     printf("Sorting took %.02f seconds.\n", secs);  
  142.     printf("sorting result saved in %s%d.dat.\n", input_prefix, 0);  
  143.   
  144.     return 0;  
  145. }  
  146.   
  147. void k_merge(run_t** runs, char* input_prefix, int num_runs, int base, int n_merge)  
  148. {  
  149.     int bp, bytes, output_fd;  
  150.     int live_runs = num_runs;  
  151.     run_t *mr;  
  152.     char filename[20];  
  153.   
  154.     bp = 0;  
  155.     create_loser_tree(runs, num_runs);  
  156.   
  157.     snprintf(filename, 100, "%s%d.dat", output_prefix, n_merge);  
  158.     output_fd = open(filename, O_CREAT|O_WRONLY|O_TRUNC,   
  159.             S_IRWXU|S_IRWXG);  
  160.     if (output_fd < 0) {  
  161.         printf("create file %s fail\n", filename);  
  162.         exit(0);  
  163.     }  
  164.   
  165.     while (live_runs > 0) {  
  166.         mr = runs[ls[0]];  
  167.         buffer[bp++] = mr->buf[mr->idx++];  
  168.         // 输出缓冲区已满  
  169.         if (bp*4 == BUF_SIZE) {  
  170.             bytes = write(output_fd, buffer, BUF_SIZE);  
  171.             bp = 0;  
  172.         }  
  173.         // mr的输入缓冲区用完  
  174.         if (mr->idx == mr->length) {  
  175.             snprintf(filename, 20, "%s%d.dat", input_prefix, ls[0]+n_merge*K);  
  176.             if (base) {  
  177.                 mr->buf[mr->idx] = MAX_INT;  
  178.                 live_runs--;  
  179.             } else {  
  180.                 int fd = open(filename, O_RDONLY);  
  181.                 lseek(fd, mr->offset, SEEK_SET);  
  182.                 bytes = read(fd, mr->buf, BUF_SIZE);  
  183.                 close(fd);  
  184.                 if (bytes == 0) {  
  185.                     mr->buf[mr->idx] = MAX_INT;  
  186.                     live_runs--;  
  187.                 }  
  188.                 else {  
  189.                     mr->length = bytes/sizeof(int);  
  190.                     mr->offset += bytes;  
  191.                     mr->idx = 0;  
  192.                 }  
  193.             }  
  194.         }  
  195.         adjust(runs, num_runs, ls[0]);  
  196.     }  
  197.     bytes = write(output_fd, buffer, bp*4);  
  198.     if (bytes != bp*4) {  
  199.         printf("!!!!!! Write Error !!!!!!!!!\n");  
  200.         exit(0);  
  201.     }  
  202.     close(output_fd);  
  203. }  
  204.   
  205. long get_time_usecs()  
  206. {  
  207.     struct timeval time;  
  208.     struct timezone tz;  
  209.     memset(&tz, '\0'sizeof(struct timezone));  
  210.     gettimeofday(&time, &tz);  
  211.     long usecs = time.tv_sec*1000000 + time.tv_usec;  
  212.   
  213.     return usecs;  
  214. }  
  215.   
  216. void swap(int *p, int *q)  
  217. {  
  218.     int     tmp;  
  219.   
  220.     tmp = *p;  
  221.     *p = *q;  
  222.     *q = tmp;  
  223. }  
  224.   
  225. int partition(int *a, int s, int t)  
  226. {  
  227.     int     i, j;   /* i用来遍历a[s]...a[t-1], j指向大于x部分的第一个元素 */  
  228.   
  229.     for (i = j = s; i < t; i++) {  
  230.         if (a[i] < a[t]) {  
  231.             swap(a+i, a+j);  
  232.             j++;  
  233.         }  
  234.     }  
  235.     swap(a+j, a+t);  
  236.   
  237.     return j;  
  238. }  
  239.   
  240. void quick_sort(int *a, int s, int t)  
  241. {  
  242.     int     p;  
  243.   
  244.     if (s < t) {  
  245.         p = partition(a, s, t);  
  246.         quick_sort(a, s, p-1);  
  247.         quick_sort(a, p+1, t);  
  248.     }  
  249. }  
  250.   
  251. void adjust(run_t ** runs, int n, int s)  
  252. {  
  253.     int t, tmp;  
  254.   
  255.     t = (s+n)/2;  
  256.     while (t > 0) {  
  257.         if (s == -1) {  
  258.             break;  
  259.         }  
  260.         if (ls[t] == -1 || runs[s]->buf[runs[s]->idx] > runs[ls[t]]->buf[runs[ls[t]]->idx]) {  
  261.             tmp = s;  
  262.             s = ls[t];  
  263.             ls[t] = tmp;  
  264.         }  
  265.         t >>= 1;  
  266.     }  
  267.     ls[0] = s;  
  268. }  
  269.   
  270. void create_loser_tree(run_t **runs, int n)  
  271. {  
  272.     int     i;  
  273.   
  274.     for (i = 0; i < n; i++) {  
  275.         ls[i] = -1;  
  276.     }  
  277.     for (i = n-1; i >= 0; i--) {  
  278.         adjust(runs, n, i);  
  279.     }  
  280. }  
  281.   
  282. void usage()  
  283. {  
  284.     printf("sort <filename> <K-ways>\n");  
  285.     printf("\tfilename: filename of file to be sorted\n");  
  286.     printf("\tK-ways: how many ways to merge\n");  
  287.     exit(1);  
  288. }  
 

 

五 编译运行

gcc sort.c -o sort -g

./sort random.dat 64

以64路平衡归并对random.dat内的数据进行外部排序。在I5处理器,4G内存的硬件环境下,实验结果如下

文件大小    耗时

128M        14.72 秒

256M        30.89 秒

512M        71.65 秒

1G             169.18秒

 

六 读取二进制文件,查看排序结

 

C代码  收藏代码
  1. #include <assert.h>  
  2. #include <fcntl.h>  
  3. #include <stdio.h>  
  4. #include <stdlib.h>  
  5. #include <string.h>  
  6. #include <unistd.h>  
  7.   
  8. #include <sys/time.h>  
  9. #include <sys/types.h>  
  10. #include <sys/stat.h>  
  11.   
  12. int main(int argc, char **argv)  
  13. {  
  14.     char *filename = argv[1];  
  15.     int *buffer = (int *)malloc(1<<20);  
  16.     struct stat     sbuf;  
  17.     int rv, data_size, i, bytes, fd;  
  18.   
  19.     fd = open(filename, O_RDONLY);  
  20.     if (fd < 0) {  
  21.         printf("%s not found!\n", filename);  
  22.         exit(0);  
  23.     }  
  24.     rv = fstat(fd, &sbuf);  
  25.     data_size = sbuf.st_size;  
  26.   
  27.     bytes = read(fd, buffer, data_size);  
  28.     for (i = 0; i < bytes/4; i++) {  
  29.         printf("%d ", buffer[i]);  
  30.         if ((i+1) % 10 == 0) {  
  31.             printf("\n");  
  32.         }  
  33.     }  
  34.     printf("\n");  
  35.     close(fd);  
  36.     free(buffer);  
  37.     return 0;  
  38. }  
原文地址:https://www.cnblogs.com/lexus/p/2996444.html