Skip to content

Commit f8603bf

Browse files
authored
Merge pull request #257 from aakankshabhende/determine-if-max-heap
Determine if given array is a max-heap
2 parents 88c6a21 + 83a78f3 commit f8603bf

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// C++ program to check whether a given array represents a max-heap or not
2+
#include <limits.h>
3+
#include <stdio.h>
4+
#include <iostream>
5+
using namespace std;
6+
bool isHeap(int arr[], int n)
7+
{
8+
// Start from root
9+
for (int i = 0; i <= (n - 2) / 2; i++)
10+
{
11+
// If left child is greater, return false
12+
if (arr[2 * i + 1] > arr[i])
13+
return false;
14+
15+
// If right child is greater, return false
16+
if (2 * i + 2 < n && arr[2 * i + 2] > arr[i])
17+
return false;
18+
}
19+
return true;
20+
}
21+
// Driver program
22+
int main()
23+
{
24+
int n;
25+
cout << "Enter the number of array elements-";
26+
cin >> n;
27+
int arr[n];
28+
cout << "Enter the array elements-";
29+
for (int i = 0; i < n; i++)
30+
{
31+
cin >> arr[i];
32+
}
33+
isHeap(arr, n) ? printf("Yes, it represents a max-heap.") : printf("No");
34+
35+
return 0;
36+
}

0 commit comments

Comments
 (0)