Implementation of max and min heap

  • Max-Min Heap
    A heap is a sorted complete binary tree in which the data value of any non-terminal node is not greater (or less than) the value of its left and right children.
    Max heap and min heap are two forms of binary heap.
    Max heap: The key value of the root node is the largest of all heap node key values.
    Min heap: The key value of the root node is the smallest of all heap node key values.

  • Minimum heap example

  • Establish the minimum heap
    The initial array is: 9,3,7,6,5,1,10,2
    According to the complete binary tree, fill in the numbers in turn.
    After filling in, find the last node and
    start adjusting from its parent node (the node with number 6 in this example). According to the nature, the small number moves up; at this point, the first adjustment is completed.
    Note that the adjusted nodes, as well as the child nodes, need to be adjusted recursively.
    The second adjustment is the node whose subscript of the node array of number 6 is smaller by 1 (the node whose subscript is 1 smaller than the subscript of number 6 is the node of number 7),
    which is adjusted with the previous rules. And so on until adjusted to the root node.

  • Replace the node
    Remove the top of the heap and put the newly added 23 on the top of the heap.
    Obviously, after adding the number, it does not meet the characteristics of the minimum heap, and we need to adjust the newly added number to the appropriate position.

    Adjust down, compare this number with its two sons 2 and 5, and choose the smaller one to exchange with it.

    At this time, we find that the minimum heap is still not satisfied, so we continue to compare 23 with the smaller of its two sons. an exchange.

    exchange again

  • Adding a new node
    If you just want to add a new number instead of deleting the minimum value, you only need to insert the new element at the end, and then judge whether the new element needs to be moved up according to the situation until the new characteristic position is satisfied.
    Join We are now going to add a 3.

    First compare 3 with its parent node 25 and find that it is smaller than the parent node and needs to be exchanged with the parent node. and so on

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325119334&siteId=291194637