rb612
rb612

Reputation: 5573

How to to keep this merge array method in-bounds?

I have to write a method that combines two arrays that are already in ascending order into one array sorted in ascending order. However, they are different lengths and so incrementing brings them out of bounds.

Visualization

int[] mergeTwo(int[] nums1, int[] nums2) {
      int[] arr = new int[nums1.length+nums2.length];

  int index_1=0;
  int index_2=0;
  int content_1=0;
  int content_2=0;
  for(int steps=0;steps<arr.length&&index_1<nums1.length&&index_2<nums2.length;steps++) {
    content_1=nums1[index_1];
    content_2=nums2[index_2];

    if(content_1<content_2) {

      arr[steps]=content_1;
      index_1++;

    }

    if(content_1>content_2) {

      arr[steps]=content_2;
      index_2++;

    }

  }

  return arr;  
}

What do I need to fix to make this method work? Thanks so much!

Upvotes: 0

Views: 35

Answers (1)

Thiyagu
Thiyagu

Reputation: 17900

After you break out of loop add the remaining elements(from one of the arrays) to the final array

while(index_1  < nums1.length)
{

    arr[steps] = nums1[index_1];
    index_1++;
    steps++;
}
while(index_2  < nums2.length)
{
    arr[steps] = nums2[index_2];
    index_2++;
    steps++;
}

Upvotes: 1

Related Questions