这个是算法导论编号为6.5-8的习题,代码如下: #include <stdio.h> #include <stdlib.h> #define INFINITE_VAL 0x7FFFFFFF //保证pos节点以下为最小堆 void min_heap(int *heap, int size, int pos) { int lpos, rpos, minpos, temp; while (1) { lpos = 2*pos + 1; rpos = 2*pos + 2; if (lpos < size && (heap[pos] == INFINITE_VAL || heap[lpos] < heap[pos])) { minpos = lpos; } else { minpos = pos; } if (rpos < size && ( heap[minpos] == INFINITE_VAL || heap[rpos] < heap[minpos])) { minpos = rpos; } if (minpos != pos) { temp = heap[pos]; heap[pos] = heap[minpos]; heap[minpos] = temp; pos = minpos; } else { break; } } } //根据数组构造一个最小堆 void min_heap_create(int *heap, int size) { int i; if (NULL == heap || size <= 0) { return; } for (i = (size - 1)/2; i > 0; i--) { min_heap(heap, size, i); } } void k_way_merge() { //test data int a[] = {1, 3, 5, 7, 8, 9, 12}; int b[] = {12, 32, 43, 54, 65, 76, 86, 97, 100}; int c[] = {21, 23, 34, 56, 57, 78, 88}; int d[] = {12, 34, 43, 53, 65}; int e[] = {2, 54, 100}; int f[] = {122, 422, 566, 777, 888, 999, 1111,2222, 3333, 4444, 5555}; int g[] = {31, 34, 35, 37, 38, 39, 43, 44}; int h[] = {65, 85, 95, 105, 205, 305, 405, 505, 605, 705}; //set of test data int *L[] = {a, b, c, d, e, f, g, h}; //size of each test data array int S[] = {sizeof(a)/sizeof(int), sizeof(b)/sizeof(int), sizeof(c)/sizeof(int), sizeof(d)/sizeof(int), sizeof(e)/sizeof(int), sizeof(f)/sizeof(int), sizeof(g)/sizeof(int), sizeof(h)/sizeof(int)}; int *A, n, k, i, j, *heap; k = sizeof(L)/sizeof(int*); //num of elements in array L //num of elements in all test data n = (sizeof(a) + sizeof(b) + sizeof(c) + sizeof(d) + sizeof(e) + sizeof(f) + sizeof(g) + sizeof(h))/sizeof(int); if (NULL == (A = (int*)malloc(n * sizeof(int)))) { return; } if (NULL == (heap = (int*)malloc(k * sizeof(int)))) { return; } /*------------------------------------------------- Because each of test data array is a sort list,so all of them are min(max) heap, extract the data is the min(max) data in each list. we get all the min(max) data in each list, and create a new min(max) heap, extract the data in new min(max) heap is the min(max) data in the all test data.Then, we get the second min data in the data which is extracted list, insert to the data into the new min(max) heap, and make it min heap again, extract it, and do it again and again, until all data extracted. ------------------------------------------------*/ //create a min heap for (j = 0; j < k; j++) { heap[j] = L[j][0]; } min_heap_create(heap, k); for (i = 0; i < n; ++i) { A[i] = heap[0]; for (j = 0; j < k; ++j) { if (L[j][0] == A[i]) { L[j][0] = INFINITE_VAL; min_heap(L[j], S[j], 0); heap[0] = L[j][0]; break; } } min_heap(heap, k, 0); } for (i = 0; i < n; ++i) { printf("%d ", A[i]); } printf("/n"); free(heap); free(A); } int main(int argv, char* argc[]) { k_way_merge(); return 0; } 运行结果: