|
| 1 | +#Made by SHASHANK CHAKRAWARTY |
| 2 | +# Python3 program for Fibonacci search. |
| 3 | +''' |
| 4 | +Works for sorted arrays |
| 5 | +A Divide and Conquer Algorithm. |
| 6 | +Has Log n time complexity. |
| 7 | +
|
| 8 | +1)Fibonacci Search divides given array in unequal parts |
| 9 | +
|
| 10 | +''' |
| 11 | + |
| 12 | +#Given a sorted array arr[] of size n and an element x to be searched in it. Return index of x if it is present in array else return -1. |
| 13 | + |
| 14 | +def fibMonaccianSearch(arr, x, n): |
| 15 | + |
| 16 | + # Initialize fibonacci numbers |
| 17 | + |
| 18 | + var2 = 0 # (m-2)'th Fibonacci No. |
| 19 | + var1 = 1 # (m-1)'th Fibonacci No. |
| 20 | + res = var2 + var1 # m'th Fibonacci |
| 21 | + |
| 22 | + |
| 23 | + # fibM is going to store the smallest |
| 24 | + # Fibonacci Number greater than or equal to n |
| 25 | + |
| 26 | + while (res < n): |
| 27 | + var2 = var1 |
| 28 | + var1 = res |
| 29 | + res = var2 + var1 |
| 30 | + |
| 31 | + # Marks the eliminated range from front |
| 32 | + offset = -1; |
| 33 | + |
| 34 | + # while there are elements to be inspected. |
| 35 | + # Note that we compare arr[var2] with x. |
| 36 | + # When fibM becomes 1, var2 becomes 0 |
| 37 | + |
| 38 | + |
| 39 | + while (res > 1): |
| 40 | + |
| 41 | + # Check if var2 is a valid location |
| 42 | + i = min(offset+var2, n-1) |
| 43 | + |
| 44 | + # If x is greater than the value at |
| 45 | + # index var2, cut the subarray array |
| 46 | + # from offset to i |
| 47 | + if (arr[i] < x): |
| 48 | + res = var1 |
| 49 | + var1 = var2 |
| 50 | + var2 = res - var1 |
| 51 | + offset = i |
| 52 | + |
| 53 | + # If x is greater than the value at |
| 54 | + # index var2, cut the subarray |
| 55 | + # after i+1 |
| 56 | + elif (arr[i] > x): |
| 57 | + res = var2 |
| 58 | + var1 = var1 - var2 |
| 59 | + var2 = res - var1 |
| 60 | + |
| 61 | + # element found. return index |
| 62 | + else : |
| 63 | + return i |
| 64 | + |
| 65 | + # comparing the last element with x */ |
| 66 | + if(var1 and arr[offset+1] == x): |
| 67 | + return offset+1; |
| 68 | + |
| 69 | + # element not found. return -1 |
| 70 | + return -1 |
| 71 | + |
| 72 | +# Driver Code, you can change the values accordingly |
| 73 | +arr = [10, 22, 35, 40, 45, 50, |
| 74 | + 80, 82, 85, 90, 100] |
| 75 | +n = len(arr) |
| 76 | +x = 85 |
| 77 | +print("Found at index:", |
| 78 | + fibMonaccianSearch(arr, x, n)) |
| 79 | + |
0 commit comments