代码拉取完成,页面将自动刷新
namespace Algorithms.Search;
/// <summary>
/// Class that implements interpolation search algorithm.
/// </summary>
public static class InterpolationSearch
{
/// <summary>
/// Finds the index of the item searched for in the array.
/// Algorithm performance:
/// worst-case: O(n),
/// average-case: O(log(log(n))),
/// best-case: O(1).
/// </summary>
/// <param name="sortedArray">Array with sorted elements to be searched in. Cannot be null.</param>
/// <param name="val">Value to be searched for. Cannot be null.</param>
/// <returns>If an item is found, return index, else return -1.</returns>
public static int FindIndex(int[] sortedArray, int val)
{
var start = 0;
var end = sortedArray.Length - 1;
while (start <= end && val >= sortedArray[start] && val <= sortedArray[end])
{
var denominator = (sortedArray[end] - sortedArray[start]) * (val - sortedArray[start]);
if (denominator == 0)
{
denominator = 1;
}
var pos = start + (end - start) / denominator;
if (sortedArray[pos] == val)
{
return pos;
}
if (sortedArray[pos] < val)
{
start = pos + 1;
}
else
{
end = pos - 1;
}
}
return -1;
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。