简体   繁体   中英

Why is my Java program to merge 2 integer arrays only giving correct output to a certain point?

I have these 2 arrays:

array A [-5, -4, -3, -2, -1, 6, 7, 8, 9, 10, 11] array B [-33, -22, -11, 44, 55, 66, 77, 88]

As you can see, array A and array B are both sorted. I have to merge them into a third array (array C ) which should be sorted. (I can't use any array sort function though)

Here is my while loop:

 int[] c = new int[a.length + b.length];
   int aCount = 0;
   int bCount = 0;
   int cIndex = 0;

   while (aCount < a.length && bCount < b.length) {
      if (a[aCount] < b[bCount]) {
         c[cIndex] = a[aCount];
         cIndex++;
         aCount++;
      }
      else {
         c[cIndex] = b[bCount];
         cIndex++;
         bCount++;
      }
   }

And this is my output:

[-33, -22, -11, -5, -4, -3, -2, -1, 6, 7, 8, 9, 10, 11, 0, 0, 0, 0, 0]

It is working correctly until it reaches 11, but then after that it only displays 0's when it should be 44,55,66,77,88.

What am I missing?

You only merge the two arrays to the point, where you reach the end of array a. Afterwards the while loop breaks off. You'll have to insert the remaining values of the other array.

int[] tmp = (aCount == a.length ? b : a);
int ct = (aCount == a.length ? bCount : aCount);

for(; ct < tmp.length ; ct++)
     c[cIndex++] = temp[ct];

After you pick each element from a and b you increment the respective index. When you get to the last element of a (namely a[10] ) you increment the index again, and now aCount is no longer less than a.length . So you skip the entire rest of the process.

The zeros are the default value of c before values are set. Since you're not setting the values, they remain 0.

Your loop condition ( aCount < a.length && bCount < b.length ) becomes false as soon as one of the indices reaches the end of the array. Since you only increment one of the indices in the loop, that means there is at least 1 element in the other array that needs to be inserted to c .

You can add the following code to add the missing elements too:

// add elements missing from first array
while (aCount < a.length) {
     c[cIndex] = a[aCount];
     cIndex++;
     aCount++;
}

// add elements missing from second array
while (bCount < b.length) {
     c[cIndex] = b[bCount];
     cIndex++;
     bCount++;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM