fork download
  1. #include <stdio.h>
  2.  
  3. int lSize = 4;
  4. int rSize = 3;
  5. int L[4] = {1, 3, 6, 7};
  6. int R[4] = {1, 2, 4};
  7. int finalArray[7];
  8.  
  9. void merge()
  10. {
  11. int lIndx = 0;
  12. int rIndx = 0;
  13. int i = 0;
  14.  
  15. for (i = 0; i < (lSize + rSize); i++) {
  16. if (L[lIndx] <= R[rIndx]) {
  17. finalArray[i] = L[lIndx++];
  18. if (lIndx == lSize) {
  19. break;
  20. }
  21. } else {
  22. finalArray[i] = R[rIndx++];
  23. if (rIndx == rSize) {
  24. break;
  25. }
  26. }
  27. }
  28.  
  29. i++;
  30. if (lIndx != lSize) {
  31. while(1) {
  32. finalArray[i++] = L[lIndx++];
  33.  
  34. if (lIndx == lSize) {
  35. return;
  36. }
  37. }
  38. }
  39. if (rIndx != rSize) {
  40. while(1) {
  41. finalArray[i++] = R[rIndx++];
  42.  
  43. if (rIndx == rSize) {
  44. return;
  45. }
  46. }
  47. }
  48. }
  49.  
  50. void display()
  51. {
  52. int i = 0;
  53.  
  54. printf("\n\nArray1: ");
  55. for (i = 0; i < lSize; i++) {
  56. printf("%d ", L[i]);
  57. }
  58.  
  59. printf("\nArray2: ");
  60. for (i = 0; i < rSize; i++) {
  61. printf("%d ", R[i]);
  62. }
  63.  
  64. printf("\nMerge array: ");
  65. for (i = 0; i < lSize+rSize; i++) {
  66. printf("%d ", finalArray[i]);
  67. }
  68. }
  69.  
  70. int main()
  71. {
  72. // Test 1
  73. merge();
  74. display();
  75.  
  76. // Test 2
  77. R[0] = 1;
  78. R[1] = 3;
  79. R[2] = 6;
  80. R[3] = 7;
  81. L[0] = 1;
  82. L[1] = 2;
  83. L[2] = 4;
  84. lSize = 3;
  85. rSize = 4;
  86. merge();
  87. display();
  88.  
  89. // test 3
  90. L[0] = 1;
  91. R[0] = 1;
  92. lSize = 1;
  93. rSize = 1;
  94. merge();
  95. display();
  96.  
  97. return 0;
  98. }
  99.  
Success #stdin #stdout 0s 2248KB
stdin
Standard input is empty
stdout

Array1: 1 3 6 7 
Array2: 1 2 4 
Merge array: 1 1 2 3 4 6 7 

Array1: 1 2 4 
Array2: 1 3 6 7 
Merge array: 1 1 2 3 4 6 7 

Array1: 1 
Array2: 1 
Merge array: 1 1