编程之美-3.11

1.给定一个有序(不降序)数组a,求任意一个i使得a[i]等于v,不存在返回-1

int bisearch(int[] a, int v){
  int low = 0,high = a.length-1,t;
  while(low<=high){
       t = low+(high-low)/2;
       if(a[t]==v) return t;
       else if(a[t]>v){
           low = t+1;
       }else{
           high = t-1;
       }
     }
   return -1;
}

2. 给定一个有序(不降序)数组a,求最小的i使得a[i]等于v,不存在返回-1

int bisearch(int[] a, int v){
     int low = 0,high = a.length-1,t;
     while(low<high){
          t = low+(high-low)/2;
          if(a[t]<v){
              low = t+1;   
          }else{                               //相等时仍要往下标为0处走
          high = t;        
          }
        }  
            if(a[high]==v)  return (high);
            else return -1;  }

  3.给定一个有序(不降序)数组a,求最大的i使得a[i]等于v,不存在返回-1

int bisearch(int[] a, int v){
    int low = 0,high = a.length-1,t;
    while(low<high-1){
           t = low+(high-low)/2;			      
           if(a[t]>v){
	 high = t-1;  			       
           }else{                               
	 low = t;    
           }
      }  
          if(a[low+1]==v)  System.out.println(low+1);
          else if(a[low]==v) System.out.println(low);
          else System.out.println(-1);			
   }

 

    原文作者:iteye_4516
    原文地址: https://blog.csdn.net/iteye_4516/article/details/82405602
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞