加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C# – 帮助优化循环

发布时间:2020-12-15 23:57:37 所属栏目:百科 来源:网络整理
导读:我有一段代码,原则上如下所示.问题是我触发了数千次的代码10次,需要对其进行更优化.欢迎大家提出意见. //This array is in reality enormous and needs to be triggered loads of times in my codeint[] someArray = { 1,631,632,800,801,1600,1601,2211,221
我有一段代码,原则上如下所示.问题是我触发了数千次的代码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;
}

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

解决方法

数组值看起来已排序.如果确实如此,请使用 binary search:

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读