//在排好序的数组中添加一个数字,将添加后的数字插入到数组合适的位置
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 + " ");
}
}
}
在排好序的数组中添加一个数字,将添加后的数字插入到数组合适的位置
最新推荐文章于 2024-07-24 07:00:00 发布