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
holdand looping whilej >= nElementswhich should never happen.To make room, you need to uses something like:
Added now we discover that we cannot use system calls:
Alternatively, if
arrayCopyis not allowed you will need a loop such as:Note that this code is deliberately untested as this question is likely to be homework.