二分法查找

package lianxi;
import java.util.*;

public class Erfenchazhao {
    
// 网上查到的方法  
public static int halfSearch(int a[], int x) {
      int mid, left, right;
      left = 0;
      right = a.length - 1;
       
       mid = (left + right) / 2;      

      while (a[mid] != x)
      {        
       if(a[left]>x||x>a[right])
          {
              System.out.println("你输入的数字不在数组中");
              System.exit(0);
          }

      if (x > a[mid])
       {
        left = mid + 1;
       }
       else if (x < a[mid]) 
       {
        right = mid - 1;
       }
          mid=(left+right)/2;

      } 
     
      return mid;


     }
    

    public static void main(String[] args) {        
    //输入要查找的对象    
    Scanner shu=new Scanner(System.in);
    System.out.println("请输入一个整数:");
    int i=shu.nextInt();
    //查看一下输入的数字
    System.out.println("您输入的数值是"+i);
    //创建数组 并查看数组元素
    //二分查找法需要按大小排好,这里直接按从小到大排列,不用排序
    int ary[]={2,4,6,8,10,12,14,16,18,20};
    for (int j = 0; j < 10; j++)
    {
    System.out.println("ary["+j+"]="+ary[j]);        
    }
    
    
    int s = halfSearch(ary, i);
    System.out.println(i + "在数组中是 ary["+s+"] =" + ary[s]);
     
  }
}
    

 

 

 

posted @ 2016-05-10 20:41  凌零聆  阅读(157)  评论(0编辑  收藏  举报