# Fast searching through an array

Let's say that I have an array of doubles, for example double[] foo = double[] {1.3, 4.5, 8.12, 10.1};

Just assume the doubles are in increasing order.

Can you guys make me a fast algorithm (function) that takes two parameters, a double array and a double, and returns the lowest element in the array that is greater than or equal to that given double? By lowest element, I actually mean the "index of the lowest element".

Phrased more clearly: Let a_0, a_1, ..., a_n  be positive real numbers.  Let  a  be a positive real number. Find the least i such that  a_i >= a.

Is there any faster way to do this than just for-looping through the array?

Notice that the beast should be fast in the sense that the array is constant throughout, but the double (that I call a above) is changing alot and I will always need to find such a "least index" for different a's loads of times over and over again.
C#

Last Comment
dedekind
Jaime Olivares

THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
margajet24

since it is ordered, like jaime_olivares have said, use binary search.

or if you dont like to use that try to copy the content of your array to a List variable then use Find() or FindAll() but these functions would iterate on your items internally..
light3268

I would convert to a List using the array.ToList() command or start out using a list.  I would then use the List.Sort() command and then iterate through the List until you find the first one that it greater than your number.  Then break out of the loop as you found what you are looking for.  This way you don't have to iterate through the entire sequence of numbers.
dedekind

Ok thanks for telling me about binary search!
C#

C# is an object-oriented programming language created in conjunction with Microsoft’s .NET framework. Compilation is usually done into the Microsoft Intermediate Language (MSIL), which is then JIT-compiled to native code (and cached) during execution in the Common Language Runtime (CLR).

98K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts

TRUSTED BY