Hi to all, I was wandering which is the best way to found the closer number in an array. OK not exactly the closer number, I explain my self:
For example I have the array:
Index: 0 1 2 3
Numbers: 750 500 300 200

* If I receive the number 730, I should return 500(or index 1)
I should return 500 because 730 is smaller that 750

* If I receive the number 750 or 760, I should return 750(or index 0)
I should return 750 because 760 is bigger that 750

* If I receive the number 100, I should return nothing (or index -1)
I should return nothing because 100 is smaller that 200

I look into the search techniques and I didn't found any that work this way.
I search for the number in a linear way, there is a better way.
I did the following:

for (int i=0; i<array.size;i++)
  {
  if(valuetoSearch >= array[i])
  {
  value= array[i];
  break;
  }
  }
Member Avatar for iamthwee

huh. Is there actually any logic in your example.

You're close. try this formatted code:

value = -1;  initialize the return value to NOT FOUND
  for (int i=0; i<array.size;i++)
  {
      if(valuetoSearch >= array[i])
      {
          value= i;    // if you want to return the index
          break;     
      }
  }

Sort your vector.
If the input number (assume it is x) is smaller than the 0th element return array[0].
If x>the last element from the vector, return array[last].
Else pass through the vector, until you found a value which is larger than x. Suppose this number is at index j. Then calculate array[j]-x and x-array[j-1]. The smallest number will be returned.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.