void sort(int a[], int b[], int m, int n)
{
int e = m + n;
while(m >=0 && n >=0)
{
if(a[m] > b[n])
{
a[e] = a[m];
m--;
e--;
}
else if(a[e] < b[n])
{
a[e] = b[n];
n--;
e--;
}
else
{
a[e] = b[n];
e--;
n--;
m--;
}
}
}
public static void main(String[] args) {
SortSorted obj = new SortSorted();
int a[] = new int [6];
int b[] = new int [3];
a[0] = 1;
a[1] = 2;
a[2] = 3;
b[0] = 2;
b[1] = 7;
b[2] = 8;
obj.sort(a,b, 2, 2);
}
I get the output as 1 2 3 7 8 0 instead of 1 2 2 3 7 8 with and without adding the 3rd else condition.
You start
etoo low, it should bem + n + 1.Think about it, for two three-element arrays,
mandnare both two. That means that you’ll start at four withm + nwhereas, with a six-element result, you should be starting at five.This is a relatively simple off-by-one error.
You can also fix the other problem of losing values when they’re equal by simply ignoring the equality. Choose
aif it’s greater than or equal, otherwise chooseb.And your loop continuation logic is wrong, which you would see if you exhausted
afirst (usea = {2, 2, 3}andb = {1, 7, 8}to see what I mean). You only continue if bothaandbhave elements left. You should continue while either of them have elements left.You can fix this by leaving that loop as-is but adding two other loops (only one of which will actually do anything) to exhaust the other list.
As support, I provide the following C code (since I’m faster with that than Java, but the sort routine itself should be pretty much identical):
And some test code:
The output of this is:
as expected.
And the equivalent Java code:
along with its test suite:
In fact, since you’re writing to
aanyway, you can actually leave out that middle loop (thewhile (m >= 0)one). That’s because, in that situation, you’re simply transferring elements to themselves.I’ll leave it in since it becomes important if the array you’re writing to is not in-place but you can remove it if you wish for your particular situation.