How to use 'pseudo code for binary search' in Python

Every line of 'pseudo code for binary search' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Python code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
13def binary_search(array, query):
14 lo, hi = 0, len(array) - 1
15 while lo <= hi:
16 mid = lo + (hi - lo) // 2
17 val = array[mid]
18
19 # If the element is present at the middle itself
20
21 if val == query:
22 return mid
23
24 # If element is smaller than mid, then
25 # it can only be present in right subarray
26
27 elif val < query:
28 lo = mid + 1
29
30 # Else the element can only be present
31 # in left subarray
32
33 else:
34 hi = mid - 1
35
36 # We reach here when element is not
37 # present in array
38
39 return None
45def search(self,key,node = None):
46
47 if node is None:
48 node = self.root
49
50 if self.root.key == key:
51 print "key is at the root"
52 return self.root
53
54 else:
55 if node.key == key :
56 print "key exists"
57 return node
58
59 elif key < node.key and node.left is not None:
60 print "left"
61 return self.search(key,node = node.left)
62
63 elif key > node.key and node.right is not None:
64 print "right"
65 return self.search(key,node = node.right)
66
67 else:
68 print "key does not exist"
69 return None

Related snippets