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