What you have to do is to take always next_element
from original structure (array, list) and place it top.(others elements goes down by 1 till next element
initial position)
next_element
is start from second_position and it's increment by 1 till the end of structure (length or size)
import java.util.Arrays;
import java.util.stream.Collectors;
public class Test {
public static void main(String[] args)
{
int a1[] = {1,2,3,4,5};
new Test().compute(a1);
int a2[] = {5,4,3,2,1};
new Test().compute(a2);
}
public void compute(int[] a)
{
for(int i=1;i<a.length;i++)
{
//i : next_element which will be place always on first_position
int temp= a[i];
//j : current_element (iterate by till next_element)
for(int j=i; j>0; j--)
{
a[j] = a[j-1];
}
a[0] = temp;
String str = Arrays.stream(a).boxed().map(t->String.valueOf(t)).collect(Collectors.joining(","));
System.out.println("step="+i+": array="+str);
}
}
}
Output
step=1: array=2,1,3,4,5
step=2: array=3,2,1,4,5
step=3: array=4,3,2,1,5
step=4: array=5,4,3,2,1
and (reverse)
step=1: array=4,5,3,2,1
step=2: array=3,4,5,2,1
step=3: array=2,3,4,5,1
step=4: array=1,2,3,4,5