3

Lets say I have the array:

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

How can I move an element based its index to the front? Example:

Move element taco[5] to the front should produce this:

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

EDIT: Does it make a difference if the ints are instead objects?

3
  • 2
    Thank you for the invaluable input. Commented Dec 22, 2011 at 0:58
  • 1
    And no, this is for a personal project I am working on. I have never taken a programming course. Commented Dec 22, 2011 at 0:59
  • Do you need to use an array, can you use an arrayList of Integer? Commented Dec 22, 2011 at 0:59

7 Answers 7

7
  1. Store the value you're moving in a temporary int variable
  2. Copy all elements down the array, one at a time, in a loop
  3. Assign the value you stored in the temporary variable to the new position (the front of the array, taco[0], in this case)

It does not make any difference if it's an array of int values, or objects. The algorithm is the same. Since an array of Object references would literally be an array of 32-bit or 64-bit memory references, you're effectively still copying integers around.

Here is code that would do it - there are several ways to do this, but this is the basic idea:

public int[] moveValueAtIndexToFront(int[] arrayToBeShifted, int index) {
  int valueBeingMoved = originalArray[index];

  for (int i = index; i > 0; i--) {
    arrayToBeShifted[i] = arrayToBeShifted[i-1];
  }

  arrayToBeShifted[0] = valueBeingMoved;

  return arrayToBeShifted;
}
  • This will moves all values at the specified index backward in the array by one position, and places the value being moved at the front.
  • If the index passed in is 0, then nothing winds up being moved.
  • If the index passed in happens to be the the index of the very last item in the array, every single item in the array needs to be shifted. If you're dealing with large arrays, and you're doing a lot of shifts of values late in the array, this becomes really inefficient, really fast.

You could also take a look at the source code of arraycopy if you're curious, via the OpenJDK project.

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

5 Comments

How would you do this with code? Would you implement System.arraycopy?
@ConnerRuhl - unless you have convincing evidence to the contrary (e.g. you've profiled your application, and this code is a clear bottleneck) the performance of arraycopy versus a simple loop is irrelevant.
arraycopy also allocates an extra array worth of memory. This is probably not a big deal unless you're dealing with very large arrays, or have some other reason to believe that this would become a problem. As Stephen C says, unless you've got convincing evidence in your specific app, performance shouldn't be a concern here.
@normalocity - actually, System.arraycopy does NOT allocate any memory. Perhaps you are confusing it with something else.
Hm, perhaps I am. My mistake.
5
int[] taco = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int index = 5;
int temp = taco[index];
for(int i = index; i > 0; i--) {
    taco[i] = taco[i-1];
}
taco[0] = temp;

Comments

2
int[] taco = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int indexTarget = 7;
int valueAtIndex = taco[indexTarget];
for(int i = indexTarget; i > 0; i--){
   taco[i] = taco[i-1];
}
taco[0] = valueAtIndex;

Comments

1

Because Java arrays have a fixed size, you should create a new array, and loop through the elements:

/**
 * Moves the element wanted to the front of the array, and returns a new array.
 * @param array The array to adjust
 * @param position The position of the element
 * @return The adjusted array
 */
private int[] moveElement (int[] array, int position)
{
    // Create temporary array to hold values
    int[] tempArray = new int[array.length];

    // Set first value to your wanted element
    tempArray[0] = array[position];

    // Set values of array before array[position]
    for (int tempPosition = 0; tempPosition < position; tempPosition++)
    {
        tempArray[tempPosition + 1] = array[tempPosition];
    }

    // Set values of array after array[position]
    for (int tempPosition = position + 1; tempPosition < array.length; tempPosition++)
    {
        tempArray[tempPosition] = array[tempPosition];
    }

    // Return newly created array
    return tempArray;
}

Comments

1

for the new added question:no it doesnot make any difference ,you just need to use a temp variable of object type variable instead of int variable.

Comments

0
private int[] moveToZero (int[] workOnArray, int position) { 
 workOnArray[0]=workOnArray[position]+workOnArray[0];
 workOnArray[position]=workOnArray[0]-workOnArray[position];
 workOnArray[0]=workOnArray[0]-workOnArray[position];
 return workOnArray;
}

1 Comment

you exchange the array[0] and array[index],but it is not fit for this question.
0

I wrote a sample, you can check it:

   public static void main(String[] args) {
        int[] taco = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
        int index = 2;
        int tmp = taco[0];
        int preValue;
        taco[0]=taco[index];
        for(int i=1,n=taco.length;i<n;i++){
            if(i==index+1)
                break;
            preValue = taco[i];
            taco[i]=tmp;
            tmp=preValue;
        }
        for(int i=0,n=taco.length;i<n;i++){
            System.out.println(taco[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.