Java Algorithm Exploration: Detailed Explanation of Binary Search

Binary search is an efficient algorithm when you need to find a specific element in an ordered array. Its time complexity is O(log n). Compared with O(n) of linear search, binary search can significantly improve search efficiency. This article will explain in detail what binary search is and how to implement it in Java.

Introduction to binary search

Binary search, also known as binary search, is an algorithm for finding the target element in an ordered array. Its principle is to continuously halve the search range until the target element is found or it is determined that the target element does not exist. The steps for binary search are as follows:

  1. Initialize the left boundary left to be the index of the first element of the array, and the right boundary right to be the index of the last element of the array.
  2. Calculate the index mid of the middle element, which is equal to (left + right) / 2.
  3. Compare the middle element to the target element:
  • If the middle element is equal to the target element, the target is found and the index of the middle element is returned.
  • If the middle element is larger than the target element, update the right boundary to mid - 1 and continue searching on the left half.
  • If the middle element is smaller than the target element, update the left boundary to mid + 1 and continue searching on the right half.
  1. Repeat steps 2 and 3 until the target element is found or the left boundary exceeds the right boundary.

Java implements binary search

The following is sample code to implement binary search in Java:

/**
 * 二分查找
 */
public static int binarySearch(int[] intArr,int key){
    
    
    int left = 0;
    int right = intArr.length -1;

    while(left <= right){
    
    
        //计算中间元素的索引
        int mid = (left + right) >>> 1;
        //获取中间元素的值
        int midVal = intArr[mid];
        //比较中间元素和目标元素的值
        //如果中间元素小于目标元素,则将左边界更新为 mid + 1,继续在右半边查找。
        if (midVal < key)
            left = mid + 1;
        //如果中间元素大于目标元素,则将右边界更新为 mid - 1,继续在左半边查找。
        else if (midVal > key)
            right = mid - 1;
        //如果中间元素等于目标元素,则找到目标,返回中间元素的索引。
        else
            return mid;
    }

    //如果循环结束仍未找到目标元素,返回一个负数,表示未找到,通常为-(left + 1)
    return -(left + 1);
}

public static void main(String[] args) {
    
    

    int[] intArray = new int[]{
    
    2,4,5,7,9,11,16,23,45,67};

    System.out.println(binarySearch(intArray,5));
    System.out.println(binarySearch(intArray,23));
    System.out.println(binarySearch(intArray,1));
    System.out.println(binarySearch(intArray,20));
    System.out.println(binarySearch(intArray,110));

}

The output is:

2
7
-1
-8
-11

In the above code, the binarySearch method accepts an ordered array intArr and the target element key as parameters, and then uses the binary search algorithm to find the index of the target element in the array. If the target element is found, its index is returned; otherwise, a negative number is returned to indicate that the target element does not exist.

Precautions

The premise of binary search is that the array must be ordered , otherwise it will not work properly. If the array is not sorted, the array needs to be sorted before the binary search algorithm can be used.

Summarize

Binary search is an efficient search algorithm suitable for ordered arrays. Its time complexity is O(log n), where n is the length of the array. Because the search range is halved with each iteration, it is more efficient than simple search algorithms such as linear search, especially for large ordered arrays. By carefully implementing and understanding the binary search algorithm, you can easily apply it in Java to solve a variety of search problems.

Guess you like

Origin blog.csdn.net/weixin_44002151/article/details/132822775