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[1];
  30. }
  31. int main()
  32. {
  33.     int n, i, x, max;
  34.     int a[20];
  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.

advertisement
advertisement

Here’s the list of Best Books in C Programming, Data Structures and Algorithms.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.