1

1. The concept of binary search

Binary search refers to finding the target element in a sorted array. If the element exists, the index of the element is returned, and if it does not exist, it returns -1.
Let's take ascending order as an example for a brief description

2. Search process:

Take the middle element of the array and compare it with the search element target. If the target is equal to the middle element, the index of the middle element is directly returned. If the target is less than the middle element of the array, it is searched on the left side of the array, and if the target is greater than the middle element of the array, it is searched on the right. Repeat the above steps.

3. Time complexity of binary search

O(logn)

4. Java implementation

4.1 Iterative version

public int searchByLoop(int[] arr, int target) {
    return searchByLoop(arr, 0, arr.length - 1, target);
}

private int searchByLoop(int[] arr, int low, int high, int target) {
    while (low <= high) {
        int mid = (low + high) / 2;
        if (target == arr[mid]) {
            return mid;
        } else if (target < arr[mid]) {
            high = mid - 1;
        } else {
            low = mid + 1;
        }
    }
    return -1;
}

4.2 Recursive version

public int searchByRecursion(int[] arr, int target) {
    return searchByRecursion(arr, 0, arr.length - 1, target);
}


private int searchByRecursion(int[] arr, int low, int high, int target) {
    int mid = (low + high) / 2;
    if (target == arr[mid]) {
        return mid;
    }
    if (low > high) {
        return -1;
    }
    if (target < arr[mid]) {
        return searchByRecursion(arr, low, mid - 1, target);
    }
    return searchByRecursion(arr, mid + 1, high, target);
}

5. Data structure series code address

Github:https://github.com/bennetty74/algorithm-notes


benntty74
49 声望0 粉丝

小透明