Find the specified element in the array (binary search)

Finding a specified element in an array (binary search)
To find a specified element in an array, a more efficient binary search can be used for ordered arrays.
Take the ascending array as an example. Binary search first takes the element in the middle position, and sees whether the value to be found is larger or smaller than the middle element. If it is smaller, go to the left to find; otherwise, go to the right to find.
Code:

public static void main(String[] args) {
    
    
        int[] arr = {
    
    12, 22, 32, 42, 52, 62};
        System.out.println(binarySearch(arr, 32));
    }

    public static int binarySearch(int[] arr, int toFind) {
    
    
        int left = 0;
        int right = arr.length - 1;
        while (left <= right) {
    
    
            int mid = (left + right) / 2;
            if (toFind < arr[mid]) {
    
    
                // 去左侧区间找
                right = mid - 1;

            } else if (toFind > arr[mid]) {
    
    
                // 去右侧区间找
                left = mid + 1;
            } else {
    
    
                // 相等, 说明找到了
                return mid;
            }
        }// 循环结束, 说明没找到
                return -1;
            }

result:
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_44436675/article/details/112091531