• 往一个已知数组中插入一个元素


    package ch07;

    import java.util.Arrays;

    /**
    * Created by liwenj on 2017/7/19.
    */
    public class test2 {
    public static void main(String[] args) {
    char[] a = new char[]{'b', 'c', 'e', 'f', 'g'};
    // Arrays.sort(a);
    // System.out.println(a);u
    char d = 'd';
    char[] temp = new char[a.length + 1];//定义一个新数组存储,temp数组比a多一个元素
    for (int i = 0; i < a.length; i++) {
    temp[i] = a[i];//{'b', 'c', 'e', 'f', 'g'}//temp[i]就是a[i]
    }
    temp[temp.length - 1] = d;//把d放到temp中的最后一个
    //找插入位置
    int index = 0;
    //1.一直数组中最大的在倒数第一位,如果插入字符比原来字符中最大还要大
    if (d > temp[temp.length - 2]) {
    index = temp.length - 1;
    } else if (d < temp[0]) { //2.如果插入字符比原来字符第一个还要小
    index = 0;
    }
    //3.普通情况
    for (int i = 0; i < temp.length - 2; i++) {
    if (d > temp[i] && d < temp[i + 1]) {
    index = i + 1;
    break;
    }
    }
    System.out.println(index);
    //移动元素
    for (int j = temp.length - 2; j >=index; j--) {
    temp[j + 1] = temp[j];//往后挪

    }
    temp[index] = d;
    System.out.println(temp);
    }

    }
  • 相关阅读:
    hbase过滤器(1)
    公司jar包提交到集群的方法
    hbase Hfile处理原因
    oracle pl/sql远程连接过程
    mapreduce join操作
    HTML不熟悉方法总结
    Ajax详解
    getElementById和querySelector区别
    Session
    ES6模块化
  • 原文地址:https://www.cnblogs.com/lwj820876312/p/7204718.html
Copyright © 2020-2023  润新知