Error code:
Locate the subscript index that should be inserted
for (int i = 0; I <array.length; i++) {
if (Num<array[i];) {
index = i;
}
}
for (int i = index; i<array.length-1; i++) {
ARRAY[I+1] = Array[i];
}
Array[index] = num;
for (int i = 0; i<array.length; i++) {
System.out.print (array[i]+ "\ t");
}
Analysis: After entering 2, after the correct insertion of 2, 2 after the elements are all changed to 3, because the subscript index after the value is assigned to the initial index of the underlying value. The loop also continues to assign the value of index to the back, resulting in the result. Therefore, the code loop statement has errors that need to be improved.
Correct code:
Locate the subscript index that should be inserted
for (int i = 0; I <array.length; i++) {
if (Num<array[i];) {
index = i;
}
}
After inserting, the index of each element after the subscript will also add 1
for (int i = array.length-2; i>index-1; i--) {
ARRAY[I+1] = Array[i];
}
Array[index] = num;
for (int i = 0; i<array.length; i++) {
System.out.print (array[i]+ "\ t");
}
Analysis: Because the previous bit is assigned to the next one. So we can't loop the statement from the front to the back, so we loop the statement from the back forward, because the size of the array can not be changed, insert a number, you need to discard the last number, so the initial loop is starting from array.length-2, to the end of the index, as shown above.
Add the INPUT element to the correct position in the array (JAVA)