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?
Solution 1:
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);
Solution 2:
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;
Solution 3:
You can just use Collections.rotate(List<?> list, int distance)
Use Arrays.asList(array)
to convert to List
more info at: https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#rotate(java.util.List,%20int)
Solution 4:
Instead of shifting by one position you can make this function more general using module like this.
int[] original = { 1, 2, 3, 4, 5, 6 };
int[] reordered = new int[original.length];
int shift = 1;
for(int i=0; i<original.length;i++)
reordered[i] = original[(shift+i)%original.length];