This is a Java array instance that inserts a number into a sequential array. It's obvious that direct insertion is not going to work, because the Java array is fixed, invariant is not dynamically expandable, want to insert a number must re-create an array, its length is larger than the original array, and then copy it, the next thing to do is to implement the insertion in the new array. Using the System.arraycopy () method, you can copy an array, or you can use a for loop just like a blogger, more intuitive
Import java.util.*;
public class Insert {
int[] a={2,9,13,28,30,45,58,60};
Public void Insert (int m) {
int[] b=new int[a.length +1];
for (int i=0;i<a.length;i++) {
b[i]=a[i];
}
for (int i=0;i<b.length-1;i++) {
if (M>b[a.length-1]) {
b[b.length-1]=m
}
if ((b[i]<m) && (b[i+1]>=m)) {for
(int j=i;j<b.length-1;j++) {
b[j+1]=a[j];
}
b[i+1]=m;
break;
}
}
for (int i=0;i<b.length;i++) {
System.out.print (b[i]+ " ");
}
}
public static void Main (string[] args) {
//TODO auto-generated method stub
Insert p=new Insert ();
Scanner sc=new Scanner (system.in);
System.out.print ("Please enter the number to insert:");
int C=sc.nextint ();
P.insert (c);
Sc.close ();
}
For this example, 1, first to copy a new expansion of the array
2, and then determine whether to insert the number is greater than the maximum number, if directly in the last side of the insertion
3, otherwise, insert into the appropriate position and the number after the insertion position to move back
The focus of this topic is to investigate the expansion of the array and cross-border problems, here is more prone to chaos, I have tried many times to eliminate the bug, we must have patience, for the array to be cautious or inadvertently will be crossed errors.