Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the closest number in a list of numbers

Tags:

c#

algorithm

I have a list of constant numbers. I need to find the closest number to x in the list of the numbers. Any ideas on how to implement this algorithm?

like image 707
Alon Gubkin Avatar asked Jan 01 '10 16:01

Alon Gubkin


1 Answers

Well, you cannot do this faster than O(N) because you have to check all numbers to be sure you have the closest one. That said, why not use a simple variation on finding the minimum, looking for the one with the minimum absolute difference with x?

If you can say the list is ordered from the beginning (and it allows random-access, like an array), then a better approach is to use a binary search. When you end the search at index i (without finding x), just pick the best out of that element and its neighbors.

like image 182
R. Martinho Fernandes Avatar answered Sep 21 '22 18:09

R. Martinho Fernandes