题目:有一个已经排好序的数组,现输入一个数,要求按原来的规律将它插入数组中
1 public class _030InsertOneFigure {
2
3 public static void main(String[] args) {
4 insertOneFigure();
5 }
6
7 private static void insertOneFigure() {
8 int[] a = new int[] { 1, 2, 6, 14, 25, 36, 37, 55 };
9 int[] b = new int[a.length + 1];
10 int i = 0;
11
12 Scanner scanner = new Scanner(System.in);
13 System.out.println("请输入一个整数:");
14
15 int num = scanner.nextInt();
16 if (num >= a[a.length - 1]) {
17 b[b.length - 1] = num;
18 for (i = 0; i < a.length; i++) {
19 b[i] = a[i];
20 }
21 } else {
22 for (i = 0; i < a.length; i++) {
23 if (num >= a[i]) {
24 b[i] = a[i];
25 } else {
26 b[i] = num;
27 break;
28 }
29 }
30 for (int j = i + 1; j < b.length; j++) {
31 b[j] = a[j - 1];
32 }
33 }
34 for (i = 0; i < b.length; i++) {
35 System.out.print(b[i] + " ");
36 }
37 }
38 }
网友评论