python - Could this recursive binary search algorithm be more efficient? -


i've seen lot of different implementations of algorithm, i'm wondering if there ways improve efficiency beyond making search binary. i've designed particular version of algorithm edges , midpoint of array/list checked key being searched for, avoid looping through search when key looking first, middle, or last element.

def searchrb(the_array, the_key, imin, imax):     print("searching")     found = false     if (0 > the_key or the_key > len(the_array)):         return found     else:         imid = imin + ((imax - imin) // 2)         if imid == the_key or imin == the_key or imax == the_key:             found = true             return found         elif the_array[imid] > the_key:             return searchrb(the_array, the_key, imin, imid-1)         elif the_array[imid] < the_key:             return searchrb(the_array, the_key, imid+1, imax)         else:             return found 

for example, if looking number 1 in list of 1-100, find on first loop, unlike other implementations.

however, i'm not sure if improves efficiency @ (except edge cases), , if checking first, mid, , end values in list/array detrimental once continue loop , have check 3 values every time.

is or bad implementation of type of algorithm, or splitting hairs?

the main big 1 changing recursive approach using while loop, saves having call stack (since python doesn't have tail recursion).

you have small redundancies can optimised. algorithm optimised enough, don't over optimise unless understand compiler

if you're going down tree on left you'll comparing same imin on , over, whole line might parallelised or done sequentially

if the_array[imid] == the_key or the_array[min] == the_key or the_array[imax] == the_key:

also mess cache performance have the_array[min] being kept in cache. compilers store chunk array around index you're trying access in cache. might wasting more cache 1 value.

also statements optimized , type return true , again should picked compiler.

found = true return found

not having found object optimise code because object wouldn't stored in memory whole time.

this else statement seems redundant there's no possible way else else return found

actual relevant optimisations come knowing more dataset.

if able preprocess data (or have more information data) can other algorithms.


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -