This is a C program to implement the binary heap. It constructs a maximum binary heap of given array elements. Maximum binary heap is one in which the every child node has value less than the value of the parent.

Here is the source code of the C Program. The C program is successfully compiled and run on a Windows system. The program output is also shown below.

`/* C program to build a binary heap */`

`#include <stdio.h>`

`#include <stdlib.h>`

`#define MAX 20`

void maxheapify(int *, int, int);

int* buildmaxheap(int *, int);

void main()

`{`

int i, t, n;

int *a = calloc(MAX, sizeof(int));

int *m = calloc(MAX, sizeof(int));

printf("Enter no of elements in the array\n");

scanf("%d", &n);

printf("Enter the array\n");

for (i = 0; i < n; i++) {

scanf("%d", &a[i]);

`}`

m = buildmaxheap(a, n);

printf("The heap is\n");

for (t = 0; t < n; t++) {

printf("%d\n", m[t]);

`}`

`}`

int* buildmaxheap(int a[], int n)

`{`

int heapsize = n;

int j;

for (j = n/2; j >= 0; j--) {

maxheapify(a, j, heapsize);

`}`

return a;

`}`

void maxheapify(int a[], int i, int heapsize)

`{`

int temp, largest, left, right, k;

left = (2*i+1);

right = ((2*i)+2);

if (left >= heapsize)

return;

else {

if (left < (heapsize) && a[left] > a[i])

largest = left;

`else`

largest = i;

if (right < (heapsize) && a[right] > a[largest])

largest = right;

if (largest != i) {

temp = a[i];

a[i] = a[largest];

a[largest] = temp;

maxheapify(a, largest, heapsize);

`}`

`}`

`}`

Output

Enter no of elements in the array 5 Enter the array 7 5 9 3 2 The heap is : 9 5 7 3 2

**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 Data Structure I
- Participate in Data Structure I Certification Contest
- Become a Top Ranker in Data Structure I
- Take Data Structure I 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:**

- Practice Computer Science MCQs
- Practice Design & Analysis of Algorithms MCQ
- Practice Programming MCQs
- Buy Computer Science Books
- Buy Programming Books