zoukankan      html  css  js  c++  java
  • 数组(插入算法[int])

     1 public static void main(String[] args) {
     2         //在一个数组中插入一个数据[步骤]----前提:该数组是有序数组!!!
     3         //01.首先声明这个数组
     4         //刚开始的数组
     5         int[] num = { 10, 25, 36, 49 };
     6         //遍历输出num数组元素
     7         for (int i = 0; i < num.length; i++) {
     8             System.out.print(num[i] + "	");
     9         }
    10         System.out.println();
    11         //02.建立一个新的数组,数组长度为原数组长度+你想插入的数字的个数
    12         //定义一个新的数组nums
    13         int[] nums = new int[5];
    14         //03.声明想要插入的数
    15         //定义一个想插入的整数number
    16         int number = -5;
    17         //04.将原数组赋值给新的数组
    18         //将刚开始的length为4的数组赋值给length为5的新数组
    19         for (int i = 0; i < num.length; i++) {
    20             nums[i] = num[i];
    21         }
    22         //05.输出新数组的各项元素(会发现,新数组比原数组多的一个或几个位置上的值为0)
    23         //遍历输出新数组的元素
    24         for (int i = 0; i < nums.length; i++) {
    25             System.out.print(nums[i] + "	");
    26         }
    27         System.out.println();
    28         //06.声明一个位置,为想要插入的数在新数组上占一个位置
    29         //定义一个下标,该下标代表number在数组nums中的位置
    30         int index = nums.length - 1;
    31         //07.通过循环比较,找到这个位置
    32         for (int i = 0; i < nums.length; i++) {
    33             if (nums[i] > number) {
    34                 index = i;
    35                 break;
    36             }
    37         }
    38         //08.将这个位置前或后的其他元素位置向前或向后变更
    39         for (int i = nums.length - 1; i > index; i--) {
    40             nums[i] = nums[i - 1];
    41         }
    42         //09.将想要插入的数赋值给这个找到的位置上的新数组的元素
    43         nums[index] = number;
    44         //10.遍历输出新数组中的元素--------插入完成!!!
    45         for (int i = 0; i < nums.length; i++) {
    46             System.out.print(nums[i] + "	");
    47         }
    48     }
  • 相关阅读:
    shell脚本中使用nohup执行命令不生效
    【异常】Could not find artifact com.wm.****:
    【异常】The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
    MySQL添加唯一索引
    MacBook Pro实现共享屏幕(多台mac之间)
    【异常】lockfile.AlreadyLocked: ~/airflow/airflow-scheduler.pid is already locked
    CentOS7.2安装Airflow
    Docker
    Docker
    Docker
  • 原文地址:https://www.cnblogs.com/dark-qinshou/p/4710380.html
Copyright © 2011-2022 走看看