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);
                }
            }    
        }    
    }   
}
11
  • 3
    You are using the same index variable i for the both the for-loop Commented Nov 20, 2017 at 14:39
  • 3
    I want to combine two sorted arrays, so they just need to be compared and printed out I can't understand what that mean. Combining and comparing look like completely different things to me. Elaborate, with a concrete example. Commented Nov 20, 2017 at 14:40
  • both loops contains the same counter variable i Commented Nov 20, 2017 at 14:41
  • Duplication of https://stackoverflow.com/questions/5958169/how-to-merge-two-sorted-arrays-into-a-sorted-array Commented Nov 20, 2017 at 14:41
  • 1
    I don't understand the purpose of adding equal numbers Commented Nov 20, 2017 at 14:43

1 Answer 1

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++];
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.