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.
#include <stdio.h>
void max_heapify(int *a, int i, int n)
{
int j, temp;
temp = a[i];
j = 2 * i;
while (j <= n)
{
if (j < n && a[j+1] > a[j])
j = j + 1;
if (temp > a[j])
break;
else if (temp <= a[j])
{
a[j / 2] = a[j];
j = 2 * j;
}
}
a[j/2] = temp;
return;
}
int binarysearchmax(int *a,int n)
{
int i;
for(i = n/2; i >= 1; i--)
{
max_heapify(a,i,n);
}
return a[1];
}
int main()
{
int n, i, x, max;
int a[20];
printf("Enter no of elements of array\n");
scanf("%d", &n);
printf("\nEnter %d elements: ", n);
for (i = 1; i <= n; i++)
{
scanf("%d", &a[i]);
}
max = binarysearchmax(a, n);
printf("\nMaximum element is : %d", max);
return 0;
}
$ 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.
Next Steps:
- Get Free Certificate of Merit in C Programming
- Participate in C Programming Certification Contest
- Become a Top Ranker in C Programming
- Take C Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Related Posts:
- Watch Advanced C Programming Videos
- Practice BCA MCQs
- Practice Computer Science MCQs
- Apply for C Internship
- Buy C Books