Introduction to binary search algorithms and related Python implementation examples, python examples

Source: Internet
Author: User

Introduction to binary search algorithms and related Python implementation examples, python examples

Binary Search idea:
When an ordered table is used to represent a static search table, the search function can be implemented using binary search.
In Binary Search, the interval of the record to be queried is determined first, and then the interval is gradually reduced until the record is found or cannot be found.
The time complexity of 1 binary search is O (log (n), and the worst case is O (n ).
If low points to the lower boundary, high points to the upper boundary, and mid points to the middle of the interval, mid = (low + high)/2;
Specific process:
1. Compare the keyword with the element pointed to by mid. If the keyword is equal, the mid is returned.
2. If the keyword is less than the element keyword pointed to by mid, perform binary search in the [low, mid-1] interval.
3. If the keyword is greater than the element keyword pointed to by mid, perform binary search in the [mid + 1, high] interval.

Binary Search example using Python:

>>> def find(self, num):  l = len(self)  first = 0  end = l - 1  mid = 0  if l == 0:   self.insert(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)    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.