首先判断此数是否大于最后一个数,然后再考虑插入中间的数的情况,插入后此元素之后的数,依次后移一个位置。
import java.util.Scanner;
public class test30{
public static void main(String[] args){
int[] a={5,6,8,2,1,13,15,77,88,37,31,58}; //定义一个整型数组
System.out.print("排序前:");
for(int x:a){ //输出排序前数组
System.out.print(x+" ");
}
System.out.println();
int[] b=sort(a); //执行排序
System.out.print("排序后:");
for(int x:b){ //打印排序后数组
System.out.print(x+" ");
}
System.out.println();
System.out.print("请输入要插入的数:");
Scanner scan = new Scanner(System.in);
int input = scan.nextInt();
scan.close();
int[] c=insert(input,b);//向数组中插入数字
System.out.print("插入数字后:");
for(int x:c){ //打印插入后的数组
System.out.print(x+" ");
}
}
private static int[] sort(int[] a){
//升序 冒泡排序
for(int j=0;j<a.length-1;j++){
for(int i=0;i<a.length-1;i++){
if(a[i]>a[i+1]){
int temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;
}
}
}
return a;
}
private static int[] insert(int n,int[] b){
int[] tempArray=new int[b.length+1];//定义数组存放插入后的数组。
if(n>b[b.length-1]){//n大于排序好的数组最后一位,直接把n放到tempArray最后一位。
tempArray[b.length]=n;
for(int i=0;i<b.length;i++){
tempArray[i]=b[i]; //之前的数字按顺序赋值。
}
}else{
for(int i=0;i<b.length;i++){
if(n<b[i]){ //找到原来数组中大于n的第一位,并将n放在此位置
//给之前没变的数组赋值
for(int j=0;j<i;j++){
tempArray[j]=b[j];
}
//后面向后挪一位
for(int k=i;k<b.length;k++){
tempArray[k+1]=b[k];
}
tempArray[i]=n;
break;
}
}
}
return tempArray;
}
}