How to implement the binary search algorithm in the programming competition?

Table of contents

1. What is binary search

2. How to perform a binary search

3. Advantages and application scenarios of binary search


 

1. What is binary search

Binary search algorithm, also known as binary search algorithm, is a search algorithm for finding a specific element in an ordered array. Its implementation principle is to narrow the search range by continuously dividing the search area into two parts until the target element is found or it is determined that the target element does not exist.

The specific implementation steps are as follows:

  1. Determine the start position and end position of the interval to be searched. Usually, the initial start position is the first element subscript of the array, and the end position is the last element subscript of the array.
  2. Calculate the middle position of the interval to be searched, use the method of (start + end) / 2, and take the integer part as the subscript of the middle position.
  3. Determine the size relationship between the element in the middle position and the target element:
    • If the element at the middle position is equal to the target element, return that position.
    • If the element at the middle position is larger than the target element, update the end position to the middle position minus 1, and narrow the search range from the start position to the middle position minus 1.
    • If the element at the middle position is smaller than the target element, update the start position to the middle position plus 1, and narrow the search range from the middle position plus 1 to the end position.
  4. Repeat steps 2 and 3 until the start position is greater than the end position, indicating that the search interval is empty. At this time, it can be determined that the target element does not exist, and -1 is returned.

The key of the binary search algorithm is to continuously reduce the area to be searched by half, and quickly determine the position of the target element by continuously comparing it with the element in the middle position. Since each search reduces the search range by half, the time complexity of the binary search algorithm is O(log n), where n is the length of the array. This makes binary search an efficient search algorithm, suitable for searching large-scale data. But it should be noted that the binary search algorithm requires that the array to be searched must be in order.

 2. How to perform a binary search

The following is a sample code for binary search implemented in Java:

public class BinarySearch {
    public int binarySearch(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        
        while (left <= right) {
            int mid = left + (right - left) / 2;
            
            if (nums[mid] == target) {
                return mid;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        
        return -1; // 目标元素不存在
    }
    
    public static void main(String[] args) {
        BinarySearch binarySearch = new BinarySearch();
        int[] nums = {1, 3, 5, 7, 9};
        int target = 5;
        int result = binarySearch.binarySearch(nums, target);
        if (result != -1) {
            System.out.println("目标元素的索引为: " + result);
        } else {
            System.out.println("目标元素不存在");
        }
    }
}

In the above code, binarySearchthe method receives an ordered array  nums and a target element  target, and finds the index of the target element in the array by using the binary search algorithm. Initially, the left boundary of the search interval  left is set to the index of the first element of the array, and the right boundary of the search interval  right is set to the index of the last element of the array. Then, by continuously dividing the search interval into two, according to the size relationship between the element in the middle position and the target element, the  value of sum left is updated  right to narrow the search range. Finally, if the target element is found, its index is returned; if the search interval is empty, indicating that the target element does not exist, -1 is returned.

In the example  method, an ordered array  and target element  main are created   the method is called to perform a binary search, and the returned result is used to determine whether the target element exists, and the result is output.numstargetbinarySearch

 

3. Advantages and application scenarios of binary search

The advantages of binary search The binary search potential has the following advantages of the algorithm:

  1. The complexity of time potential and application multiplexing field is low: the scene is as follows:

Advantages of optimal binary search algorithm:

  1. The time complex time complexity is O(log n), and the complexity is low: 2 where n is the length of the array to be searched. The time complexity of the sub-search algorithm is O(logn) for each search, where n is the reduction in half of the array, so the length of the large-scale data is limited. Compared with the O(n) of the linear search algorithm, the binary search algorithm can search in a shorter time, and the efficiency of the binary search is very high.
    2 Find the target element.
  2. Efficiency. Applicable to ordered arrays: Binary search requires to be searched: Because the binary search algorithm continuously divides the array in the search area into order, but the positive dichotomy can quickly narrow the search. It is due to this feature that the scope of the search can be reduced. The number of search times is used to compare and narrow the search range each time, quickly locate the position of the target element, and improve the search efficiency.
  3. Applies to have.

The application scenarios of binary search are as follows:
1. Ordinal array: The binary search algorithm requires to find specific elements in the ordered array: the array to be searched must be ordered when we need to find something in an ordered array, but it is Due to this condition, binary search is a very efficient algorithm when making specific elements.
The binary search algorithm can quickly locate the target element 2. Search for elements with a specific attribute: Yes.

Application scenario:

  1. Search At some point we need to search for a specific element in an ordered array: When we need to search for a specific element in an ordered array to find an element that meets a specific condition, such as searching, we can use the binary search algorithm. For example, in an array containing the first element greater than a certain value or looking for a large amount of data, you need to find a certain value, and the binary search algorithm is the closest to a special method that can quickly locate the target element.

2 fixed-value elements, etc., the binary search can quickly locate the elements that meet the conditions.
3. Find the optimal solution: In some problems, database indexing: Binary search is often used, and the solution space of the problem can be applied to database indexing technology. The database uses binary search to quickly sort according to a certain rule and locate the Records that meet certain conditions are found using a binary search algorithm.

In general, the binary search algorithm is the optimal solution. For example, find the smallest or largest value in an ordered array that satisfies a condition that applies to find a specific element in an ordered array.

  1. Scenarios such as searching for elements with certain attributes in a distributed system. Data sharding: In a distributed system, its advantage lies in efficient time complexity and moderateness. Data is usually sharded according to a certain keyword for an ordered array, which can quickly locate the storage of the target element. When you need to find a certain location. For specific data, the binary search algorithm can be used to quickly locate the shard where the data resides, improving the efficiency of data access.

In general, the binary search algorithm is suitable for scenes that need to be searched in an ordered array, and can quickly locate the target element. Its advantage lies in its high efficiency and low time complexity, and it is suitable for searching large-scale data.

Guess you like

Origin blog.csdn.net/2301_77899321/article/details/131594680