是否存在在圆形的int数组上执行左移的现有方法?
具体来说,给定一个包含4个项目{1,2,3,4}且移位量为2 的数组,我想要一个方法将前两个字母移动到数组的后面,使它看起来如下:{3,4,1,2}.
这个算法可以将圆形数组移动一个吗?
algShiftByOne(Array)
{
temp=array[0];
i=1
while(i < Array.length - 1) // Loop from 1 up to array.length == last index
{
// If there is no exception i assume it copies value from
// initial array starting from 1 up to array.length
Array[i - 1] = Array[i];
i++;
}
Array[Array.length]=temp;
}
Run Code Online (Sandbox Code Playgroud)
这是我的目标...(这是一个ideone.com演示)
import java.util.Arrays;
public class Test {
public static void circularShiftLeft(int[] arr) {
if (arr.length == 0)
return;
int first = arr[0];
System.arraycopy(arr, 1, arr, 0, arr.length - 1);
arr[arr.length - 1] = first;
}
public static void main(String[] arg) {
int[] arr = { 1, 2, 3, 4 };
System.out.println(Arrays.toString(arr));
circularShiftLeft(arr);
System.out.println(Arrays.toString(arr));
}
}
Run Code Online (Sandbox Code Playgroud)