# C Program to Search Sorted Sequence using Divide and Conquer

This C program searches for an element in a sorted array with the aid of fibonacci numbers.

The Fibonacci search technique is a method of searching a sorted array using a divide and conquer algorithm that narrows down possible locations with the aid of Fibonacci numbers. Compared to binary search, Fibonacci search examines locations whose addresses have lower dispersion. Therefore, when the elements being searched have non-uniform access memory storage (i.e., the time needed to access a storage location varies depending on the location previously accessed), the Fibonacci search has an advantage over binary search in slightly reducing the average time needed to access a storage location. The typical example of non-uniform access storage is that of a magnetic tape, where the time to access a particular element is proportional to its distance from the element currently under the tape’s head. Note, however, that large arrays not fitting in cache or even in RAM can also be considered as non-uniform access examples. Fibonacci search has a complexity of O(log(x)).

Here is the source code of the C program to implement fibonacci search. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

1. `#include <stdio.h>`
2. `#include <string.h>`
3. ` `
4. `int fibsearch(int a[], int n, long x)`
5. `{ `
6. `    int inf = 0, pos, k;`
7. `    static int kk= -1, nn = -1;`
8. `    static int fib[]={0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 98,`
9. `    1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811,`
10. `    514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817,`
11. `    39088169, 63245986, 102334155, 165580141};`
12. `    if (nn != n)`
13. `    { `
14. `        k = 0;`
15. `        while (fib[k] < n)`
16. `            k++;`
17. `        kk = k;`
18. `        nn = n;`
19. `    }`
20. `    else`
21. `        k = kk;`
22. `    while (k > 0)`
23. `    {`
24. `        pos = inf + fib[--k];`
25. `        if ((pos >= n) || (x < a[pos]));`
26. `        else if (x > a[pos])`
27. `        {`
28. `            inf = pos + 1;`
29. `            k--;`
30. `        }`
31. `        else {`
32. `            return pos;`
33. `        }`
34. `    }`
35. `    return -1;`
36. `}`
37. `main()`
38. `{`
39. `    int arr[] = {2, 3 , 45, 56 ,67 ,78 , 89, 99, 100, 101};`
40. `    int num, pos;`
41. `    printf("\nEnter an element to search: ");`
42. `    scanf("%d", &num);`
43. `    pos = fibsearch(arr, 10, num);`
44. `    if ( pos >= 0)`
45. `        printf("\nElement is at index : %d", fibsearch(arr, 10, num));`
46. `    else`
47. `        printf("\nElement NOT found!! ");`
48. ` `
49. `}`

```\$ gcc fibsearch.c -o fibsearch
\$ ./fibsearch

Enter an element to search: 78
Element is at index: 5```

Sanfoundry Global Education & Learning Series – 1000 C Programs.