Home >Java >javaTutorial >How to use binary search to specify elements in an array in java

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

王林
王林forward
2023-05-01 20:10:051016browse

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));
    }

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!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete