在圆形数组中搜索的最佳方法是什么?
Example 1 array : 45 67 44 11 49 4 56 12 39 90
circular array 11, 49, 4, 56, 12, 39, 90, 45, 67
二进制搜索是正确的开始方法吗?
在圆形数组中搜索的最佳方法是什么?
Example 1 array : 45 67 44 11 49 4 56 12 39 90
circular array 11, 49, 4, 56, 12, 39, 90, 45, 67
二进制搜索是正确的开始方法吗?
有同样的问题,如果不运行两次搜索就看不到使用内置函数的方法,所以编写了一个自定义函数。
可能有一种方法可以更快地进行超出范围检查,但这符合我的目的。(不想复制带有负索引内容的标准二进制搜索接口,因为消费者将其转换回循环缓冲区上的真实索引会很痛苦)
public bool BinarySearchCircular<T>(T[] array, T searchValue, int head, out int lowerIndex, out int upperIndex) where T : IComparable<T>
{
int bottom = 0;
int top = (int)array.Length - 1;
int count = (int)array.Length;
int middle = top >> 1;
while (top >= bottom)
{
int middleIndex = (middle + head) % count;
if (array[middleIndex].CompareTo(searchValue) == 0)
{
upperIndex = middleIndex;
lowerIndex = middleIndex;
return true;
}
else if (array[middleIndex].CompareTo(searchValue) > 0)
{
top = middle - 1;
}
else
{
bottom = middle + 1;
}
middle = (bottom + top) >> 1;
}
if(array[head].CompareTo(searchValue) < 0)
{
lowerIndex = head;
upperIndex = -1;
}
else if(array[(head+1) % count].CompareTo(searchValue) > 0)
{
upperIndex = (head+1) % count;
lowerIndex = -1;
}
else
{
lowerIndex = (top + head) % count;
upperIndex = (bottom + head) % count;
}
return false;
}
二进制搜索仅在数组已排序时才有用。
您没有提供有关问题域的太多信息,但一种方法是使用集合(或哈希表)。对于您放入数组中的每个数字,也将其插入集合中。集合(或哈希表)中的查找在恒定时间内发生,因此没有“搜索”。当您从数组中删除一个项目时,也将它从集合中删除。如果您的循环缓冲区在填满时覆盖了值,请确保它也更新集合以删除覆盖的值。
如果你不能使用其他数据结构,那么你能做的最好的就是对数组进行线性扫描。