在排好序的数组中添加一个数字,将添加后的数字插入到数组合适的位置

//在排好序的数组中添加一个数字,将添加后的数字插入到数组合适的位置
public class Test00 {
	public static int[] fun(int[] num, int n) {
		int index = binarySearchAsc(num,n,0,num.length-1);
		int[] newN=new int[num.length+1];
		int i=0;
		for(int j=0;j<newN.length;j++){
			if(j==index){
				newN[j]=n;
			}else{
				newN[j]=num[i++];
			}
		}
		return newN;
		
	}
	public static int binarySearchAsc(int[] ary,int target,int start,int last){
		 
	        // 如果范围大于0,即存在两个以上的元素,则继续拆分  
	        if (last > start) {   
	            int mid = (last + start) / 2;  
	            if (ary[mid] > target) {     
	                return binarySearchAsc(ary, target, start, mid - 1);  
	            } else {  
	                return binarySearchAsc(ary, target, mid + 1, last);  
	            }  
	        } else {  
	            if (ary[start] > target) {//如 5,4, 要插入的是4  
	                return start;  
	            } else {  
	                return start + 1;  
	            }  
	        }  
		  
	}

	public static void main(String args[]) {
		int[] num = { 1, 3, 5, 7, 8, 9 };
		int n = 4;
	
		int[] newN = fun(num, n);
		for (int n1 : newN) {
			System.out.print(n1 + "  ");
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值