0

I want to combine two sorted arrays, so they just need to be compared and printed out. The problem I have is, that the output is wrong, because the programm just goes through the second for-loop. What do I have to do to make it work?

result = {1,2,3,3,3,5,5,6,7,8,9,9,10}

    public static void main(String[] args) {

        int[] array1 = { 1, 3, 3, 5, 6, 9 };
        int[] array2 = { 2, 3, 5, 7, 8, 9, 10 };
        int i;
        int j;
        int a;
        int b;

        for (j = 0; j < array1.length; j++) {
            a = array1[j];
            for (i = 0; i < array2.length; i++) {
                b = array2[i];
                if (a < b) {
                    System.out.print(a);
                } else if (b < a) {
                    System.out.print(b);
                } else if (a == b) {
                    System.out.print(a + b);
                }
            }    
        }    
    }   
}
JacobBalb
  • 43
  • 5

1 Answers1

0

algo --

int i=0, j=0, k=0
int[] result = new int[arr1.length+arr2.length];
while (i<arr1.length && j<arr2.length)  {
    if(arr1[i] <= arr2[j]) {
        result[k++] = arr1[i++];
        // or if u just want to print do a sysout. 
    } else {
        result[k++] = arr2[j++];
    }
} 

while(i<arr1.length) 
     result[k++] = arr1[i++];

while(j<arr2.length) 
     result[k++] = arr2[j++];
ajc
  • 1,685
  • 14
  • 34