Binary search algorithm!

binary search

What is binary search?

Binary search is a relatively efficient search algorithm, but the premise must be an ordered array. The main steps are as follows:

  1. Start from the middle element of the array, if the middle element is exactly the target value, the search ends
  2. If the target value is greater than or less than the middle element, continue the binary search in the half of the array that is greater than or less than the middle element

base case

  • Time complexity: O (logn)
  • Space Complexity: O(1)
Array.prototype.binarySearch = function (target) {
    
    
    let low = 0
    let high = this.length - 1

    while (low <= high) {
    
    
        const mid = Math.floor((low + high) / 2)
        const element = this[mid]

        if (element < target) {
    
    
            low = mid + 1
        } else if (element > target) {
    
    
            high = mid - 1
        } else {
    
    
            return mid
        }
    }

    return -1
}

const res = [1, 2, 3, 4, 5].binarySearch(1) // 0

Since each comparison reduces the search range by half, the time complexity is O(logn). And the space complexity is O(1), since no linearly growing variables are used.

Original Link: Vegetable Garden Front End

Guess you like

Origin blog.csdn.net/qq2603375880/article/details/131687564