Reputation: 1723
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}
Upvotes: 4
Views: 4056
Reputation: 53819
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));
Upvotes: 2
Reputation: 1500485
To move index x
to the front, you need to:
x
0
to x - 1
up one index, e.g. with System.arrayCopy
0
to be the value you remembered in the first stepFor 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.
Upvotes: 4