# Thread: Mergin two arrays problem.

1. Member Join Date
Jun 2008
Posts
20
Rep Power
0

## Mergin two arrays problem.

In this hw problem, we are told that two arrays are already sorted and we need to merge them.

Here is my code:
Java Code:
```int length = a.length+ b.length;
int[] c = new int[length];
for(int i =0; i < a.length; i++)
c[i] = a[i];
for(int j = a.length-1; j < length;j++){
for(int k = 0; k < b.length; k++){
c[j] = b[k];
}
}
java.util.Arrays.sort(c);
return c;

}```
The issues given were:
----------------------------------------------------------------
⇒*****Exception java.lang.ArrayIndexOutOfBoundsException: -1
***************occurred
*****⇒*****result is incorrect
*****⇒*****result is incorrect
*****⇒*****result is incorrect
*****⇒*****result is incorrect
*****⇒*****result is incorrect

Fails When:
*****⇒*****arr1[i] == arr21[i]
*****⇒*****arr1[length-1]
-----------------------------------------------------------

I cannot see what is wrong. can anyone help?  Reply With Quote

2. ## What line in your code is throwing the exception?
Since the value of the index j shown in the error message is -1, the only place I see that can happen is if length of a == 0
for(int j = a.length-1; j < length;j++){

If you want help with your algorithm, write some comments in your code describing what it is you are trying to do and how each of the statements does a step of the process.  Reply With Quote

3. Senior Member Join Date
May 2008
Location
Makati, Philippines
Posts
234
Rep Power
13

## I think there is a problem in your algorithm.

Here is a suggestion.

Java Code:
```int temp =0;
for(int i = temp; i < a.length; i++) {
c[i] = a[i];
temp = i;
}
for(int i = temp; i < length;i++){
c[i] = b[i-temp];
}```
Try this Algo  Reply With Quote

4. Member Join Date
Jul 2008
Posts
1
Rep Power
0

## Hellooooo

The problem is with the for loop.

int length = a.length+ b.length;
int[] c = new int[length];
for(int i =0; i < a.length; i++)
c[i] = a[i];
for(int j = a.length-1; j < length;j++){
for(int k = 0; k < b.length; k++){
c[j] = b[k];
}
}

int length = a.length+ b.length;
int k=0;
int[] c = new int[length];
for(int i =0; i < a.length; i++)
c[i] = a[i];

k=a.length;

for(int j=0; j < b.length; j++,k++)
{
c[k]=b[j];
}
Last edited by Mythili; 07-09-2008 at 01:29 PM.  Reply With Quote

5. ## "need to merge them."
Seems to me your solution is not in the spirit of the assignment. I would think the assignment would be to create a new array large enough to hold both the other arrays and then to go thru the two arrays moving the contents from them to the output array by testing which one was smaller (assuming ascending sequence). By calling sort YOU are not doing the merge, the sort program is.  Reply With Quote

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•