Data structure - heap (Heap) large root heap, small root heap

  • Heap is a data structure with the following characteristics:
    1) Complete binary tree ;
    2) The values ​​stored in the heap are in partial order ;

  • Min-heap : the value of the parent node is less than or equal to the value of the child node; Max-heap : the value of the parent node is greater than or equal to the value of the child node;

     
     

     


    1. Heap storage:
      Generally, arrays are used to represent heaps, and the subscript of the parent node of the i node is (i–1)/2. Its left and right child nodes have subscripts 2 * i + 1 and 2 * i + 2, respectively. For example, the subscripts of the left and right child nodes of the 0th node are 1 and 2 respectively.

       
       
    2. The operation of the heap: insert
      inserts an element: the new element is added to the end of the heap, and then the tree is updated to restore the order of the heap.
      Each insert puts new data at the end of the array. It can be found that from the parent node of the new data to the root node must be an ordered sequence, and now the task is to insert the new data into the ordered data - this is similar to inserting a data into the sorted data incorporated into the ordered interval.

       
       

       

    3. Operation of the heap: Removemax
      by definition removes the 0th data from the heap every time. In order to facilitate the reconstruction of the heap, the actual operation is to assign the value of the last data to the root node, and then perform a top-down adjustment from the root node. When adjusting, first find the largest among the left and right child nodes. If the parent node is larger than the smallest child node, it means that no adjustment is required. Otherwise, exchange the parent node with it and then consider the following nodes. It is equivalent to the "sinking" process of a data from the root node.

       
       

       

    4. Heap operation: buildHeap heap array
      For leaf nodes, there is no need to adjust the order. According to the nature of the full binary tree, the number of leaf nodes is 1 more than the number of internal nodes. So i=n/2 -1, do not start from n.

       
       

       

    5. 堆排序
      堆建好之后堆中第0个数据是堆中最大的数据。取出这个数据再执行下堆的删除操作。这样堆中第0个数据又是堆中最大的数据,重复上述步骤直至堆中只有一个数据时就直接取出这个数据。

Guess you like

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