赞
踩
有一个数组,其中有十个元素从小到大依次排列 {12,14,23,45,66,68,70,77,90,91}。再通过键盘录入一个整数数字。要求:把数字放入数组序列中,生成一个新的数组,并且数组的元素依旧是从小到大排列的。
思路:使用动态初始化定义一个新数组,新数组的长度为原数组长度+1,在遍历原数组向新数组拷贝元素时,先将元素与录入数字比较大小,若小于录入数字,则该元素在原数组的索引同样也是在新数组中的索引;若大于或等于录入数字,则该元素在原数组的索引+1,即向后移动了一位。循环结束后,新数组中必然空了一个位置,在那个位置插入录入的数字即可。
- package array;
-
- import java.util.Scanner;
-
- public class Train {
- public static void main(String[] args) {
- //从键盘录入一个整数
- Scanner sc = new Scanner(System.in);
- System.out.println("请输入需要录入的整数:");
- int num = sc.nextInt();
-
- int[] arr1 = {12,14,23,45,66,68,70,77,90,91};
- int[] arr2 = new int[11];//动态初始化定义新数组
- int index = 0;//定义变量用来存放录入数字的索引
- //遍历原数组依次将元素赋值给新数组
- for (int i = 0; i < arr1.length; i++) {
- if (arr1[i] < num){
- arr2[i] = arr1[i];//若小于录入的数字,则不需要移位
- index = i+1;//录入的数字往后一位
- }else {
- arr2[i+1] = arr1[i];//若大于录入的数字,则向后移动一位,中间空出来的位置存放录入的数字
- }
- }//循环结束index即要插入数字的索引
- arr2[index] = num;//插入数字
- //打印新数组
- for (int i = 0; i < arr2.length; i++) {
- System.out.print(arr2[i] + " ");
- }
- }
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。