二分查找算法可以快速搜索大型数字数组,通常被称为分治法。
public class BinarySearch
{
public int BinarySearch(int[] items, int searchValue)
{
int left = 0;
int right = items.Length - 1;
while (left <= right)
{
var middle = (left + right) / 2;
//If the searchValue is in the center, we found it!
if(items[middle] == searchValue)
{
return middle;
}
//If the searchValue is less than the current middle, we set the right to (middle - 1)
//Because the searchValue is in the lower half of the items.
if(searchValue < items[middle])
{
right = middle - 1;
}
//If the searchValue is greater than the current middle, we set the right to (middle + 1)
//Because the searchValue is in the higher half of the items.
else
{
left = middle + 1;
}
} // now that we've either found the item and returned it or we've reset our search boundaries
// we'll search it again.
// Not found.
return -1;
}
} 作者:Chuck Conway 是一位 AI 工程师,拥有近 30 年的软件工程经验。他构建实用的 AI 系统——内容管道、基础设施代理和解决实际问题的工具——并分享他沿途的学习成果。在社交媒体上与他联系:X (@chuckconway) 或访问他的 YouTube 和 SubStack。