Fast algorithm for finding the next smallest and largest number in a set

I have a set of positive numbers. Given a number not in the set, I want to find the next smallest and the next largest numbers that are in the set. The only way I can do this now is to find the next minimum, decreasing by 1, until I find the number in the set, and then do the same to find the next largest one.

Motivation: I have a bunch of data in a hash map using dates. I have no data for each date. If I have data, for example, 10/01/2000 as 60 and 10/05/2000 as 68, and I ask for 10/02/2000, I want to interpolate linearly. I have to get 62.

+3
source share
9 answers

It depends on whether your set is sorted.

If your set is unsorted, then finding the nearest one (above and below) is an O (n) operation and a fairly simple algorithm.

If your set is sorted, you can use a modified bisection search to find the answer in O (log n), which is obviously much better, especially on large sets.

If you do this several times, it might be worth sorting a set that carries the cost of O (n log n), which can be disabled or not, depending on how often the set changes. Some kind of tree can help improve future views as new elements are added.

+4
source

, . .

O (logn). O (nlogn) . n ; , sort().

, , , O (n).

+3

, AVL tree, - B +/B-. .

+1

, , . , .

+1

, , . , , , . n, n , n+1 .

, , . , , floorEntry() () Java TreeMap.

+1

/ : , Python bisect Python .

+1

, , . , - , .

, .

( , , , . , , , ).

0

n- - O (n). (Select Algorithm) , . , , .. - O (n). ( ...)

, O (n log n)

- O (log n) ( )

0

, , , , HashMap , ... , 14 - ( 7 ), O (1).

, , , , . , , .

0

Source: https://habr.com/ru/post/1708967/


All Articles