Basic Storage of Heaps
I. Concept and Introduction
A heap (Heap) is a general term for a special class of data structures in computer science.
A heap is usually an array object that can be viewed as a complete binary tree.
A heap satisfies the following properties:
- The value of any node in a heap is always not greater than or not less than the value of its parent.
- A heap is always a complete binary tree.
II. Applicability Notes
A heap uses the structure of a complete binary tree to maintain a set of data and then perform related operations. The time complexity of a single general operation is between O(1) and O(logn). Heaps are often used to dynamically allocate and free objects used by programs.
For use cases involving priority queues, ordinary arrays or sequential arrays have a worst-case of O(n^2); the heap data structure can also improve the efficiency of enqueue and dequeue.
| enqueue | Dequeue | |
|---|---|---|
| Ordinary Array | O(1) | O(n) |
| Sorted Array | O(n) | O(1) |
| Heap | O(logn) | O(log) |
III. Structural diagram
A binary heap is a complete binary tree, and the value of any node in the heap is always not greater than that of its parent. The depth of this complete binary tree is k; except for level k, all other levels (1~k-1) have the maximum number of nodes, and all nodes at level k are continuously concentrated on the leftmost side.
When the root node of the heap is the largest, it is called a maximum heap, as shown below:

We can use an array to store a binary heap; the labels on the right are the array indices.


Assuming the index position of the current element is i, we can derive the rules:
parent(i) = i/2(取整)
left child(i) = 2*i
right child(i) = 2*i +1
IV. Java Example Code
Source code package download:Download
src/runoob/heap/MaxHeap.java file code:
package
runoob.heap
;
/**
* Heap definition
*/
public
class
MaxHeap
<
T
{
private
T
[
]
data;
private
int
count
;
// Constructor, construct an empty heap that can hold capacity elements
public
MaxHeap
(
int
capacity
)
{
data
=
(
T
[
]
)
new
Object
[
capacity
1
]
;
count
=
0
;
}
// Return the number of elements in the heap
public
int
size
(
)
{
return
count
;
}
// Return a boolean value indicating whether the heap is empty
public
boolean
isEmpty
(
)
{
return
count
==
0
;
}
// Test MaxHeap
public
static
void
main
(
String
[
]
args
)
{
MaxHeap
<
Integer
maxHeap
=
new
MaxHeap
<
Integer
(
100
);
System
.
out
.
println
(
maxHeap.
size
(
)
)
;
}
}