这是我写的,感觉特别复杂,不太好
- package org.heima;
- public class Test9 {
- /**
- * 数组查询,折半查找,利用折半查找,将一个数字插入到数组中
- */
- public static void main(String[] args) {
- int[] a=new int[]{1,2,3,5,6,7,8,9};
- int[] b=new int[a.length+1];
-
- int min=0,max=a.length-1;
- int mid=(max+min)/2;
-
- int key=4;//要插入的值
- while(true){
- if(a[mid]>key&&a[max]!=a[min]){
- max=mid-1;
- mid=(max+min)/2;
- System.out.println(a[mid]);
- }
- else if(a[mid]<key&&a[max]!=a[min]){
- min=mid+1;
- mid=(max+min)/2;
- System.out.println(a[mid]);
- }
- else{
- for(int i=0;i<b.length-1;i++){
- if(i==mid){
- b[mid+1]=key;
- b[mid]=a[mid];
- }
- else if(i<mid)
- b[i]=a[i];
- else
- b[i+1]=a[i];
- }
- break;
- }
-
- }
- for(int i=0;i<b.length;i++)
- System.out.print(b[i]+" ");
-
-
-
- }
- }
复制代码
|
|