Skip to content

Commit

Permalink
GITBOOK-45: Basic binary search
Browse files Browse the repository at this point in the history
  • Loading branch information
VallariAg authored and gitbook-bot committed Jul 20, 2024
1 parent 29848ba commit 022078c
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
1 change: 1 addition & 0 deletions SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@

## Algorithms

* [Binary Search](algorithms/binary-search.md)
* [Sorting](algorithms/sorting.md)
* [Greedy](algorithms/greedy.md)
* [Dynamic Programming](algorithms/dynamic-programming.md)
Expand Down
38 changes: 38 additions & 0 deletions algorithms/binary-search.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# Binary Search

To search in a **sorted arrays**.

#### Interactive 

<pre class="language-python"><code class="lang-python"><strong>class Solution:
</strong> def iterative_binarys(self, nums: List[int], target: int):
p1, p2 = 0, len(nums) - 1
while(p2>=p1):
mid = p1 + ((p2-p1) // 2)
if target == nums[mid]:
return mid
elif target > nums[mid]:
p1 = mid+1
else:
p2 = mid-1
return -1
</code></pre>

#### Recursive

```python
class Solution:
def recursive_binarys(self, nums, target, left, right):
if left > right:
return -1
mid = left + ((right - left) // 2)
if nums[mid] == target:
return mid
elif nums[mid] > target:
return self.recursive_binarys(nums, target, left, mid-1)
else:
return self.recursive_binarys(nums, target, mid+1, right)
```

Note: Do not worry if it's an even numbered arrays, `mid` will reach there (as it checks even 1 length array `[a]` at the end)

0 comments on commit 022078c

Please sign in to comment.