C # - help in loop optimization

I have a piece of code that basically looks like this. The problem is that I run this code 10 thousand times and need to optimize it. Any suggestions are welcome.

//This array is in reality enormous and needs to be triggered loads of times in my code
int[] someArray = { 1, 631, 632, 800, 801, 1600, 1601, 2211, 2212, 2601, 2602 };

//I need to know where in the array a certain value is located
//806 is located between entry 801 and 1600 so I want the array ID of 801 to be returned (4).
id = 806

//Since my arrays are very large, this operation takes far too long 
for (int i = 0; i < someArrayLenght; i++)
{
  if (someArray[i] <= id)
    return i;
}

Edit: Sorry the condition was incorrect. It should return an identifier when 806 is greater than 801. I hope you can make sense from it.

+3
source share
2 answers

Array values ​​look sorted. If so, use a binary search :

int result = Array.BinarySearch(someArray, id);
return result < 0 ? (~result - 1) : result;

, Array.BinarySearch . . , .

. , log 2 n n ( n - ).

+10

someArray , - . Array.BinarySearch.

. if (someArray[i] <= id) return i; , id >= 1. , .

+2

All Articles