Simple implementation of binary search

Simply record the implementation of binary search

Article Directory

foreword

1. What is binary search?

2. Code implementation

Summarize


foreword

One day, Liuhua came to a company for an interview, and the interviewer said: "Give you an ordered array of integers and a value, and you can write a simple query to return the subscript." When you heard this, you burst into laughter until the back of your head. Take out the keyboard and type a for loop to traverse the query. When the interviewer saw it, he nodded and said to you earnestly: "Young man, I see that your bones are good. Go back and wait for the news. I think you have a great chance!" After you heard this, you went home excitedly and waited for the news, thinking "It's just an interview, but that's it..." From then on, there was no more follow-up.

1. What is binary search?

Given a value, query an ordered integer array , such as [1, 2, 3, 4, 5, 6, 7, 8], you need to find the position (subscript) corresponding to 5. Select the number in the middle of the array (4 here) and compare it with the target value to be searched, and return the answer (subscript) directly if they are equal. If not, two cases should be considered:

1) If the number in the middle is greater than the target value, all numbers to the right of the middle number are greater than the target value , all excluded

2) If the number in the middle is less than the target value, all numbers to the left of the middle number are less than the target value , all excluded

Then it goes on like this.

Note: It has been emphasized many times here that is an ordered integer array. After all, if it is not ordered, it cannot be determined that the number on the other side of the middle number can be completely greater than (less than) the target number and then excluded . Secondly, the target value of the query can only be one , not multiple.

2. Code implementation

The opening and closing of binary search are different, and the corresponding iteration methods are also different. There are the following two methods:

  • Close left and close right[left, right]

  • Left closed right open [left, right)

 The left-close and right-close code is as follows:

    private static int binarySearch(int target, int[] arry) {
        int left = 0, right = arry.length - 1;
        while (left <= right){
            int mid = (left + right) >>> 1;
            if (arry[mid] == target){
                return mid;
            } else if (arry[mid] < target) {
                left = mid + 1;
            } else if (arry[mid] > target) {
                right = mid - 1;
            }
        }
        return -1;
    }

The difference between left-closed and right-open is that the right boundary of the array selects the length of the array, while the boundary of left-closed and right-close selects the array length -1. There is also the judgment of the loop condition. For details, please see: [Binary Search] Detailed Diagram_Charon_cc's Blog-CSDN Blog

code show as below:

    private static int binarySearch(int target, int arry[])
    {
        int left = 0;
        int right = arry.length; //定义target在左闭右开的区间里,即[left, right)
        while (left < right) {	//因为left = right的时候,在[left, right)区间上无意义
            int middle = (left + right) >>> 1;
            if (arry[middle] > target) {
                right = middle; //target 在左区间,在[left, middle)中 
            } else if (arry[middle] < target) {
                left = middle + 1;
            } else {
                return middle;
            }
        }
        // 没找到就返回-1
        return -1;
    }

test:

Given an ordered (ascending) integer array nums with n elements and a target value target, write a function to search the target in nums, and return the subscript if the target value exists, otherwise return -1.

Example one:

Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 appears in nums with subscript 4

result:

Example two:

Input: nums = [-1,0,3,5,9,12], target = 2
Output: -1
Explanation: 2 does not exist in nums so return -1

result:


Summarize

The two most important points of binary search are the loop condition and the subsequent interval assignment problem.

The two are interrelated and affect each other, so they need to be unified. If the two are not unified, problems will arise.

Therefore, the loop condition and the assignment problem must be unified, that is, the loop invariant.

Guess you like

Origin blog.csdn.net/weixin_58403235/article/details/129843775
Recommended