//java coding



import java.util.Scanner;

/**
 * @author 
 * 2014-5-22 下午04:29:56
 * 二分查找
 */
public class Binary_search {

public static int device(int[] a,int c)
{
int begin=0;
int end=a.length-1;
int mid;


while(begin<=end)
{
mid=(begin+end)/2;
if(a[mid]==c)
{
return mid;
}
else if(a[mid]>c)
{
end=mid-1;
}else
{
begin=mid+1;
}

}
return -1;
}


public static void main(String[] args) {
int[] a ={1,5,7,10,15,25,34,67,99};

Scanner input = new Scanner(System.in);
System.out.print("输入你要查找的数:");
int c = input.nextInt();

int index;
//Binary_search de = new Binary_search();
index =device(a,c);
System.out.println(c+"这个元素"+( index==-1?"不存在":"在数组中的位置是"+index));

/*if(( index=device(a,c))<0)
{
System.out.println("在数组中未找到元素"+c+"的值");
}else
{
System.out.println("元素"+c+"在数组中的下标是"+index);
}*/




}


}

版权声明:本文为博主原创文章,未经博主允许不得转载。

posted on 2014-05-22 19:17  六月心悸  阅读(1090)  评论(0编辑  收藏  举报