Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java, Shifting Elements in an Array

I have an array of objects in Java, and I am trying to pull one element to the top and shift the rest down by one.

Assume I have an array of size 10, and I am trying to pull the fifth element. The fifth element goes into position 0 and all elements from 0 to 5 will be shifted down by one.

This algorithm does not properly shift the elements:

Object temp = pool[position];

for (int i = 0; i < position; i++) {                
    array[i+1] = array[i];
}
array[0] = temp;

How do I do it correctly?

like image 507
darksky Avatar asked Nov 01 '11 18:11

darksky


People also ask

How do you shift elements in an array to the left?

The array can be left rotated by shifting its elements to a position prior to them which can be accomplished by looping through the array and perform the operation arr[j] = arr[j+1]. The first element of the array will be added to the last of rotated array.

What is shifting in array?

shift() The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.


2 Answers

Logically it does not work and you should reverse your loop:

for (int i = position-1; i >= 0; i--) {                
    array[i+1] = array[i];
}

Alternatively you can use

System.arraycopy(array, 0, array, 1, position);
like image 134
Howard Avatar answered Oct 07 '22 05:10

Howard


Assuming your array is {10,20,30,40,50,60,70,80,90,100}

What your loop does is:

Iteration 1: array[1] = array[0]; {10,10,30,40,50,60,70,80,90,100}

Iteration 2: array[2] = array[1]; {10,10,10,40,50,60,70,80,90,100}

What you should be doing is

Object temp = pool[position];

for (int i = (position - 1); i >= 0; i--) {                
    array[i+1] = array[i];
}

array[0] = temp;
like image 33
Komal Padia Avatar answered Oct 07 '22 06:10

Komal Padia