mirror of
https://github.com/TheAlgorithms/Ruby
synced 2024-12-25 21:58:57 +01:00
add fibonacci search
This commit is contained in:
parent
af40ff3628
commit
7fbd71df1f
1 changed files with 34 additions and 0 deletions
34
searches/fibonacci_search.rb
Normal file
34
searches/fibonacci_search.rb
Normal file
|
@ -0,0 +1,34 @@
|
||||||
|
def fibonacci_search int arr, int element
|
||||||
|
n = n.size
|
||||||
|
f2 = 0
|
||||||
|
f1 = 1
|
||||||
|
f = f2 + f1
|
||||||
|
offset = -1
|
||||||
|
|
||||||
|
while f < n do
|
||||||
|
f2 = f1;
|
||||||
|
f1 = f;
|
||||||
|
f = f2 + f1;
|
||||||
|
end
|
||||||
|
|
||||||
|
while f > 1 do
|
||||||
|
i = [offset+f2, n-1].min
|
||||||
|
|
||||||
|
if arr[i] < element
|
||||||
|
f = f1
|
||||||
|
f1 = f2
|
||||||
|
f2 = f - f1
|
||||||
|
offset = i
|
||||||
|
elsif arr[i] > element
|
||||||
|
f = f2
|
||||||
|
f1 = f1 - f2
|
||||||
|
f2 = f - f1
|
||||||
|
else
|
||||||
|
return i
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
return offset + 1 if f1 && arr[offset + 1] == element
|
||||||
|
|
||||||
|
-1
|
||||||
|
end
|
Loading…
Reference in a new issue