import java.util.Scanner; public class erfen { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int x = scan.nextInt(); int[] a= {0,1,2,3,4,5,6,7,8,9,10}; int i = 0; int j= a.length-1; int mid=0; while(i<=j) { mid = (i+j)/2; if(x==a[mid]) break; if(x>a[mid]) { i=mid+1; } else{ j=mid-1; } } System.out.println(a[mid]); } }
分析:i<=j,而不是i<j是因为在i=j时还存在搜索空间i(j);