Code doesn't always find the index.
I'm trying to implement the fibonacci search algorithm in C#. Sometimes the algorithm doesn't find the element in the array. I wrote Unit Tests to check Code coverage and saw that 10 % of my code isn't reached. I also checked other implementations. I think the problem is this part:
if (GetFibonacciNumberOnIndex(index - 1) == 1 && hayStack[offset + 1] == needle)
return offset + 1;
But logically this should run when one last element is left.
public static int FibSearch(int[] hayStack, int needle)
{
if (hayStack == null)
{
throw new ArgumentNullException(nameof(hayStack), "The array containing values to search in mustn't be null");
}
if (hayStack.Length == 0)
{
return -1;
}
int index = 0;
while (GetFibonacciNumberOnIndex(index) < hayStack.Length)
index++;
int offset = -1;
while (GetFibonacciNumberOnIndex(index) > 1)
{
int i = Math.Min(offset + GetFibonacciNumberOnIndex(index - 2), hayStack.Length - 1);
if (needle < hayStack[i])
index -= 2;
else if (needle > hayStack[i])
{
index--;
offset = i;
}
else
return i;
}
if (GetFibonacciNumberOnIndex(index - 1) == needle && hayStack[offset + 1] == needle)
return offset + 1;
return -404;
}
private static int GetFibonacciNumberOnIndex(int index)
{
if (index < 1)
return 0;
else if (index == 1)
return 1;
int first = 0;
int second = 1;
int tmp = 0;
for (int i = 0; i < index; i++)
{
tmp = first;
first = second;
second = tmp + second;
}
return first;
}
}
I have a file with 1000000 numbers. I'm reading the file and converting the content to an integer array. Finally I'm searching for a number, knowing the number is in the array, but the algorithm returns -404. I verified that the number is in the array using Linq Extension Methods on the integer array.