1

I need help rewriting a function so that System.arraycopy() does what the function does.

For example, my code:

for( int k = 0; k <= i - 1; k++ ) {
    a[ j + k ] = a[ j + k + 1 ];
}

is equivalent to:

System.arraycopy( a, j + 1, a, j, i );

But I can't figure out how to do this for:

for ( int k = n; k > i; k-- ) {
    a[ j + k ] = a[ j + k - 1 ];
}

Thanks for any input.

1
  • 1
    What's that second loop supposed to be doing? Is j+k a legal subscript when j+k > n-1? Commented Oct 19, 2014 at 19:59

2 Answers 2

1

Let's simplify first, since your second loop seems to be a little more complex than necessary. With n=3, i=1, j=2, your loop would transform a=[1,2,3,4,5,6,7] into a=[1,2,3,4,4,5,7]. In other words, the loop shifts n-i elements one position to the right, starting on index j+i. So, actually you need only two parameters instead of three. (Let's define them to be x=n-i and y=j+i.)

Now, given the following excerpt from the javadoc on System.arraycopy()

If the src and dest arguments refer to the same array object, then the copying is performed as if the components at positions srcPos through srcPos+length-1 were first copied to a temporary array with length components and then the contents of the temporary array were copied into positions destPos through destPos+length-1 of the destination array.

I conclude that System.arraycopy(a, y, a, y+1, x); does what you want. Or, if the variables you use are a given, System.arraycopy(a, j+i, a, j+i+1, n-i);.

I didn't test it, so let me know if it works ;)

Sign up to request clarification or add additional context in comments.

Comments

0

It looks like your 2nd loop intends to move elements i (exclusive) through n (inclusive) one position to the right:

System.arraycopy(a, i + 1, a, i + 2, n - i);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.