Skip to content

Commit

Permalink
solved: practicing binary_search 1X -@iamserda
Browse files Browse the repository at this point in the history
  • Loading branch information
iamserda committed Feb 25, 2025
1 parent b9a3e2c commit 9800000
Showing 1 changed file with 13 additions and 9 deletions.
22 changes: 13 additions & 9 deletions neetcodeio/algostructybeginners/Lv4-BinarySearch/search_array1.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,22 @@
import math

import math, random

class Solution:
def binary_search(self, arr, val):
left = 0
right = len(arr) - 1
while left <= right:
mid = int(math.ceil((right - left) // 2))
if arr[mid] == val:
return mid
mid = (right + left) // 2
if val > arr[mid]:


left = mid + 1
elif val < arr[mid]:
right = mid - 1
else:
return mid
return -1

arr = [i for i in range(1, 101)]
arr = [i for i in range(-100, 100)]
sol = Solution()
sol.binary_search(arr, val)
index = sol.binary_search(arr, 10)
assert sol.binary_search(arr, val=10) != -1 # Found
index = sol.binary_search(arr, 400)
assert sol.binary_search(arr, val=400) == -1 # Not Found

0 comments on commit 9800000

Please sign in to comment.