#include <iostream>
#include <vector>
using namespace std;
// The function return index of x if present, else return -1
int fibonacciSearch(vector<int> arr, int x)
{
int fib2 = 0, fib1 = 1, fib = 1, n = arr.size();
while (fib < n) // Find the largest fibonacci number less than or equal to array size
{
fib2 = fib1;
fib1 = fib;
fib = fib1 + fib2;
}
int offset = -1; // Marks the eliminated range from front
while (fib > 1)
{
int index = min(offset + fib2, n - 1);
// If x is greater than the value at index fib2, cut the subarray from offset to index
if (arr[index] < x) // Skip the left
{
fib = fib1;
fib1 = fib2;
fib2 = fib - fib1;
offset = index;
}
// If x is less
else if (arr[index] > x) // Skip the right
{
fib = fib2;
fib1 = fib1 - fib2;
fib2 = fib - fib1;
}
else return index; // Found the element
}
if (fib1 > 0 && arr[offset + 1] == x) return offset + 1; // Compare the last element with x
return -1; // Not found
}
int main()
{
vector<int> arr{0, 4, 5, 7, 9, 12, 13};
cout << fibonacciSearch(arr, 11);
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8dmVjdG9yPgp1c2luZyBuYW1lc3BhY2Ugc3RkOwoKLy8gVGhlIGZ1bmN0aW9uIHJldHVybiBpbmRleCBvZiB4IGlmIHByZXNlbnQsIGVsc2UgcmV0dXJuIC0xCmludCBmaWJvbmFjY2lTZWFyY2godmVjdG9yPGludD4gYXJyLCBpbnQgeCkKewogICAgaW50IGZpYjIgPSAwLCBmaWIxID0gMSwgZmliID0gMSwgbiA9ICBhcnIuc2l6ZSgpOwoKICAgIHdoaWxlIChmaWIgPCBuKSAvLyBGaW5kIHRoZSBsYXJnZXN0IGZpYm9uYWNjaSBudW1iZXIgbGVzcyB0aGFuIG9yIGVxdWFsIHRvIGFycmF5IHNpemUKICAgIHsKICAgICAgICBmaWIyID0gZmliMTsKICAgICAgICBmaWIxID0gZmliOwogICAgICAgIGZpYiA9IGZpYjEgKyBmaWIyOwogICAgfQoKICAgIGludCBvZmZzZXQgPSAtMTsgLy8gTWFya3MgdGhlIGVsaW1pbmF0ZWQgcmFuZ2UgZnJvbSBmcm9udAoKICAgIHdoaWxlIChmaWIgPiAxKQogICAgewogICAgICAgIGludCBpbmRleCA9IG1pbihvZmZzZXQgKyBmaWIyLCBuIC0gMSk7CgogICAgICAgIC8vIElmIHggaXMgZ3JlYXRlciB0aGFuIHRoZSB2YWx1ZSBhdCBpbmRleCBmaWIyLCBjdXQgdGhlIHN1YmFycmF5IGZyb20gb2Zmc2V0IHRvIGluZGV4CiAgICAgICAgaWYgKGFycltpbmRleF0gPCB4KSAvLyBTa2lwIHRoZSBsZWZ0CiAgICAgICAgewogICAgICAgICAgICBmaWIgPSBmaWIxOwogICAgICAgICAgICBmaWIxID0gZmliMjsKICAgICAgICAgICAgZmliMiA9IGZpYiAtIGZpYjE7CiAgICAgICAgICAgIG9mZnNldCA9IGluZGV4OwogICAgICAgIH0KCiAgICAgICAgLy8gSWYgeCBpcyBsZXNzCiAgICAgICAgZWxzZSBpZiAoYXJyW2luZGV4XSA+IHgpIC8vIFNraXAgdGhlIHJpZ2h0CiAgICAgICAgewogICAgICAgICAgICBmaWIgPSBmaWIyOwogICAgICAgICAgICBmaWIxID0gZmliMSAtIGZpYjI7CiAgICAgICAgICAgIGZpYjIgPSBmaWIgLSBmaWIxOwogICAgICAgIH0KCiAgICAgICAgZWxzZSByZXR1cm4gaW5kZXg7IC8vIEZvdW5kIHRoZSBlbGVtZW50CiAgICB9CiAgICAKICAgIGlmIChmaWIxID4gMCAmJiBhcnJbb2Zmc2V0ICsgMV0gPT0geCkgcmV0dXJuIG9mZnNldCArIDE7IC8vIENvbXBhcmUgdGhlIGxhc3QgZWxlbWVudCB3aXRoIHgKCiAgICByZXR1cm4gLTE7IC8vIE5vdCBmb3VuZAp9CgppbnQgbWFpbigpCnsKICAgIHZlY3RvcjxpbnQ+IGFycnswLCA0LCA1LCA3LCA5LCAxMiwgMTN9OwoKICAgIGNvdXQgPDwgZmlib25hY2NpU2VhcmNoKGFyciwgMTEpOwoKICAgIHJldHVybiAwOwp9