Back to Home

Fibonacci Search

A comparison-based search technique that uses Fibonacci numbers to divide the array into unequal parts. It's similar to binary search but divides the array using Fibonacci numbers instead of dividing it in half.

Visualization

Step 1 / 4
Speed:

Details

Analogy

Imagine searching for a book on a shelf, but instead of dividing the shelf in half each time (binary search), you divide it according to the golden ratio (approximately 0.618). This is what Fibonacci search does - it uses Fibonacci numbers, which approximate the golden ratio, to determine where to look next.

Purpose

To search sorted arrays efficiently using Fibonacci numbers for division. It's particularly useful when the cost of division operations is high, as it only uses addition and subtraction. The algorithm is based on the divide and conquer approach.

Use Cases

Useful on systems where division or multiplication operations are expensive (embedded systems, older processors). Good for large datasets stored on slow memory (tapes, disks) where sequential access is preferred. Used in financial algorithms that naturally involve Fibonacci sequences. Beneficial when you want to minimize the number of comparisons.

Algorithm Steps

Line 1
1
fib2 = 0, fib1 = 1, fib = 1
2
while fib < n:
3
fib2 = fib1; fib1 = fib; fib = fib1 + fib2
4
offset = -1
5
while fib > 1:
6
i = min(offset + fib2, n-1)
7
if arr[i] < target: offset = i; fib = fib1; fib1 = fib2; fib2 = fib - fib1
8
elif arr[i] > target: fib = fib2; fib1 = fib1 - fib2; fib2 = fib - fib1
9
else: return i
10
if fib1 and arr[offset+1] == target: return offset+1
11
return -1
Current
Executed
Pending

Explanation

What's Happening?

Step 1/4

Initial sorted array: [10, 22, 35, 40, 45, 50, 80, 82, 85, 90, 100]. Starting Fibonacci search with search range [0, 10].

Updates with each step • Clickfor full view

Code Implementation

def fibonacci_search(arr, target):
    n = len(arr)
    fib2, fib1 = 0, 1
    fib = fib2 + fib1

    while fib < n:
        fib2 = fib1
        fib1 = fib
        fib = fib2 + fib1

    offset = -1

    while fib > 1:
        i = min(offset + fib2, n - 1)

        if arr[i] < target:
            fib = fib1
            fib1 = fib2
            fib2 = fib - fib1
            offset = i
        elif arr[i] > target:
            fib = fib2
            fib1 = fib1 - fib2
            fib2 = fib - fib1
        else:
            return i

    if fib1 and offset + 1 < n and arr[offset + 1] == target:
        return offset + 1

    return -1
Fibonacci Search - Interactive Visualization | AlgoViz | AlgoViz