0

I'm having a trouble with what should be a very simple algorithm, but for some reason my head is not working properly (too much work?)

I have an Array of numeric values: [ 10, 20, 30, 40, 100, 1000, 5000, 100000] I want to check which is the next "item" in the array.

For example,

  • given the number 10, my algorithm should return 10.
  • given the number 1, my algorithm should return 10
  • given the number 50, my algorithm should return 100.
  • given the number 99999999, my algorithm should return 100000

In pseudo-code I was thinking:

for previousValue, nextValue in values: 
  if ( previousValue < value && nextValue >= value ):
    return nextValue
return values[max]

If anyone can point out to my exhausted brain what I'm missing it would be great. thanks!

dornad
  • 1,274
  • 3
  • 17
  • 36

4 Answers4

0

Assuming the array is already sorted, your solution works fine. But to make it more clear I would rewrite it as follows:

  prev = 0
  for(v in values){
        if(target > prev && target <= v) 
              return v
        prev = v
  }
  return values[values.length-1] 
Niki
  • 1,105
  • 1
  • 10
  • 17
0

In ruby :

find 0,values.length,val
def find left,right,val
    if left == right || left > right then return values[left]
    if val > values[(right + left)/2]
        find (right + left)/2, right, val
    else
        find left, (right + left)/2, val
    end
end
0

the array need not be sorted. sorting an array has O(nlogn) time complexity. You can check each element in the array in theta(n) time.

Assuming the array is arr and the comparison item is item and the array arr contains at least one element greater than or equal to item:

In java

public static int find_greater(int[] arr,int item)
{
    int j=0;
    int previous =0;
    for(int i=0;i<arr.length;i++){
        if(arr[i]>=item){
            if(j==0){
                previous = arr[i];

             }else{
                 if(arr[i]<previous)
                 {
                     previous = arr[i];
                 }
             }
             j++;

        }
    }
    return previous;
}

Here I go through the array and keep a variable previous which is the smallest number greater or equal item. The running time for this procedure is theta(N) where N is arr.length.

Shikhar Subedi
  • 606
  • 1
  • 9
  • 26
0

I would probably represent this array as a tree. To find out the closest biggest value, I will just look in the tree the same way I will do to find a key, and always keep track of my closest value. When I reach the end of the node, I return the closest value.

This is another alternative, compared to the other answers. You can check it in this thread How to find the closest element to a given key value in a binary search tree?

Community
  • 1
  • 1
Jeremy D
  • 4,787
  • 1
  • 31
  • 38