Matt C (cr4k) wrote in algorithms,
Matt C
cr4k
algorithms

Finding the nearest in a sorted set of int to a given int

Hi guys,

I'm in the middle of writing a connector to some accounting software and I've been implementing a lazy loading list of proxies because I'm dealing with huge lists of items which load slowly (even the item id s load slowly).

That's not important to the question I am asking though, basically, I want an algorithm which finds either the given search int in my sorted set (of indexes) or the nearest int contained in the list (it doesn't matter, but we can say that the algorithm has a preference for lower numbers if 2 values are equally near)

The essence of the problem is outlined here:


import java.util.TreeSet;

public class Search {
static TreeSet sorted = new TreeSet();

public static void main(String...args){

sorted.add(1);
sorted.add(3);
sorted.add(5);
sorted.add(7);
sorted.add(10);

findNearest(2); // return 1
findNearest(8); // return 7
findNearest(10); // return 10
}

private static Integer findNearest(Integer search) {
return null; //TODO halp pls!
}
}


Thanks for any advice in advance!
  • Post a new comment

    Error

    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

    Your IP address will be recorded 

  • 14 comments