Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit fc1db23

Browse files
committed
check given array is heap or not
1 parent 1d8ea5b commit fc1db23

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

‎Data-Structure/Tree/Heap/checkHeap.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
'use strict';
2+
function checkHeap(arr, root, n) {
3+
if (root > (parseInt((n - 2) / 2))) return true;
4+
let left = (root * 2) + 1;
5+
let right = (root * 2) + 2;
6+
if (arr[left] < arr[root] && arr[right] < arr[root])
7+
return checkHeap(arr, left, n) && checkHeap(arr, right, n);
8+
9+
let result = false;
10+
if ((left < n && arr[left] > arr[root])) result = false;
11+
else if (left < n && arr[left] < arr[root]) result = true;
12+
13+
if (right < n && arr[right] > arr[root]) result = result & false;
14+
else if (right < n && arr[right] < arr[root]) result = result & false;
15+
16+
return result;
17+
}
18+
let array = [90, 15, 10, 7, 12, 2, 9, 1, 6];
19+
console.log('Given Array is', checkHeap(array, 0, array.length) == true ? 'Heap' : 'not Heap');

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /