1. 首页
  2. 软件开发
  3. 改变数组中数字的位置(前到后,后到前)

改变数组中数字的位置(前到后,后到前)

  • 发布于 2024-09-21
  • 0 次阅读

改变数组的位置:例如输入3,1 2 3 4 5=>4 5 1 2 3;

2 ,1 2 3 4 5=>3 4 5 1 2;

思路:1.先把要后移的数据赋值到新数组里保护起来

2.把要前移的数据提前

3.把保护的数据再赋给原数据的后几位

import java.util.Scanner;

public class shuzugai {
    //改变数组位置
    public static void main(String[] args) {
        //定义数组
        int[] a = {5, 9, 8, 6, 7};
        System.out.println("5,9,8,6,7");
        System.out.println("输入要移动位置的下标:");
        Scanner scanner = new Scanner(System.in);
        //将要改变位置的数的角标赋给dex
        int dex = scanner.nextInt();
        //定义新的数组
        int[] a1 = new int[5];
        //将要放到后面的数字先保护起来
        //用循环将要保护的数字放到新建的数组里
        for (int i = 0; i < dex; i++) {
            a1[i] = a[i];
        }
        //将后面的数字提到最前面来
        //用循环把后面的数字往前覆盖
        int b = 0;
        for (int j = dex; j < a.length; j++) {
            a[b++] = a[j];
        }
       //用循环将保护起来的数字接到数组的后面
        for (int j = 0; j < dex; j++) {
            a[b++] = a1[j];
        }
        System.out.println("改前");
        System.out.println("5,9,8,6,7");
        System.out.println("改后");
        //输出
        for (int j = 0; j < a.length; j++) {
            System.out.print(" " + a[j]);
        }
    }
}

输出结果:

5,9,8,6,7
输入要移动位置的下标:
4
改前
5,9,8,6,7
改后
7 5 9 8 6
Process finished with exit code 0

原文链接: https://blog.csdn.net/daibadetianshi/article/details/136766403