二分搜索技术

    科技2022-07-11  96

    小白,不知道自己的代码为什么不对,希望大神告知

    package SF1; import java.util.Scanner; public class sf032 { public static void main(String args[]) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); //int x=sc.nextInt(); int a[]=new int[n]; for(int i=0;i<=n;i++) { a[i]=sc.nextInt(); } System.out.println(bin(a, 3, n)); } public static int bin(int []a,int x,int n) { int left=0;int right=n-1; while (left<=right) { int middle=(left+right)/2; if (x==a[middle]) return middle; if(x>a[middle]) left=middle +1; else right =middle -1; } return -1; } }

    Processed: 0.050, SQL: 8