algorithm - Search in ordered list -


assume have list 0, 10, 30, 45, 60, 70 sorted in ascending order. given number x how find number in list below it?

i looking efficient (faster) algorithm this, without of course having iterate through whole list.

ex: [0, 10, 30, 45, 60, 70]  given number 34, want return 30. given number 30, want return 30. given number 29, want return 10. 

and forth.

  • if list indeed small, efficient way create array of size 71, initialize once arr[i] = answer, , in constant query time - answer. idea since possible set of queries limited, there no reason not pre-calculate , result pre-calculated data.

  • if cannot pre-process, , array small - linear scan efficient such small array, overhead of using complex algorithm not worth such small arrays. overhead more complex algorithms (like binary search) add lot of instructions per iteration, nullified small arrays. note log_2(6) < 3, , expected time (assuming uniform distribution) result in linear search, linear search simpler, each iteration faster in binary search.

pseudo code:

prev = -infinity (x in arr):    if x>arr:         return prev    prev = x 
  • if array getting larger, use binary search. algorithm designed find value (or first value closest it) in sorted array, , runs in o(logn) time, needing traverse fewer elements entire list.
    it achieve better results (in terms of time performance) compared naive linear scan, assuming uniform distribution of queries.

Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -