Introduction to binary lookup algorithms and related Python implementation examples

Source: Internet
Author: User
Binary Search Idea:
When a static lookup table is represented by an ordered table, the lookup function can be implemented with a binary lookup.
Binary search finds the process by determining the interval of the unknown origin record, and then gradually narrowing the interval until it is found or cannot be found.
The time complexity of the 12-point lookup is O (log (n)), and the worst-case time complexity is O (n).
Assuming that the low is pointing to the lower bound of the interval, high points to the upper bounds, and mid to the middle of the interval, then mid = (low + high)/2;
Specific process:
1. Compare the keyword to the element that the mid points to and return to mid if it is equal.
2. The keyword is smaller than the element keyword that the mid points to, then the binary lookup is continued in the [Low, mid-1] interval.
3. The keyword is larger than the element keyword that is pointing to mid, and the binary search continues in the [mid +1, high] interval.

Using Python to achieve a binary search example:

>>> def find (self, num):  l = len (self) First  = 0  end = l-1  mid = 0  if L = = 0:   self.inse  RT (0,num)   return False while first  < end:   mid = (first + end)/2   if num > Self[mid]: First    = mid  + 1   elif num < Self[mid]:    end = mid-1   else:    break  if first = = end:   if Self[first] > Num:    self.insert (First, num)    return False   elif Self[first] < num:    self.insert (first + 1, num) C21/>return False   Else:    return True  elif first > End:   self.insert (First, num)   return False  Else:   return true>>> list_d = [' A ', ' B ', ' C ', ' d ', ' e ', ' f ', ' d ', ' t ']>>> value_d = ' t ' >>> Aa=find (list_d,value_d) >>> aatrue>>> value_d= ' ha ' >>> aa=find (list_d,value_ d) >>> Aafalse
  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.