2021-10-22 13:02:39 +02:00
|
|
|
def fibonacci_search int arr, int element
|
2021-11-02 12:41:47 +01:00
|
|
|
n = n.size
|
2021-10-22 13:02:39 +02:00
|
|
|
f2 = 0
|
|
|
|
f1 = 1
|
2021-11-02 12:41:47 +01:00
|
|
|
f = f2 + f1
|
2021-10-22 13:02:39 +02:00
|
|
|
offset = -1
|
|
|
|
|
2021-11-02 12:41:47 +01:00
|
|
|
while f < n do
|
|
|
|
f2 = f1;
|
|
|
|
f1 = f;
|
|
|
|
f = f2 + f1;
|
2021-10-22 13:02:39 +02:00
|
|
|
end
|
|
|
|
|
2021-11-02 12:41:47 +01:00
|
|
|
while f > 1 do
|
|
|
|
i = [offset+f2, n-1].min
|
2021-10-22 13:02:39 +02:00
|
|
|
|
2021-11-02 12:41:47 +01:00
|
|
|
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
|
2021-10-22 13:02:39 +02:00
|
|
|
end
|
2021-11-02 12:41:47 +01:00
|
|
|
end
|
|
|
|
|
|
|
|
return offset + 1 if f1 && arr[offset + 1] == element
|
2021-10-22 13:02:39 +02:00
|
|
|
|
|
|
|
-1
|
|
|
|
end
|