package datastruct.usearray; import java.util.Scanner; public class Shift_k { private static void shift_method(int array[],int k) { int n=array.length-1; k=k%n; //为了防止k>n ,右移K位和右移k%n的结果是一样的 shift_method(array, 0, n-k); shift_method(array, n-k+1, n); shift_method(array, 0, n); System.out.println("右移"+k+"位的结果为:"); for (int i : array) { System.out.print(i+" "); } } private static void shift_method(int array[],int begin,int end) { int temp; while (begin =end 结束 temp=array[begin]; array[begin]=array[end]; array[end]=temp; begin++; end--; } } public static void main(String[] args) { Scanner sc=new Scanner(System.in); System.out.println("输入数组元素个数:"); int n=sc.nextInt(); int array[]=new int[n]; System.out.println("输入"+n+"个数组元素:"); for (int i = 0; i < n; i++) { array[i]=sc.nextInt(); } System.out.println("输入移动的位数:"); int k=sc.nextInt(); shift_method(array, k); } }
运行结果如下: