对半法查找元素
package 对半法找数组元素;
import java.util.Scanner;
public class 对半法找数组元素 {
public static void main(String[] args)
{
int m=0;
Scanner sc=new Scanner(System.in);
System.out.println("请输入该数组的元素数量");
m=sc.nextInt();
int arr[]=new int[m];
for(int i=0;i<arr.length;i++)
{
System.out.println("请输入该数组的第"+(i+1)+"元素");
arr[i]=sc.nextInt();
}
//for(int i=0;i<arr.length;i++)
//{
//arr[i]=sc.nextInt();
//}
int findelem=170;
int high=m;
int low=1;
int mid=(high+low)/2;
while(findelem!=arr[mid])
{
if(findelem>arr[mid])
{
low=mid+1;
}
else
{
high=mid-1;
}
mid=(high+low)/2;
}
System.out.print("你要找的元素在第"+(mid+1)+"个");
//for(lint i = 0;i<arr.length;i++)//{//System.out.print//(arr[i]);//}
}
}