简体   繁体   中英

Rearranging an array in Java

If I have an array:

int[] myArray = new int[10]
for (int i = 0; i < myArray.length; i++) {
    myArray[i] = i;
}

//resulting array: {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

How can I move everything behing the 4 up one space, and send the 4 to the back? Example:

this:

{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

into this:

{0, 1, 2, 3, 5, 6, 7, 8, 9, 4}

How about this:

int[] myArray = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
System.arraycopy(myArray, 5, myArray, 4, 5);
myArray[myArray.length-1] = 4;

In the above code, I'm using the arraycopy method to copy a range of 5 numbers starting from index 5, to index 4 in the array, and then simply set a 4 in the last position.

Notice that using arraycopy is much faster than copying the values in a loop, since it's usually implemented as a native operation which copies memory positions.

EDIT :

A more generic solution, a method for sending to the back a given position in the array:

public static void sendBack(int[] array, int idx) {
    int value = array[idx];
    System.arraycopy(array, idx+1, array, idx, array.length-idx-1);
    array[array.length-1] = value;
}

For your example, call it like this:

sendBack(myArray, 4);
// now myArray is {0, 1, 2, 3, 5, 6, 7, 8, 9, 4}

Like this?

int start = 4;
int temp = myArray[start];
for(int i = start; i < myArray.length - 1; i++) {
    myArray[i] = myArray[i+1];
}
myArray[myArray.length-1] = temp;

It's the fastest way I can guess...

使用System.arraycopy

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM