[Algorithm] Dichotomy

1. Dichotomy

1.1 Principle of dichotomy

        Each time the search range is reduced by half until the record is finally found or no record is found and returned.

        Requirement: When using binary search, the data must be sorted.

1.2 Dichotomy idea

        Determine whether a certain number exists in the array (for example: determine whether 3 exists in the array)

       (1) For the sorted array, perform the first round of half division and find the 4th position.

        (2) 3 is smaller than 4, so search to the left, perform the second round of splitting, and find the second position

        (3) 3 is larger than 2, so search to the right and perform the third round of half-dividing, but there is only one position left, so directly determine whether the data is 3 and end the search.

2. Algorithm analysis

2.1 Logical analysis

        Due to its halving rule, if the desired result happens to be in the middle, the result is obtained in one go

        if its

2.2 Time complexity

        Since its operation method is to process it in half each time, its time complexity is

3、code

3.1 java

public static boolean exist(int[] arr, int target) {
        if(arr == null || arr.length == 0){
            return false;
        }
        int left = 0;
        int right = arr.length - 1;
        int mid;
        while (left < right) {
            mid = left + ((right - left) >> 1);
            if (arr[mid] == target) {
                return true;
            } else if (arr[mid] > target) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return arr[left] == target;
    }

3.2 python

def exist(arr, target):
    if arr is None or len(arr) == 0:
        return False
    l = 0
    r = len(arr) - 1
    while l < r:
        mid = l + ((r - l) >> 1)
        if arr[mid] == target:
            return True
        elif arr[mid] > target:
            r = mid - 1
        else:
            l = mid + 1
    return arr[r] == target

Guess you like

Origin blog.csdn.net/weixin_38996079/article/details/135044285