Heap indices and order
In a zero-indexed max heap the parent value is at least each child value. Equal keys are permitted.
| Parent of i > 0 | (i − 1) div 2 | Integer division |
| Children of i | 2i + 1 and 2i + 2 | Check against array length |
| Peak priority | O(1) | Read the root |
| Insert or extract | O(log n) | Repair one path |
Python
def is_max_heap(a):
return all(a[(i-1)//2] >= a[i] for i in range(1, len(a)))C++
bool isMaxHeap(const std::vector<int>& a) {
for (size_t i = 1; i < a.size(); ++i)
if (a[(i-1)/2] < a[i]) return false;
return true;
}Java
static boolean isMaxHeap(int[] a) {
for (int i = 1; i < a.length; i++)
if (a[(i-1)/2] < a[i]) return false;
return true;
}