fork download
  1. #include <stdio.h>
  2.  
  3. void sortArrayElements(void);
  4. int main() {
  5. int t = 0;
  6. scanf("%d",&t);
  7. for(int i=0; i<t; i++)
  8. {
  9. sortArrayElements();
  10. }
  11. return 0;
  12. }
  13. void sortArrayElements(void)
  14. {
  15. int *array1 = NULL, array1Length = 0, *array2 = NULL, array2Length = 0;
  16. int i = 0, j = 0, k = 0;
  17.  
  18. scanf("%d",&array1Length);
  19. array1 = malloc(array1Length * sizeof(int));
  20. scanf("%d",&array2Length);
  21. array2 = malloc(array2Length * sizeof(int));
  22. for(i =0; i < array1Length; i++)
  23. scanf("%d", &array1[i]);
  24. for(i =0; i < array2Length; i++)
  25. scanf("%d", &array2[i]);
  26.  
  27. for(i = 0, j = 0; i < array1Length; i++)
  28. {
  29. if(array1[i] > array2[j])
  30. {
  31. /*Swap the elements*/
  32. int temp = array1[i];
  33. array1[i] = array2[j];
  34. array2[j] = temp;
  35. if((j+1) < array2Length)//index should not exceed boundary
  36. if(array2[j] > array2[j+1])//if the new entry is greater than next index
  37. j++;//point to the new minimum of sorted part of array2
  38. }
  39. }
  40. // printf("\nafter stage1:");
  41. // for(i = 0; i < array1Length; i++)
  42. // printf("%d ", array1[i]);
  43. // for(i = 0; i < array2Length; i++)
  44. // printf("%d ", array2[i]);
  45. // printf("\n");
  46.  
  47. for(i = 0, k = 0; i < array1Length; i++)
  48. {
  49. if(array1[i] > array2[k])
  50. {
  51. /*Swap the elements*/
  52. int temp = array1[i];
  53. array1[i] = array2[k];
  54. array2[k] = temp;
  55. if(k<j)
  56. if(array2[k] > array2[k+1])//if the new entry is greater than next index
  57. k++;//point to the new minimum of sorted part of array2
  58. }
  59. }
  60. // printf("\nafter stage1.1:");
  61. // for(i = 0; i < array1Length; i++)
  62. // printf("%d ", array1[i]);
  63. // for(i = 0; i < array2Length; i++)
  64. // printf("%d ", array2[i]);
  65. // printf("j:%d\n",j);
  66.  
  67. for(i = 0; i < j; i++)
  68. {
  69. if(array2[i] > array2[j])
  70. {
  71. /*Swap the elements*/
  72. int temp = array2[i];
  73. array2[i] = array2[j];
  74. array2[j] = temp;
  75. if((j+1) < array2Length)//index should not exceed boundary
  76. if(array2[j] > array2[j+1])//if the new entry is greater than next index
  77. j++;//point to the new minimum of sorted part of array2
  78.  
  79. }
  80. }
  81. // printf("\nafter stage 2:");
  82. for(i = 0; i < array1Length; i++)
  83. printf("%d ", array1[i]);
  84. for(i = 0; i < array2Length; i++)
  85. printf("%d ", array2[i]);
  86. printf("\n");
  87. }
Success #stdin #stdout 0s 9424KB
stdin
2
5 4
0 2 6 8 9
1 3 5 7
2 3
10 12
5 18 20
stdout
0 1 2 3 5 6 7 8 9 
5 10 12 18 20