in reply to Find a number in a list closest to a target

gnu@perl,
Unfortunately I don't have the time to go find links to all the references I want, but what you want to do is:

  • Sort the epoch times
  • Perform a variation on a binary search

    The variation on the binary search is to also keep track of the offset and not just is it higher or lower. This is proven to be the fastest algorithm for this specific type of search.

    The only trick will be if two items in the list are equidistant from the target number and you would prefer one over the other. In that case you will have to do more work.

    If you would like additional information and can wait until tonight (EST) - drop me a note.

    Cheers - L~R

    • Comment on Re: Find a number in a list closest to a target
  • Replies are listed 'Best First'.
    Re: Re: Find a number in a list closest to a target
    by skyknight (Hermit) on Jul 25, 2003 at 15:02 UTC
      This may or may not be a wholly useful thing to do, depending on some stuff that he didn't state in his problem. It wasn't clear from his description whether or not he would be repeatedly doing searches on the same list, or if he'd be getting a fresh list every time. If he uses the naive method of traversing the whole n element array, this will yield him O(n) for one search, and O(m*n) were he to perform this search m times. With your strategy, in the case of a single search he'd get O(n*lg(n)) (unnecessary overhead because we're doing pre-processing then throwing it away), but in the case of m searches we'd have O(m*lg(n)) + O(n*lg(n)) = O((m+n)*lg(n)) which we can simplify further if we know the relative sizes of m and n. Thus, your idea is fantastic if he meant he'd be repeatedly searching on the same list, but he wasn't clear whether that was the case, so it might turn out to be an investment of pre-computation in a problem that doesn't in fact exist.