Add binary search solution
This commit is contained in:
parent
32db0cd91d
commit
deece0073a
19
README.md
19
README.md
@ -2052,6 +2052,21 @@ Kubernetes is especially good for scenarios when you no longer running small num
|
||||
<summary>Explain big O notation</summary><br><b>
|
||||
</b></details>
|
||||
|
||||
##### Common algorithms
|
||||
|
||||
<details>
|
||||
<summary>Binary search:
|
||||
* How it works?
|
||||
* Can you implement it? (in any language you prefer)
|
||||
* What is the average performance of the algorithm you wrote?</summary><br><b>
|
||||
|
||||
It's a search algorithm used with sorted arrays/lists to find a target value by dividing the array each iteration and comparing the middle value to the target value. If the middle value is smaller than target value, then the target value is searched in the right part of the divided array, else in the left side. This continues until the value is found (or the array divided max times)
|
||||
|
||||
[python implementation](coding/python/binary_search.py)
|
||||
|
||||
The average performance of the above algorithm is O(log n). Best performance can be O(1) and worst O(log n).
|
||||
</b></details>
|
||||
|
||||
##### Code Review
|
||||
|
||||
<details>
|
||||
@ -2398,10 +2413,12 @@ def is_unique4(l:list) -> bool:
|
||||
<summary>How to check how much time it took to execute a certain script or block of code?</summary><br><b>
|
||||
</b></details>
|
||||
|
||||
##### Algorithms Implementation
|
||||
##### Common Algorithms Implementation
|
||||
|
||||
<details>
|
||||
<summary>Can you implement "binary search" in Python?</summary><br><b>
|
||||
|
||||
[Solution](coding/python/binary_search.py)
|
||||
</b></details>
|
||||
|
||||
##### Files
|
||||
|
23
coding/python/binary_search.py
Normal file
23
coding/python/binary_search.py
Normal file
@ -0,0 +1,23 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
import random
|
||||
|
||||
rand_num_li = sorted([random.randint(1, 50) for iter in range(10)])
|
||||
target = random.randint(1, 50)
|
||||
|
||||
def binary_search(li, le, ri, target):
|
||||
if le <= ri:
|
||||
mid = ri + le // 2
|
||||
if li[mid] == target:
|
||||
return mid
|
||||
elif li[mid] < target:
|
||||
return binary_search(li, mid + 1, ri, target)
|
||||
else:
|
||||
return binary_search(li, le, mid - 1, target)
|
||||
else:
|
||||
return -1
|
||||
|
||||
|
||||
print("List: {}\nTarget: {}\nIndex: {}".format(
|
||||
rand_num_li, target,
|
||||
binary_search(rand_num_li, 0, len(rand_num_li) - 1, target)))
|
Loading…
Reference in New Issue
Block a user