简体   繁体   中英

Java rearrange array based on element number

Here is my array:

int[] myArray = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

Let's say I want to move myArray[3] (it could be any element) and myArray[6] (same with this one) to the front of the array while rearranging the back, how can I do this? Example:

This:

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

Into this:

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

To move index x to the front, you need to:

  • Remember what's at index x
  • Copy everything from 0 to x - 1 up one index, eg with System.arrayCopy
  • Set the value at index 0 to be the value you remembered in the first step

For example:

public void moveToHead(int[] values, int index)
{
    // TODO: Argument validation
    int value = values[index];
    System.arraycopy(values, 0, values, 1, index - 1);
    values[0] = value;
}

Note that System.arraycopy handles the copying appropriately:

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.

Your original example mentioned two elements - while you could potentially do all of this more efficiently knowing both elements in advance, it would be far, far simpler to model this as two moveToHead calls. You need to take care about the ordering - for example, if you want to move index 6 to the head first, you'll need to then move index 4 rather than index 3, to take account of the first move.

An other solution may be to transform your array into a list thanks to the asList method and simply use the remove and add methods:

List<Integer> myList = new ArrayList<Integer>(Arrays.asList(myArray));
myList.add(myList.remove(myIndex));

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