![]() |
VOOZH | about |
Given a sorted array arr[] of size n and an integer x. Your task is to check if the integer x is present in the array arr[] or not. Return index of x if it is present in array else return -1.
Examples:
Input: arr[] = [2, 3, 4, 10, 40], x = 10
Output: 3
Explanation: 10 is present at index 3.Input: arr[] = [2, 3, 4, 10, 40], x = 11
Output: -1
Explanation: 11 is not present in the given array.
Fibonacci Search is a comparison-based technique that uses Fibonacci numbers to search an element in a sorted array.
Similarities of Fibonacci Search with Binary Search
Differences of Fibonacci Search with Binary Search
Background
Fibonacci Numbers are recursively defined as F(n) = F(n-1) + F(n-2), F(0) = 0, F(1) = 1. First few Fibonacci Numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ...
Below observation is used for range elimination, and hence for the O(log(n)) complexity.
F(n - 2) β (1/3)*F(n) and (Note : This is an approximation, not equal)
F(n - 1) β (2/3)*F(n).
The idea is to first find the smallest Fibonacci number that is greater than or equal to the length of the given array. Let the found Fibonacci number be fib (mβth Fibonacci number). We use (m-2)βth Fibonacci number as the index. Let (m-2)βth Fibonacci Number be i, we compare arr[i] with x, if x is same, we return i. Else if x is greater, we recur for subarray after i, else we recur for subarray before i.
Let arr[0..n-1] be the input array and the element to be searched be x.
3
Illustration:
Let us understand the algorithm with the below example:
Illustration assumption: 1-based indexing. Target element x is 85. Length of array n = 11.
Smallest Fibonacci number greater than or equal to 11 is 13. As per our illustration, fibMm2 = 5, fibMm1 = 8, and fibM = 13.
Another implementation detail is the offset variable (zero-initialized). It marks the range that has been eliminated, starting from the front. We will update it from time to time.
Now since the offset value is an index and all indices including it and below it have been eliminated, it only makes sense to add something to it. Since fibMm2 marks approximately one-third of our array, as well as the indices it marks, are sure to be valid ones, we can add fibMm2 to offset and check the element at index i = min(offset + fibMm2, n).
Visualization:
Time Complexity analysis:
The worst-case will occur when we have our target in the larger (2/3) fraction of the array, as we proceed to find it. In other words, we are eliminating the smaller (1/3) fraction of the array every time. We call once for n, then for(2/3) n, then for (4/9) n, and henceforth.
Consider that:
Auxiliary Space: O(1)