fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. int[] a = new int[] {1,2,3,4};
  13. int[] b = new int[] {2,4,5,6,10,7};
  14. int[] result = merge(a,b);
  15. System.out.println(Arrays.toString(result));
  16. }
  17.  
  18. public static int[] merge(int[] arr1, int[] arr2)
  19. {
  20. int outputSize = arr1.length + arr2.length;
  21. int[] output = new int[outputSize];
  22. int j = 0;
  23. int i = 0;
  24.  
  25. for (int k = 0; k < outputSize; k++)
  26. {
  27.  
  28. if (i >= arr1.length) {
  29. while (i < outputSize) {
  30. output[k] = arr1[i];
  31. i++;
  32. k++;
  33. break;
  34. }
  35. } else if (j >= arr2.length) {
  36. System.out.println("j's end");
  37. while (j < outputSize) {
  38. output[k] = arr2[j];
  39. j++;
  40. k++;
  41. }
  42. }
  43. if (arr1[i] < arr2[j]) {
  44. output[k] = arr1[i];
  45. i++;
  46. }
  47.  
  48. else if (arr2[j] < arr1[i]) {
  49. output[k] = arr2[j];
  50. j++;
  51. }
  52.  
  53. else {
  54. output[k] = arr1[i];
  55. k++;
  56. output[k] = arr2[j];
  57. i++;
  58. j++;
  59.  
  60. }
  61. System.out.println(Arrays.toString(output));
  62.  
  63.  
  64. }
  65. return output;
  66.  
  67. }
  68. }
Runtime error #stdin #stdout #stderr 0.1s 320512KB
stdin
Standard input is empty
stdout
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[1, 2, 2, 0, 0, 0, 0, 0, 0, 0]
[1, 2, 2, 3, 0, 0, 0, 0, 0, 0]
[1, 2, 2, 3, 4, 4, 0, 0, 0, 0]
stderr
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
	at Ideone.merge(Main.java:30)
	at Ideone.main(Main.java:14)