-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
solved: practicing binary_search 1X -@iamserda
- Loading branch information
Showing
1 changed file
with
13 additions
and
9 deletions.
There are no files selected for viewing
22 changes: 13 additions & 9 deletions
22
neetcodeio/algostructybeginners/Lv4-BinarySearch/search_array1.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |