|
| 1 | +// C program for Fibonacci Search |
| 2 | +#include <stdio.h> |
| 3 | + |
| 4 | +// Utility function to find minimum of two elements |
| 5 | +int min(int x, int y) { return (x<=y)? x : y; } |
| 6 | + |
| 7 | +/* Returns index of x if present, else returns -1 */ |
| 8 | +int fibMonaccianSearch(int arr[], int x, int n) |
| 9 | +{ |
| 10 | + /* Initialize fibonacci numbers */ |
| 11 | + int fibMMm2 = 0; // (m-2)'th Fibonacci No. |
| 12 | + int fibMMm1 = 1; // (m-1)'th Fibonacci No. |
| 13 | + int fibM = fibMMm2 + fibMMm1; // m'th Fibonacci |
| 14 | + |
| 15 | + /* fibM is going to store the smallest Fibonacci |
| 16 | + Number greater than or equal to n */ |
| 17 | + while (fibM < n) |
| 18 | + { |
| 19 | + fibMMm2 = fibMMm1; |
| 20 | + fibMMm1 = fibM; |
| 21 | + fibM = fibMMm2 + fibMMm1; |
| 22 | + } |
| 23 | + |
| 24 | + // Marks the eliminated range from front |
| 25 | + int offset = -1; |
| 26 | + |
| 27 | + /* while there are elements to be inspected. Note that |
| 28 | + we compare arr[fibMm2] with x. When fibM becomes 1, |
| 29 | + fibMm2 becomes 0 */ |
| 30 | + while (fibM > 1) |
| 31 | + { |
| 32 | + // Check if fibMm2 is a valid location |
| 33 | + int i = min(offset+fibMMm2, n-1); |
| 34 | + |
| 35 | + /* If x is greater than the value at index fibMm2, |
| 36 | + cut the subarray array from offset to i */ |
| 37 | + if (arr[i] < x) |
| 38 | + { |
| 39 | + fibM = fibMMm1; |
| 40 | + fibMMm1 = fibMMm2; |
| 41 | + fibMMm2 = fibM - fibMMm1; |
| 42 | + offset = i; |
| 43 | + } |
| 44 | + |
| 45 | + /* If x is greater than the value at index fibMm2, |
| 46 | + cut the subarray after i+1 */ |
| 47 | + else if (arr[i] > x) |
| 48 | + { |
| 49 | + fibM = fibMMm2; |
| 50 | + fibMMm1 = fibMMm1 - fibMMm2; |
| 51 | + fibMMm2 = fibM - fibMMm1; |
| 52 | + } |
| 53 | + |
| 54 | + /* element found. return index */ |
| 55 | + else return i; |
| 56 | + } |
| 57 | + |
| 58 | + /* comparing the last element with x */ |
| 59 | + if(fibMMm1 && arr[offset+1]==x)return offset+1; |
| 60 | + |
| 61 | + /*element not found. return -1 */ |
| 62 | + return -1; |
| 63 | +} |
| 64 | + |
| 65 | +/* driver function */ |
| 66 | +int main(void) |
| 67 | +{ |
| 68 | + int arr[] = {10, 22, 35, 40, 45, 50, 80, 82, |
| 69 | + 85, 90, 100}; |
| 70 | + int n = sizeof(arr)/sizeof(arr[0]); |
| 71 | + int x = 85; |
| 72 | + printf("Found at index: %d", |
| 73 | + fibMonaccianSearch(arr, x, n)); |
| 74 | + return 0; |
| 75 | +} |
0 commit comments