|
| 1 | +# Fibonacci searching algorithm only works on the sorted array with time complexity O(log(n)). |
| 2 | + |
| 3 | +# Function to find minimum out of two element |
| 4 | +def min(x, y): |
| 5 | + return x if x <= y else y |
| 6 | + |
| 7 | +# Returns the index of x if present, else returns -1 |
| 8 | +def fibonacciSearch(array, target, n): |
| 9 | + # If target is greater than last element of the array or smaller than first element of the array |
| 10 | + if target > array[n-1] or target < array[0]: |
| 11 | + return -1 |
| 12 | + |
| 13 | + # Initialize Fibonacci numbers |
| 14 | + fiboMMm2 = 0 # (m-2)'th Fibonacci No. |
| 15 | + fiboMMm1 = 1 # (m-1)'th Fibonacci No. |
| 16 | + fiboM = fiboMMm2 + fiboMMm1 # m'th Fibonacci |
| 17 | + |
| 18 | + # fiboM is going to store the smallest Fibonacci Number greater than or equal to n |
| 19 | + while fiboM < n: |
| 20 | + fiboMMm2, fiboMMm1 = fiboMMm1, fiboM |
| 21 | + fiboM = fiboMMm2 + fiboMMm1 |
| 22 | + |
| 23 | + # Marks the eliminated range from the front |
| 24 | + offset = -1 |
| 25 | + |
| 26 | + # While there are elements to be inspected. |
| 27 | + # Note that we compare array[fiboMm2] with target. |
| 28 | + # When fiboM becomes 1, fiboMm2 becomes 0 |
| 29 | + while fiboM > 1: |
| 30 | + # Check if fiboMm2 is a valid location |
| 31 | + i = min(offset + fiboMMm2, n - 1) |
| 32 | + |
| 33 | + # If target is greater than the value at index fiboMm2, cut the subarray array from offset to i |
| 34 | + if array[i] < target: |
| 35 | + fiboM, fiboMMm1, fiboMMm2 = fiboMMm1, fiboMMm2, fiboM - fiboMMm1 |
| 36 | + offset = i |
| 37 | + |
| 38 | + # If target is greater than the value at index fiboMm2, cut the subarray after i+1 |
| 39 | + elif array[i] > target: |
| 40 | + fiboM, fiboMMm1, fiboMMm2 = fiboMMm2, fiboMMm1 - fiboMMm2, fiboM - fiboMMm1 |
| 41 | + |
| 42 | + # Element found, return index |
| 43 | + else: |
| 44 | + return i |
| 45 | + |
| 46 | + # Comparing the last element with target |
| 47 | + if fiboMMm1 and array[offset + 1] == target: |
| 48 | + return offset + 1 |
| 49 | + |
| 50 | + # Element not found, return -1 |
| 51 | + return -1 |
| 52 | + |
| 53 | +if __name__ == "__main__": |
| 54 | + n = int(input("\nEnter number of elements in the array: ")) |
| 55 | + array = [] |
| 56 | + print('\n') |
| 57 | + for i in range(n): |
| 58 | + array.append(int(input(f"Enter element {i+1}: "))) |
| 59 | + array.sort() |
| 60 | + target = int(input("\nEnter target element: ")) |
| 61 | + |
| 62 | + index = fibonacciSearch(array, target, n) |
| 63 | + |
| 64 | + print('\nEntered elements are: ', end='') |
| 65 | + for i in range(n): |
| 66 | + print(array[i], end=' ') |
| 67 | + print('\n') |
| 68 | + |
| 69 | + if index != -1: |
| 70 | + print(f"\n{target} is present at index: {index}\n") |
| 71 | + else: |
| 72 | + print(f"\n{target} isn't present in the array.\n") |
0 commit comments