Saturday, January 2, 2016

Implement Heap

D-ary heap is usually implemented using array (let's suppose it is indexed starting at 0). Than for every node of the heap placed at index holds, that its parent is placed at index and its descendands are placed at indexes . It is also convenient, if the heap arity is a power of 2, because than we can easily replace multiplications used in the tree traversal by binary shifts.

005.publicclassDAryHeap<ENTITY extendsComparable> {

006.

007.privatefinalstaticintEXPAND_RATIO = 2; //how many times should be the underlying array expanded

008.privatefinalstaticdoubleCOLLAPSE_RATIO = 0.25;//how empty must the heap be, to be the underlying collapsed

009.privateObject[] array;

010.privateintd; //parameter d

011.privateintsize; //size of the heap

012.privateintinitialSize;

013.

014./**

015.* Constructor

016.* @param arraySize initial capacity of the heap

017.*/

018.publicDAryHeap(intinitialSize, intd) {

019.if(d < 2) {

020.thrownewIllegalArgumentException("D must be at least 2.");

021.}

022.this.d = d;

023.this.array = newObject[initialSize];

024.this.initialSize = initialSize;

025.this.size = 0;

026.}

027.

028./**

029.* Insert element into the heap

030.* Complexity: O(log(n))

031.* @param i element to be inserted

032.*/

033.publicvoidinsert(ENTITY i) {

034.if(array.length == size) {

035.expand();

036.}

037.size++;

038.intindex = size - 1;

039.intparentIndex = getParentIndex(index);

040.while(index != 0&& i.compareTo(array[parentIndex]) < 0) {//while the element is less then its parent