File tree Expand file tree Collapse file tree 1 file changed +63
-0
lines changed
data-structures/Priority_Queues Expand file tree Collapse file tree 1 file changed +63
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+
3
+ Problem:
4
+ Given an array of integers, check whether it represents max-heap or not.
5
+ Return true or false.
6
+
7
+
8
+ */
9
+
10
+
11
+ #include < bits/stdc++.h>
12
+ using namespace std ;
13
+
14
+ bool checkMaxHeap (int arr[], int n){
15
+
16
+ int loopSize = ((n-1 )-1 )/2 ;
17
+ int j = 0 ;
18
+ while (j <= loopSize) {
19
+ int parent = j;
20
+ int left = (2 *parent)+1 ;
21
+ int right = (2 *parent)+2 ;
22
+
23
+ bool ok = false ;
24
+ if (left < n) {
25
+ if (arr[left] <= arr[parent])
26
+ ok = true ;
27
+ else {
28
+ return false ;
29
+ }
30
+ }
31
+
32
+ if (right < n) {
33
+ if (arr[right] <= arr[parent])
34
+ ok = true ;
35
+ else {
36
+ return false ;
37
+ }
38
+ }
39
+ j++;
40
+ }
41
+ return true ;
42
+ }
43
+
44
+ int main () {
45
+ int n;
46
+ cin>>n;
47
+ int *arr = new int [n];
48
+ for (int i=0 ; i<n; i++){
49
+ cin >> arr[i];
50
+ }
51
+ bool ans = checkMaxHeap (arr, n);
52
+ if (ans){
53
+ cout << " true" << endl;
54
+ }
55
+ else {
56
+ cout << " false" << endl;
57
+ }
58
+
59
+ delete [] arr;
60
+ }
61
+
62
+
63
+
You can’t perform that action at this time.
0 commit comments