Fibonacci search is a comparison-based technique that uses Fibonacci numbers to search an element in a sorted array. It divides the array into unequal parts, using only addition and subtraction to calculate split points—making it potentially faster than binary search on some architectures.
Fibonacci Search is a divide-and-conquer algorithm designed for sorted arrays. Unlike Binary Search, which always divides the segment in half, Fibonacci search uses Fibonacci numbers to divide the range into two parts of unequal lengths.
While binary search requires division (often bitwise shift) to find the midpoint, Fibonacci search relies only on addition and subtraction. Historically, this made it efficient on hardware where division operations were significantly slower than addition.
F(m) = F(m-1) + F(m-2)
split = min(offset + F(m-2), n-1)
* offset represents the eliminated range from the left.
Here is the standard iterative implementation of Fibonacci Search. It first finds the smallest Fibonacci number strictly greater than or equal to the array length, and then proceeds with splits.
1def fibonacci_search(arr, x):2 n = len(arr)3 # Initialize fibonacci numbers4 fibSumM2 = 0 5 fibSumM1 = 1 6 fibSum = fibSumM2 + fibSumM1 7 8 while (fibSum < n):9 fibSumM2 = fibSumM110 fibSumM1 = fibSum11 fibSum = fibSumM2 + fibSumM112 13 offset = -114 15 while (fibSum > 1):16 i = min(offset + fibSumM2, n-1)17 18 if (arr[i] < x):19 fibSum = fibSumM120 fibSumM1 = fibSumM221 fibSumM2 = fibSum - fibSumM122 offset = i23 elif (arr[i] > x):24 fibSum = fibSumM225 fibSumM1 = fibSumM1 - fibSumM226 fibSumM2 = fibSum - fibSumM127 else:28 return i29 30 if(fibSumM1 and arr[offset+1] == x):31 return offset+132 33 return -1JavaScript Implementation:
1function fibonacciSearch(arr, x) {2 let n = arr.length;3 let fibMM2 = 0; // (m-2)'th Fibonacci No.4 let fibMM1 = 1; // (m-1)'th Fibonacci No.5 let fibM = fibMM2 + fibMM1; // m'th Fibonacci6 7 while (fibM < n) {8 fibMM2 = fibMM1;9 fibMM1 = fibM;10 fibM = fibMM2 + fibMM1;11 }12 13 let offset = -1;14 15 while (fibM > 1) {16 let i = Math.min(offset + fibMM2, n - 1);17 18 if (arr[i] < x) {19 fibM = fibMM1;20 fibMM1 = fibMM2;21 fibMM2 = fibM - fibMM1;22 offset = i;23 } else if (arr[i] > x) {24 fibM = fibMM2;25 fibMM1 = fibMM1 - fibMM2;26 fibMM2 = fibM - fibMM1;27 } else return i;28 }29 30 if (fibMM1 && arr[offset + 1] === x) return offset + 1;31 32 return -1;33}