PTA 7-19 数组元素循环右移问题(JAVA)

题目要求如下:
在这里插入图片描述
实现思路:如果想要移动第一位元素到第二位,那么就要将第二位先移动到第三位,依次递归,最后是移动最后一位元素到第一位。move函数每次移动一位。为避免第一位元素丢失,先将其存放在temp中,将其他元素移动结束后在赋值给第二个元素。

/*2020年11月14日09:01:05*/
import java.util.Scanner;

public class Main {
    
    
    public static void main(String[] args) {
    
    
        Scanner scan = new Scanner(System.in);
        int num, right;   //输入数组长度、右移位数
        num = scan.nextInt();
        right = scan.nextInt();
        int[] a = new int[num];
        for (int i = 0; i < num; i++)  //初始化数组
            a[i] = scan.nextInt();

        for(int i = 0; i<right ;i++) {
    
       //右移循环,每次右移一位
            int temp = a[0];   //把第一位元素的值暂存在temp中,否则会被最后一位元素右移到第一位时覆盖
            move(a, 0, num);
            a[1] = temp;
        }
        for (int i = 0; i < num; i++)  //输出
            if(i!=num-1)
                System.out.print(a[i]+" ");
            else
                System.out.println(a[i]);
    }
//定义函数move,实现对给定数组中的索引为x的元素右移一位
    public static void move(int[] b,int x,int len) {
    
    
        if(x==len-1)   //如果要移动的元素为最后一位,直接将其移动到第一位
            b[0] = b[x];
        else {
    
    
            move(b, x + 1, len);   //否则递归
            b[x+1]=b[x];		  //右移一位
        }
    }
}

猜你喜欢

转载自blog.csdn.net/m0_47470899/article/details/109686320