Home > Java > javaTutorial > How to implement binary search in java

How to implement binary search in java

王林
Release: 2023-04-28 15:49:13
forward
1125 people have browsed it

Binary search

//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("很遗憾没有找到");
        }
    }
}
Copy after login
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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template