# Mergin two arrays problem.

• 07-08-2008, 09:55 PM
frasifrasi
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:
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[13] is incorrect
*****⇒*****result[2] is incorrect
*****⇒*****result[3] is incorrect
*****⇒*****result[4] is incorrect
*****⇒*****result[5] is incorrect

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

I cannot see what is wrong. can anyone help?
• 07-08-2008, 11:54 PM
Norm
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.
• 07-09-2008, 02:50 AM
Eku
I think there is a problem in your algorithm.

Here is a suggestion.

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
• 07-09-2008, 01:25 PM
Mythili
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];
}
• 07-09-2008, 03:29 PM
Norm
"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.