In java, insert elements into an ordered array to keep the array in order

//已知有一个数组,
	/*数组里面的元素有a b c d e f y z,
	从控制台中随机输入一个字母,
	按照升序的顺序插入到该数组中并且遍历输出。*/
	public static void test1(){
		String [] str={"a","b","c","d","e","f","y","z"};
		String [] str1=new String[str.length+1];
		System.out.println("原来数组里面的元素");
		for (String s : str) {
			System.out.print(s+" ");
		}
		//赋值数组
		for(int i = 0;i<str.length;i++){
			str1[i] =str[i];
		}
		System.out.println("\n请输入要插入的元素:");
		Scanner sc = new Scanner(System.in);
		String name= sc.next();
		//找到需要插入的位置
		int index =0;
		for(int i = 0;i<str.length;i++){
			if(str[i].compareToIgnoreCase(name)>0){
				index = i;
				break;
			}
		}
		//元素往后移动
		for (int i =str1.length-1; i >index; i--) {
			str1[i] = str1[i-1];
		}
		//在指定位置插入新元素
		str1[index] = name;
		System.out.println("插入之后的数组是:");
		for (String s : str1) {
			System.out.print(s+" ");
		}

	}

The operation results are shown in the figure:
Insert picture description here
Welcome to pay attention to the public numberXiongxiong's small classroom
Insert picture description here

Published 691 original articles · praised 649 · 1.11 million views

Guess you like

Origin blog.csdn.net/qq_34137397/article/details/105396176