C# - 帮助优化循环

Blu*_*doo 3 .net c#

我有一段代码,原则上如下所示.问题是我触发了数千次的代码10次,需要对其进行更优化.欢迎大家提出意见.

//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;
}
Run Code Online (Sandbox Code Playgroud)

编辑:抱歉条件错了.它应该在806大于801时返回id.希望你能理解它.

Kon*_*lph 10

数组值看起来已排序.如果确实如此,请使用二分搜索:

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

如果搜索的值未出现在数组中,Array.BinarySearch则将返回下一个更大值索引的按位补码.这就是我在上面的代码中测试负数并使用按位补码运算符的原因.结果应该与您的代码中的结果相同.

二进制搜索具有对数运行时间而不是线性.也就是说,在最坏的情况下,只需要搜索2 n个条目而不是n(其中n是数组的大小).