有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java分割数组将第一部分添加到末尾

There is a given array and split it from a specified position, and move the first part of the array add to the end. 
 Input : arr[] = {12, 10, 5, 6, 52, 36}
            k = 2
Output : arr[] = {5, 6, 52, 36, 12, 10}

public class Split_array_add_first_part_to_the_end {
    public static void main(String[] args) {  
        int a[]= {12,10,5,6,52,36};
int i,j;
int n=a.length;
int x=a[0];

for(i=0;i<n-1;i++)
{
    int temp=a[i];
    a[i]=a[i+1];
    temp=a[i];
    
}
a[n-1]=x;
for(i=0;i<n;++i)
{
    System.out.println(a[i]);
}
    
    }
}

a[n-1]=x->;这将取代12 如何旋转第10个值

I am getting output like this 10 5 6 52 36 12

Please explain the flow of execution and what mistake I made


共 (1) 个答案

  1. # 1 楼答案

        int a[] = {12, 10, 5, 6, 52, 36};
    
        // use int declaration in for-loop.
        for (int k = 0; k < 2; k++) {
            for (int i = 0; i < a.length - 1; i++) {
                int temp = a[i]; // swap number to end per iteration
                a[i] = a[i + 1];
                a[i + 1] = temp;
            }
        }
    
        for (int i = 0; i < a.length; ++i) {
            System.out.println(a[i]);
        }
    

    你差点就成功了。这个解决方案正在发挥作用 我已经看到,您将索引声明为for循环之外的变量(不是必需的)。我建议你从小处着手,把问题一一分解

    我猜你想做的主要事情是每k次迭代循环一次数组。我将从编程开始:

    1. 打印每个项目
    2. 交换一件物品
    3. 交换每个索引项(表示交换到末尾)
    4. 只需用另一个循环(k循环)将循环包围k次即可

    我的方法是使用集合和轮换来进一步缩短它

        Integer a[] = {12, 10, 5, 6, 52, 36};
        List<Integer> list = Arrays.asList(a);
        Collections.rotate(list, -2); // Rotate the list backwards by two elements
        System.out.println(Arrays.toString(a));