Add binary search solution

This commit is contained in:
abregman 2019-12-02 20:54:31 +02:00
parent 32db0cd91d
commit deece0073a
2 changed files with 41 additions and 1 deletions

View File

@ -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> <summary>Explain big O notation</summary><br><b>
</b></details> </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 ##### Code Review
<details> <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> <summary>How to check how much time it took to execute a certain script or block of code?</summary><br><b>
</b></details> </b></details>
##### Algorithms Implementation ##### Common Algorithms Implementation
<details> <details>
<summary>Can you implement "binary search" in Python?</summary><br><b> <summary>Can you implement "binary search" in Python?</summary><br><b>
[Solution](coding/python/binary_search.py)
</b></details> </b></details>
##### Files ##### Files

View 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)))