二分查找插入

阅读更多

算法分析

       在有序数组中使用二分查找,如果没有找到则进行插入。

 

public class BinarySearchInsert{
    public static void main(String args[]){
      int search = 0;
      int[] src = {1,2,3,4,5,6,7,8,9,10};
      Map result = binarySearch(src,search);
      if("Y".equals(result.getString("isFind"))){
         System.out.println("value was found,index is :" + result.getString("index"));
      }else{
         insertArray(src,search,Integer.parseInt(result.getString("index")));
      }
    }
    public static void binarySearch(int[] src,int search){
       Map result = new HashMap();
       int left = 0;
       int right = src.length;
       while(left <= right){
          int middle = (left + right)/2
          if(src[middle] == search){
              result.put("isFind","Y");
              result.put("index",String.valueOf(middle));
              return result;
          }else if(src[middle] > search){
              left = middle + 1;
          }else{
              right = middle - 1;
          }
       }   
       result.put("isFind","N");
       result.put("index",String.valueOf(left))
       return -1;
    }
    public static void insertArray(int[] src,int value,int index){
        int[] dec = Array.copyOf(src,src.length + 1);
        int decL = dec.length;
        while(index <= decL){
            if(index == decL){
               dec[decL] = value;
               break;
            }
            dec[decL] = dec[decL-1];
            decL--;
        }
    }
}

 

你可能感兴趣的:(二分查找插入)