Basic storage for the heap

1. Concept and introduction

Heap is a general term for a special class of data structures in computer science.

The heap is usually an array of objects that can be viewed as a complete binary tree.

A heap satisfies the following properties:

  • The value of a node in the heap is always not greater than or not less than the value of its parent node.
  • The heap is always a complete binary tree.

2. Applicable instructions

The heap uses a complete binary tree structure to maintain a set of data, and then performs related operations. The time complexity of a general operation is between O(1)~O(logn). The heap is usually used for dynamic allocation and release programs. The object used.

If it is a priority queue usage scenario, ordinary arrays or sequential arrays, the worst case is O(n^2), and the heap data structure can also improve the efficiency of entering and exiting the queue.

enqueue dequeue
normal array O(1) O(n)
sequential array O(n) O(1)
heap O(logn) O(log)

3. Structural diagram

A binary heap is a complete binary tree, and the value of a node in the heap is always not greater than the value of its parent node. The depth of the complete binary tree is k. Except for the kth layer, other layers (1~k-1 ) reaches the maximum number of nodes, and all the nodes of the kth layer are continuously concentrated on the far left.

The maximum root node of the heap is called the maximum heap, as shown in the following figure:

We can use an array to store a binary heap, and the label on the right is the index of the array.

Assuming that the index position of the current element is i, the rule can be obtained:

parent(i) = i/2 (rounded)
left child(i) = 2*i
right child(i) = 2*i +1

4. Java example code

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, which can accommodate capacity elements     public MaxHeap(int capacity ){         data = (T[])new Object[capacity+1];         count = 0;     }     // returns the number of elements in the heap     public int size(){         return count;     }     // returns a Boolean value, representing the heap     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());
    }
}

Guess you like

Origin blog.csdn.net/unbelievevc/article/details/131256618