Java Shifting Array Elements Down

3.1k views Asked by At

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

There are 1 answers

7
OldCurmudgeon On

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.