Find closest value in a multidim array

Jedidia used Ask the Experts™
I have a multidim array that has hundreds of records and it.
For array(i, 2) the data looks like this:

array(0,2) = 121
array(1,2) = 3121
array(2,2) = 5121
array(3,2) = 6121

I perform a calculation and get a random value of 4010 and want to search the array(I, 2) for the closest (rounded up) value in the array.

What's the best way of going about this.

Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Kyle AbrahamsSenior .Net Developer

Is the array guaranteed to be sorted?

And when you say rounded up the 4010 becomes 5121?


no sorting of the array.

I actually don't care about the calculated value of 4010...I am just looking for the closest value (rounded up) in the array.
Senior .Net Developer
If there's no sorting you have to do a linear search:

Pseudo Code:

int value ' the number you're searching for
int delta = 10000000 'set to a high number
int NextValue = -1

for integer i = 0 to array.length
   if value < array(i, 2)  andalso array(i, 2) - value < delta then
       NextValue = array(i,2)
       delta = array(i,2) - value
   end if
after the loop nextValue will hold the value in the array, -1 not finding anything.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial