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
Here’s the list of Best Books in C Programming, Data Structures and Algorithms.
Related Posts:
- Practice Computer Science MCQs
- Practice BCA MCQs
- Check C Books
- Watch Advanced C Programming Videos
- Apply for Computer Science Internship