Home > Java > javaTutorial > body text

How to use binary search to specify elements in an array in java

王林
Release: 2023-05-01 20:10:05
forward
992 people have browsed it

Find the specified element in the array (binary search)

二分查找的必要条件是必须有序的数列
    public static int binarySearch(int[] array,int key){
        int left = 0;
        int right = array.length-1;
        while(left <= right){
            int mid = (left+right)/2;
            if(array[mid] > key){
                right = mid - 1;
            }else if(array[mid] < key){
                left = left + 1;
            }else{
                return mid;
            }
 
        }
        return -1;
    }
 
    public static void main(String[] args) {
        int[] array = {12,14,15,16,18,23};
        System.out.println(binarySearch(array, 15));
    }
Copy after login

Print result:

How to use binary search to specify elements in an array in java

The above is the detailed content of How to use binary search to specify elements in an array 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