- package Array;
- public class InsertArray
- {
- public static int[] newArr(int[] arr, int value)
- {
- int mid = insertArr(arr, value);
- int[] arrs = new int[arr.length+1];
- for(int i=0;i<arr.length;i++)
- {
- if(mid==i)
- {
- arrs[i] = arr[i];
- arrs[i+1] = value;
- }
- else
- {
- if(i>mid)
- {
- arrs[i+1] = arr[i];
- }
- else
- {
- arrs[i] = arr[i];
- }
- }
- }
- return arrs;
- }
- public static int insertArr(int[] arr,int value)
- {
- int min = 0;
- int max = arr.length-1;
- int mid = 0;
- while(min<max)
- {
- mid = (max+min)/2;
- if(arr[mid]<value)
- min = mid+1;
- else if(arr[mid]>value)
- max = mid-1;
- else
- return mid;
- }
- return mid=min;
- }
- public static void main(String[] args)
- {
- int[] arr = {1,2,7,9,12,21,22};
- for(int i=0;i<arr.length;i++)
- {
- if(i==0)
- System.out.print("插入前的数组:"+"{");
- if(i==arr.length-1)
- System.out.println(arr[i]+"}");
- else
- System.out.print(arr[i]+",");
- }
- int[] arrs = newArr(arr, 19);
- for(int i=0;i<arrs.length;i++)
- {
- if(i==0)
- System.out.print("插入后的数组:"+"{");
- if(i==arrs.length-1)
- System.out.println(arrs[i]+"}");
- else
- System.out.print(arrs[i]+",");
- }
- }
- }
复制代码 |