Java向右旋转数组元素
在此程序中,我们需要将数组元素向右旋转指定的次数。如果将数组的所有元素向右移动一个位置,则称该数组为右旋转。一种方法是通过将数组的每个元素移至其下一个位置来遍历数组。数组的最后一个元素将成为旋转数组的第一个元素。
考虑上述数组,如果n为1,则该数组的所有元素将向右移一个位置,即数组的第一个元素将处于第二位置,第二个元素将移至第三位置,依此类推。数组的最后一个元素将成为数组的第一个元素。
算法
步骤1: START
步骤2: 初始化 arr [] = {1、2、3、4、5}。
步骤3: SET n = 3
步骤4: 打印"原始数组"
步骤5: 重复步骤6,直到i < arr.length
for(i = 0; i < arr.length; i++)
步骤6: 打印 arr[i]
步骤7: 直到i < n
重复步骤8至步骤12 //for(i = 0; i < n; i++)
步骤8: 定义j,last。
步骤9: last = arr[arr.length-1]
步骤10: 重复步骤11直到j > 0
////for(j = arr.length-1; j> 0; j-)
步骤11: arr[j] = arr [j-1]
步骤12: arr[0] = last
步骤13: 打印"右旋转后的数组"
步骤14: 重复步骤15,直到i < arr.length
////for(i = 0; i < arr.length; i ++)
步骤15: 打印arr[i]
STEP 16: END
程序:
class RotateRight {
public static void main(String[] args) {
//Initialize array
int [] arr = new int [] {1, 2, 3, 4, 5};
//n determine the number of times an array should be rotated.
int n = 3;
//Displays original array
System.out.println("Original array: ");
for (int i = 0;i <arr.length;i++) {
System.out.print(arr[i] + " ");
}
//Rotate the given array by n times toward right
for(int i = 0;i <n;i++){
int j, last;
//Stores the last element of array
last = arr[arr.length-1];
for(j = arr.length-1;j >0;j--){
//Shift element of array by one
arr[j] = arr[j-1];
}
//Last element of array will be added to the start of array.
arr[0] = last;
}
System.out.println();
//Displays resulting array after rotation
System.out.println("Array after right rotation: ");
for(int i = 0;i<arr.length;i++){
System.out.print(arr[i] + " ");
}
}
}
输出:
Original Array:
1 2 3 4 5
Array after right rotation:
3 4 5 1 2