forked from TheAlgorithms/C-Sharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FibonacciSearcher.cs
89 lines (77 loc) · 3.2 KB
/
FibonacciSearcher.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
using System;
namespace Algorithms.Search;
/// <summary>
/// Class that implements Fibonacci search algorithm.
/// </summary>
/// <typeparam name="T">Type of array element.</typeparam>
public class FibonacciSearcher<T> where T : IComparable<T>
{
/// <summary>
/// Finds the index of the item searched for in the array.
/// Time complexity:
/// worst-case: O(log n),
/// average-case: O(log n),
/// best-case: O(1).
/// </summary>
/// <param name="array">Sorted array to be searched in. Cannot be null.</param>
/// <param name="item">Item to be searched for. Cannot be null.</param>
/// <returns>If an item is found, return index. If the array is empty or an item is not found, return -1.</returns>
/// <exception cref="ArgumentNullException">Gets thrown when the given array or item is null.</exception>
public int FindIndex(T[] array, T item)
{
if (array is null)
{
throw new ArgumentNullException("array");
}
if (item is null)
{
throw new ArgumentNullException("item");
}
var arrayLength = array.Length;
if (arrayLength > 0)
{
// find the smallest Fibonacci number that equals or is greater than the array length
var fibonacciNumberBeyondPrevious = 0;
var fibonacciNumPrevious = 1;
var fibonacciNum = fibonacciNumPrevious;
while (fibonacciNum <= arrayLength)
{
fibonacciNumberBeyondPrevious = fibonacciNumPrevious;
fibonacciNumPrevious = fibonacciNum;
fibonacciNum = fibonacciNumberBeyondPrevious + fibonacciNumPrevious;
}
// offset to drop the left part of the array
var offset = -1;
while (fibonacciNum > 1)
{
var index = Math.Min(offset + fibonacciNumberBeyondPrevious, arrayLength - 1);
switch (item.CompareTo(array[index]))
{
// reject approximately 1/3 of the existing array in front
// by moving Fibonacci numbers
case > 0:
fibonacciNum = fibonacciNumPrevious;
fibonacciNumPrevious = fibonacciNumberBeyondPrevious;
fibonacciNumberBeyondPrevious = fibonacciNum - fibonacciNumPrevious;
offset = index;
break;
// reject approximately 2/3 of the existing array behind
// by moving Fibonacci numbers
case < 0:
fibonacciNum = fibonacciNumberBeyondPrevious;
fibonacciNumPrevious = fibonacciNumPrevious - fibonacciNumberBeyondPrevious;
fibonacciNumberBeyondPrevious = fibonacciNum - fibonacciNumPrevious;
break;
default:
return index;
}
}
// check the last element
if (fibonacciNumPrevious == 1 && item.Equals(array[^1]))
{
return arrayLength - 1;
}
}
return -1;
}
}