# C Program to Find Maximum Element in an Array using Binary Search

«
»
This C program finds maximum element in an array using Binary Search. In binary search we prune half the search state space by selecting either one of the partition. The primary condition is that the sequence should be sorted.

Here is the source code of the C program to search an integer array using binary search to find the largest element in O(n) time. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

1. `#include <stdio.h>`
2. `void max_heapify(int *a, int i, int n)`
3. `{`
4. `    int j, temp;`
5. `    temp = a[i];`
6. `    j = 2 * i;`
7. `    while (j <= n)`
8. `    {`
9. `        if (j < n && a[j+1] > a[j])`
10. `            j = j + 1;`
11. `        if (temp > a[j])`
12. `            break;`
13. `        else if (temp <= a[j])`
14. `        {`
15. `            a[j / 2] = a[j];`
16. `            j = 2 * j;`
17. `        }`
18. `    }`
19. `    a[j/2] = temp;`
20. `    return;`
21. `}`
22. `int binarysearchmax(int *a,int n)`
23. `{`
24. `    int i;`
25. `    for(i = n/2; i >= 1; i--)`
26. `    {`
27. `        max_heapify(a,i,n);`
28. `    }`
29. `    return a;`
30. `}`
31. `int main()`
32. `{`
33. `    int n, i, x, max;`
34. `    int a;`
35. `    printf("Enter no of elements of array\n");`
36. `    scanf("%d", &n);`
37. `    printf("\nEnter %d elements: ", n);`
38. `    for (i = 1; i <= n; i++)`
39. `    {`
40. `       scanf("%d", &a[i]);`
41. `    }`
42. `    max = binarysearchmax(a, n);`
43. `    printf("\nMaximum element is : %d", max);`
44. `    return 0;`
45. `}`

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

Enter the size of array: 5
Enter 5 elements: 87 83 99 23 3

Maximum element is : 99```

Sanfoundry Global Education & Learning Series – 1000 C Programs. 