Search sorted List<Long> for closest and less than

Total Post:19

Points:133
C# 
C#
 1579  View(s)
Ratings:
Rate this:

Consider some long called X and a sorted List<Long>. What is the most efficient algorithm to find the index or value in the List<Long> that is (i) less than X, and (ii) The closest to X on the number line (assuming condition (i) has been satsified)?

For example this could be a problem setup:

long X = 500;

List<Long> foo = new Arraylist<Long>();
foo.add(450L);
foo.add(451L);
foo.add(499L);
foo.add(501L);
foo.add(550L);

Collections.sort(foo); // It's always sorted.

I would like the algorithm to either return 499 or to return the index associated with 499 (in this casei=2).

  1. Post:12

    Points:84
    Re: Search sorted List<Long> for closest and less than

    If 499 is unique than, use indexOf(Object) method.

      Modified On Mar-31-2018 06:01:59 AM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!