From deece0073ae6486260c330ea870f92d514254558 Mon Sep 17 00:00:00 2001 From: abregman Date: Mon, 2 Dec 2019 20:54:31 +0200 Subject: [PATCH] Add binary search solution --- README.md | 19 ++++++++++++++++++- coding/python/binary_search.py | 23 +++++++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 coding/python/binary_search.py diff --git a/README.md b/README.md index e9a429c..ed7b465 100644 --- a/README.md +++ b/README.md @@ -2052,6 +2052,21 @@ Kubernetes is especially good for scenarios when you no longer running small num Explain big O notation
+##### Common algorithms + +
+Binary search: + * How it works? + * Can you implement it? (in any language you prefer) + * What is the average performance of the algorithm you wrote?
+ +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). +
+ ##### Code Review
@@ -2398,10 +2413,12 @@ def is_unique4(l:list) -> bool: How to check how much time it took to execute a certain script or block of code?
-##### Algorithms Implementation +##### Common Algorithms Implementation
Can you implement "binary search" in Python?
+ +[Solution](coding/python/binary_search.py)
##### Files diff --git a/coding/python/binary_search.py b/coding/python/binary_search.py new file mode 100644 index 0000000..cd9601c --- /dev/null +++ b/coding/python/binary_search.py @@ -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)))