Home >Java >javaTutorial >How to implement binary search in java
//The premise must be in order
Example: First look at
import java.util.Scanner; public class T07 { public static void main(String[] args) { Scanner s = new Scanner(System.in); int a= s.nextInt(); int[]arr=new int[]{1,2,3,4,6,7,8,9,10}; int left=0; int right= arr.length-1; boolean is=true; while(left<=right){ int average=(int)(left+right)/2; if(arr[average]>a){ right=average-1; } else if(a==arr[average]){ System.out.println("找到了,下标是:"+average); is=false; } else { left = average + 1; // }if(left==right){ // System.out.println("没有找到"); // is=false; } } if(is){ System.out.println("很遗憾没有找到"); } } }from small to large
The above is the detailed content of How to implement binary search in java. For more information, please follow other related articles on the PHP Chinese website!