1 / * 30 [program number] Insert 30
2 Title: array row have a good sequence. Now enter a number, required by the laws of the original insert it into the array.
3 Program Analysis: determining whether the first number is greater than the last number, and then consider the case where the number of intermediate insertion, after insertion of this element after
4 number, a turn backward position.
5 * /
. 6
. 7 / * Analysis
8 * 1, there is a good array in ascending order, such as: 1,3,5,7,9,11,13,15,17,19,21; (a total of 11 number, inserting it 12 a)
9 * 2, inserting a number (e.g. 10 or 22);
10 * 3, (1) 22, then, because larger than the last number, all directly discharged in the last
11 * (2) 10, then as to insert the array, 11, 13 all to move .. . Behind the other number
12 * 4, the difficulty in determining how the inserted position and moved back to make room for the insertion ====== use for loop, traversed one by one, to find a [i] <= x < = a [i + 1] where,
13 * and then to move as the intermediate variable t
14 * * /
15
16 / *[Note]
17 * array expansion array = Arrays.copyOf (array, array.length + 1); // expansion array
18 is * * /
. 19
20 is
21 is Package Homework;
22 is
23 is Import java.util.Arrays;
24 Import Classes in java.util .Scanner;
25
26 is public class value_30 {
27
28 public static void main (String [] args) {
29 // declare an integer array size of 12
30 int [] = {1,3,5,7,9 a , 11,13,15,17,19,21 };
31 // enter the number of insert
32 System.out.println ( "Please enter an integer to be inserted:" );
33 is int X = new new Scanner (the System.in) .nextInt ();
34 is
35 // array of key expansion === Comparative
36 A = Arrays.copyOf (a, a.length +. 1 );
37 [ // declaration represents an integer array length
38 is int length = a.length;
39
40 // comparison to be inserted is greater than the number of the last number of array
41 is // the System.out .println (a [-a.length. 1]);
42 is IF (X> a [length-2]) { // X a number greater than the last
43 is a [-length. 1] = X;
44 is }
45 the else { // X is less than the number of the last
46 // declare an array subscript storage location to find the position of the
47 int location = 0 ;
48 // iterate to find the position of insertion should be
49 for ( int I = 0; I <a.length; I ++ ) {
50 IF ((a [I] <= X) & (a [I +. 1]> = X)) {
51 is lOCATION = I +. 1; // find a number of positions prior to the after, to be inserted therein between, all added here. 1
52 is BREAK ;
53 is }
54 is }
55 // // testing
56 // System.out.println(location);
57
58 //开始移动数据
59 for (int i = length; i > location; i--) {
60 a[i-1]=a[i-2];
61 }
62 a[location]=x;
63 }
64 //输出数组
65 for (int i = 0; i < a.length; i++) {
66 System.out.print(a[i]+" ");
67 }
68
69
70 }
71
72 }