`
zengshaotao
  • 浏览: 755231 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

二分法

 
阅读更多


public class Arithmetic {

 public static void main(String args[]){
  

//二分法,一般用于已经排序的数组,数据量大时,性能优势更为明显
    //如果无序,可先排序
  int tt[] = {-3,0};
  int loopCount = tt.length;
  
  System.out.println(erfen(-1,tt,0,loopCount-1));
  
 }
 
 //对于递归,递归方法里一定有迭代的不断变化的参数,这里是起始和终止index
 //不管如何递归,都是对被查询的数据和数组进行操作,所以searchdata和
 //arr是可以不发生变化并作为递归方法的参数
 public static int erfen(int searchdata,int[]arr,int start,int endIndex){
  int index;
  
  //对于被寻找的数据在数组边缘的情况需要单独考虑
  //在边缘时也囊括了数组长度比较极端的情况,长度为1,或者2,
  //对于数据量比较少的情况,一般不采用特殊的算法,直接遍历就ok
  if(searchdata==arr[start]){//寻找的数在数组的第一个位置
   index = start;
   System.out.println(searchdata +" index is :" +index);
   return index;
  }else if(searchdata==arr[endIndex]){//寻找的数在数组的最后一个位置
   index = endIndex;
   System.out.println(searchdata +" index is :" +index);
   return index;
  }
  if((endIndex-start)<=1){//此时两个数已经相邻
   index = 0;
   System.out.println("not existing ");
  }else{
   index = (endIndex+start)/2;
   if(searchdata<arr[index]){
    index = erfen(searchdata,arr,start,index);
   }else if(arr[index]==searchdata){
    System.out.println(searchdata +" index is :" +index);
   }else if(arr[index]<searchdata){
    index = erfen(searchdata,arr,index,endIndex);
   }
  }
  
  return index;
 }
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics