Java Shifting Array Elements Down

好久不见. 提交于 2019-12-11 04:09:24

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/14865802/java-shifting-array-elements-down

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!