Java下移数组元素 [英] Java Shifting Array Elements Down

查看:95
本文介绍了Java下移数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在努力编写一个循环,该循环从Array的某个点开始并将其向下推到正确的一个位置,以便可以在现有位置(插入位置)处放置一个新值.

到目前为止,我有一个循环来查找该值到达的位置:

int hold=0;
 for (int j = 0; j < nElements; j++)   
 {
    int temp = list[j];
    if (temp <= value)
    {
       hold = j;  
    }

 }

我现在正在为for循环编写代码,它将所有内容转移过来. 我有:

for (int j = hold; j >= numElements; j--)
 {
     int temp = list[j];
     list[j] = value;

     list[j+1] = temp;

    }

nElements是我存储在数组中的当前int数.

所有这些只是在我调用将整数添加到数组的方法时,在位置0插入第一个数字.再次调用该方法时,根本不会添加数字.

我也不能使用像System.arraycopy()这样的预定义方法.我需要对循环进行编码.

解决方案

您应该使用System.arrayCopy().

实际上您没有复制任何内容,因为您是从hold开始并在j >= nElements时循环,这永远不会发生.

要腾出空间,您需要使用类似以下内容的东西:

System.arrayCopy(list, hold, list, hold+1, nElements - hold - 1);

已添加,现在我们发现我们无法使用系统调用:

或者,如果不允许使用arrayCopy,则需要一个循环,例如:

for ( int i = nElements - 1; i > hold; i-- ) {
  list[i] = list[i-1];
}

请注意,此代码是未经测试的,因为此问题可能是家庭作业.

I am currently struggling writing a loop that starts at a certain point in an Array and pushes it down to the right one spot to that a new value can be placed where the existing one is, an insertion sort.

So far I have a loop that finds which spot the value goes:

int hold=0;
 for (int j = 0; j < nElements; j++)   
 {
    int temp = list[j];
    if (temp <= value)
    {
       hold = j;  
    }

 }

I am now writing for for loop that shifts everything over. I have:

for (int j = hold; j >= numElements; j--)
 {
     int temp = list[j];
     list[j] = value;

     list[j+1] = temp;

    }

nElements is the number of current ints I have stored in the array.

All this is doing is just inserting the first number in spot 0 when I call the method that adds the integer to the array. When the method is called again the number is not added at all.

I also cannot use predefined methods like System.arraycopy() . I need to code the loops.

解决方案

You should be using System.arrayCopy().

You are actually not copying anything because you are starting at hold and looping while j >= nElements which should never happen.

To make room, you need to uses something like:

System.arrayCopy(list, hold, list, hold+1, nElements - hold - 1);

Added now we discover that we cannot use system calls:

Alternatively, if arrayCopy is not allowed you will need a loop such as:

for ( int i = nElements - 1; i > hold; i-- ) {
  list[i] = list[i-1];
}

Note that this code is deliberately untested as this question is likely to be homework.

这篇关于Java下移数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆