fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <limits.h>
  4.  
  5. int multimerge(
  6. int * const * const arrays, // arrays holding the data
  7. int const * const arraysizes, // sizes of the arrays in `arrays`
  8. int number_of_arrays, // number of arrays
  9. int * const output // pointer to output buffer
  10. ){
  11. int i = 0; // output cursor
  12. int j = 0; // index for minimum search
  13. int min; // minimum in this iteration
  14. int minposition; // position of the minimum
  15.  
  16. // cursor for the arrays
  17. int * cursor = calloc(number_of_arrays,sizeof(int));
  18.  
  19. if(cursor == NULL)
  20. return -1;
  21.  
  22. while(1){
  23. min = INT_MAX;
  24. minposition = -1; // invalid position
  25.  
  26. // Go through the current positions and get the minimum
  27. for(j = 0; j < number_of_arrays; ++j){
  28.  
  29. if(cursor[j] < arraysizes[j] && // ensure that the cursor is still valid
  30. arrays[j][cursor[j]] < min){ // the element is smaller
  31. min = arrays[j][cursor[j]]; // save the minimum ...
  32. minposition = j; // ... and its position
  33. }
  34. }
  35.  
  36. // if there is no minimum, then the position will be invalid
  37.  
  38. if(minposition == -1)
  39. break;
  40.  
  41. // update the output and the specific cursor
  42. output[i++] = min;
  43. cursor[minposition]++;
  44. }
  45. free(cursor);
  46.  
  47. return 0;
  48. }
  49.  
  50. int main()
  51. {
  52. int i = 0;
  53. int test1[5] = {23, 24, 25, 33, 51};
  54. int test2[5] = {21, 34, 44, 50, 62};
  55. int test3[5] = {34, 36, 41, 44, 46};
  56. int test4[5] = {30, 31, 32, 35, 40};
  57. int test5[5] = {54, 56, 57, 58, 60};
  58. int test6[5] = {31, 33, 36, 51, 52};
  59. int test7[5] = {44, 46, 76, 78, 79};
  60. int test8[5] = {23, 33, 43, 54, 63};
  61.  
  62. int *test[] = {test1, test2, test3, test4, test5, test6, test7, test8};
  63. int testsizes[] = {5,5,5,5,5,5,5,5};
  64.  
  65. int output[40];
  66.  
  67. multimerge(test,testsizes,8,output);
  68.  
  69. while(i < 30){
  70. printf("%i\n",output[i++]);
  71. }
  72.  
  73. return 0;
  74. }
  75.  
Success #stdin #stdout 0.02s 1808KB
stdin
Standard input is empty
stdout
21
23
23
24
25
30
31
31
32
33
33
33
34
34
35
36
36
40
41
43
44
44
44
46
46
50
51
51
52
54