From f2091f10d25a973952eb57c6a2c95351aaa0ca5d Mon Sep 17 00:00:00 2001
From: marina <138340846+bt3gl-cryptographer@users.noreply.github.com>
Date: Mon, 7 Aug 2023 22:31:42 -0700
Subject: [PATCH] Update README.md
---
searching/README.md | 87 +++++++++++++++++++++++++++++++++++++++++++--
1 file changed, 84 insertions(+), 3 deletions(-)
diff --git a/searching/README.md b/searching/README.md
index 25fb960..43411c3 100644
--- a/searching/README.md
+++ b/searching/README.md
@@ -60,7 +60,7 @@ def binary_search_recursive(array, item, higher=None, lower=0):
mid = (higher + lower) // 2
- if item == array[mid]:
+ if item == array[mid]:
return mid
elif item < array[mid]:
@@ -72,6 +72,29 @@ def binary_search_recursive(array, item, higher=None, lower=0):
+* or a slightly different version that does not carry `lower` and `higher`:
+
+
+
+```python
+def binary_search_recursive(array, item):
+
+ start, end = 0, len(array)
+ mid = (end - start) // 2
+
+ while len(array) > 0:
+ if array[mid] == item:
+ return True
+ elif array[mid] > item:
+ return binary_search_recursive(array[mid + 1:], item)
+ else:
+ return binary_search_recursive(array[:mid], item)
+
+ return False
+```
+
+
+
---
### in a matrix
@@ -127,10 +150,8 @@ def sqrt(x) -> int:
if num > x:
right = mid - 1
-
elif num < x:
left = mid + 1
-
else:
return mid
@@ -190,3 +211,63 @@ def peak_element(nums):
return left
```
+
+
+
+---
+
+### find a desired sum
+
+
+
+* if the array is sorted:
+
+
+
+```python
+def find_pairs_max_sum(array, desired_sum):
+
+ i, j = 0, len(array) - 1
+
+ while i < j:
+ this_sum = array[i] + array[j]
+ if this_sum == desired_sum:
+ return array[i], array[j]
+ elif this_sum > desired_sum:
+ j -= 1
+ else:
+ i += 1
+
+ return False
+```
+
+
+
+* if the array is not sorted, use a hash table:
+
+
+
+```python
+def find_pairs_not_sorted(array, desired_sum):
+
+ lookup = {}
+
+ for item in array:
+ key = desired_sum - item
+
+ if key in lookup.keys():
+ lookup[key] += 1
+ else:
+ lookup[key] = 1
+
+ for item in array:
+ key = desired_sum - item
+
+ if item in lookup.keys():
+ if lookup[item] == 1:
+ return (item, key)
+ else:
+ lookup[item] -= 1
+
+ return False
+```