Python implements binary search

search

Search is the algorithmic process of finding a specific item in a collection of items. Searching usually answers true or false as the item exists. Several common methods of search: sequential search, binary search, binary tree search, hash search

binary search

Binary search, also known as halved search, has the advantages of less comparison times, fast search speed, and good average performance; its disadvantage is that the table to be looked up is required to be an ordered table, and insertion and deletion are difficult. Therefore, the halved search method is suitable for infrequently changing but frequently searched ordered lists. First, assuming that the elements in the table are arranged in ascending order, compare the keyword recorded in the middle of the table with the search keyword, if the two are equal, the search is successful; otherwise, the table is divided into two sub-tables before and after the middle position record is used, if If the key recorded in the middle position is greater than the search key, the previous sub-table is further searched, otherwise the latter sub-table is further searched. The above process is repeated until a record that satisfies the condition is found, and the search succeeds, or until the subtable does not exist, and the search is unsuccessful at this time.


binary search implementation

def BinarySearchRe(alist, item):
    '''Bichotomy search, recursive implementation'''
    n = len (alist)
    # If the list is empty, the item is not found
    if n == 0:
        return False
    else:
        # middle place
        mid = n // 2
        # equal to the intermediate value, return true directly
        if alist[mid] == item:
            return True
        # If it is less than the middle value, the first half of the slice is taken for recursion
        elif item < alist[mid]:
            return BinarySearchRe(alist[: mid], item)
        # If it is greater than the middle value, take the second half of the slice for recursion
        else:
            return BinarySearchRe(alist[mid + 1:], item)

def BinarySearch(alist, item):
    '''Bichotomy search, implemented by non-recursive conventional methods'''
    n = len (alist)
    # The start and end cursors of the searched sequence
    start, end = 0, n-1
    
    # The searched sequence is not empty
    while start <= end:
        # Get the middle cursor
        mid = (end + start) // 2
        if alist[mid] == item:
            return True
        # If it is less than the middle value, search in the first half of the mid cursor of the original list
        elif item < alist[mid]:
            end = mid - 1
        else:
            start = mid + 1
    return False


if __name__ == '__main__':
    alist = [12, 21, 24, 32, 39, 43, 67, 90]
    # print(BinarySearchRe(alist, 43))
    # print(BinarySearchRe(alist, 100))

    print(BinarySearch(alist, 43))
    print(BinarySearch(alist, 100))

Results of the:

/home/longhui/Desktop/Data Structures and Algorithms/venv/bin/python /home/longhui/Desktop/Data Structures and Algorithms/venv/MyCode/6_sorting_and_searching/binary_search.py
True
False

Process finished with exit code 0

time complexity

  • Optimal time complexity: O(1)
  • Worst time complexity: O(logn)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325695930&siteId=291194637