有一个已经排好序的数组。现输入一个数,要求按原来的规律将它插入数组中。

首先判断此数是否大于最后一个数,然后再考虑插入中间的数的情况,插入后此元素之后的数,依次后移一个位置。

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;
	} 
}

在这里插入图片描述

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值