Bojan Kogoj Bojan Kogoj - 17 days ago 7
C# Question

Find equal or nearest smaller value from an array

Let's suppose I have this array (it is actually 255 long, values up to int.MaxValue):

int[] lows = {0,9,0,0,5,0,0,8,4,1,3,0,0,0,0};


From this array I would like to get index of a value equal or smaller to my number.

number = 7 -> index = 4
number = 2 -> index = 9
number = 8 -> index = 7
number = 9 -> index = 1


What would be the fastest way of finding it?

So far I've used linear search, but that turned out to be too inefficient for my need, because even though this array is only 255 long, values will be searched for a few million times.

I would need something equal to TreeSet.floor(E) used in java. I wanted to use Dictionary, but i don't know if it can find first smaller or equal value like I need.

Answer

Sort the array and then do a binary search to find the values.

See:

https://en.wikipedia.org/wiki/Binary_search

and

Array.BinarySearch Method