rust (52) - the largest binary heap BinaryHeap

Binary heap (English: binary heap) is a special stack, binary heap is a complete binary tree or approximately complete binary tree. Binary heap stack satisfies characteristics: parent node key is always kept a fixed sequence a key relationship for any child nodes, each node in the subtree and the left and right sub-tree is a binary heap.

When the key of the parent node is always greater than or equal to any key in the child node is a "maximum heap." When the key of the parent node is always less than or equal to any key in the child node is a "minimum heap."

None
Some(90)
[90, 87, 61, 69, 31, 9, 23, 11]


------------------
(program exited with code: 0)

请按任意键继续. . .
use std::collections::BinaryHeap;
fn main() {
    let mut my_heap=BinaryHeap::new();
    println!("{:?}",my_heap.peek());
    let x=[11,31,9,87,90,61,23,69];
    for i in &x{
		my_heap.push(i);
	}
    println!("{:?}",my_heap.peek());
    println!("{:?}",my_heap);	
}

Binary heap is generally represented by an array. If the position of the root node is a child node of the array 1, the n-th positions, respectively 2n and 2n + 1. Thus, the first position of the sub-nodes 2 and 3, the second position of the sub-nodes 4 and 5. And so on. Such a storage array based easy to find the parent and child nodes.

If the index-based storage arrays 0, then the next child nodes labeled node i is 2i + 1 and 2i + 2; subscript parent node is ⌊floor ((i - 1) / 2) ⌋. Function floor (x) is the greatest integer function "rounded down", or "rounded down", i.e. taking not greater than x (the "rounding" different, rounded down according to the number is the most direct access to shaft close to the required value of the value of the left, that is not greater than the maximum value of the required value). For example floor (1.1), floor (1.9) returns 1.

Two stacks of FIG follows:


            1                                 11                          
         /      \                          /      \ 
       2         3                       9         10
    /    \     /   \                   /   \     /    \ 
   4      5   6     7                5      6   7      8
  / \    / \                        / \    / \
 8  9   10 11                      1   2  3   4 

The two heap stored in an array starts at 1 in:

Location: 1234567891011
Left: 1234567891011
Right: 1191056781234
With a large stack, which storage is inefficient. Because the node's children are likely in another memory page. B-heap memory is a more efficient way, each subtree into the same memory page.

If memory heap pointer list, the method requires access to a leaf node. Binary tree can "threading" (threading) mode to sequentially traverse these nodes.

Published 473 original articles · won praise 14 · views 60000 +

Guess you like

Origin blog.csdn.net/AI_LX/article/details/105082901