Implementation characteristics of binary stack
- Structural:
The heap is a fully binary tree: a completely filled tree with elements from left to right filled in from the lower level
- Sequence of the heap
The minimum of the minimum heap is on the root, and each child heap also satisfies the parent node is not greater than the child node
Basic heap Operations
- Insert (insertion)
- Add a hole in the next available location
- Compares the hole with its parent element, if
A. Hole < parent element, swap both positions, continue 2 operation
B. Hole >= parent element, stop, assign hole to insert element
The above operation is called Upper filter (percolate up)
- Deletemin (delete minimum Element)
- Creating a hole in the root node
- The hole is compared with its sub-elements, if
A. Hole <= Sub-element, stop, assign hole to end element
B. Holes > Sub elements, swap both positions, continue 2 operation
It should be noted that when selecting child elements, it is necessary to determine whether there are left and right nodes, and select the smaller of the two child nodes. The above operation is called the filter
- Buildheap (Build heap)
- Create a new array
- Copy element
- For each element of CURRENTSIZE/2 ~ 1, filter down
- Complete Heap Build
Attached code (main function implemented):
Package Datastructures;import java.util.ArrayList;/ * * The Min Heap is built in an array. * Elements is stored from 1 to currentsize. */ Public classBinaryheap<e extends Comparable<? Super E>> { Public Binaryheap() { This(default_capacity); } Public Binaryheap(intcapacity) {CurrentSize =0; Array = (e[])NewComparable[capacity]; } Public Binaryheap(e[] items) {currentsize = Items.length; Array = (e[])Newcomparable[(CurrentSize +2) * One/Ten];inti =1; for(E item:items) array[i++] = Item; Buildheap (); } Public void Insert(E x) {if(CurrentSize = = Array.Length-1) Enlargearray (Array.Length *2+1);intHole = ++currentsize; for(; hole >0&& Array[hole].compareto (Array[hole/2]) <0; Hole/=2) Array[hole] = array[hole/2]; Array[hole] = x; } PublicEFindmin() {returnarray[1]; } PublicEDeletemin() {if(IsEmpty ()) {} E Minitem = Findmin (); array[1] = array[currentsize--]; Percolatedown (1);returnMinitem; } PublicBooleanIsEmpty() {returncurrentsize==0?true:false; } Public void Makeempty() { }Private StaticFinalintDefault_capacity =Ten;Private intCurrentSize;PrivateE[] Array;Private void Percolatedown(intHole) {intChild E tmp = Array[hole]; for(; Hole *2<= currentsize; Hole = child) {Child = hole *2;if(Child! = currentsize && Array[child].compareto (Array[child +1]) >0) {child++; }if(Array[hole].compareto (Array[child]) >0) {Array[hole] = Array[child]; }Else{ Break; } } }Private void Buildheap() { for(inti = currentsize/2; i >0; i--) {Percolatedown (i); } }Private void Enlargearray(intnewSize) {arraylist<e> NewArray =NewArraylist<e> (newSize); for(inti =0; i < currentsize; i++) Newarray.add (Array[i]); Array = (e[]) Newarray.toarray (); }}
"JAVA" Heap implementation