1. Heap: Usually through a binary heap, a real two-fork tree, divided into the smallest heap and the largest heap, with the following properties:
- Any node is smaller than all descendants of it, and the minimum element is on the root of the heap.
- The heap is always a tree full of trees
The largest heap of the root node is called the maximum heap or large heap, and the smallest heap of the root node is called the minimum heap or small Gan.
2. Minimum heap implementation:
Insert:
1) Place the newly inserted element at the tail of the queue.
2) If the element is smaller than its parent node, two elements are interchanged. (Move up operation)
3) iterate until the element has no parent node or is less than its parent node.
Delete:
1) Remove the top node.
2) Place the elements at the end of the team at the top.
3) the node is compared to the smaller of its child nodes, and if it is less than that, the swap position, (move Down)
4) iterate until the leaf node is no longer larger than the smaller one in its child nodes.
Java code:
1 Packageminheap;2 3 Public classMinheap {4 Private int[] data;5 6 PublicMinheap (int[] data) {7 This. data =data;8 }9 Ten Public voidcreateheap () { One for(inti = (data.length)/2-1; I >= 0; i--) { A heapify (i); - } - } the - Public voidHeapify (intvalue) { - intLchild =Left (value); - intRchild =Right (value); + intsmallest =value; - if(Lchild < data.length && Data[lchild] <Data[value]) +smallest =Lchild; A if(Rchild < data.length && Data[rchild] <Data[smallest]) atsmallest =Rchild; - if(Value = =smallest) - return; - Swap (value, smallest); - heapify (smallest); - } in - Public intLeftintvalue) { to return((value + 1) << 1)-1; + } - the Public intRightintvalue) { * return(value + 1) << 1; $ }Panax Notoginseng - Public voidSwapintIintj) { the intTMP =Data[i]; +Data[i] =Data[j]; ADATA[J] =tmp; the } + - Public voidSetroot (intvalue) { $Data[0] =value; $Heapify (0); - } - the Public Static voidMain (string[] args) { - int[] value = {10, 100, 12, 73, 45, 32, 11, 23, 55, 34, 90, 21 };WuyiMinheap heap =Newminheap (value); the heap.createheap (); - for(inti = 0; i < value.length; i++) { WuSystem.out.print (Heap.data[i] + ""); - } About System.out.println (); $Heap.setroot (64); - for(inti = 0; i < value.length; i++) { -System.out.print (Heap.data[i] + ""); - } A System.out.println (); + } the}
Java implements minimal heap