logo

Heap-implementering i Java

I Java er Heap en spesiell type datastruktur der rotnoden eller overordnet node sammenlignes med venstre og høyre barn og ordnes i henhold til rekkefølgen. Anta at x er en rotnode og y er undernoden, egenskapen nøkkel (x)<= key(y)< strong>vil generere min-heap, og den relasjonen blir referert til som 'haugeiendom' .

Basert på rekkefølgen til overordnede og underordnede noder, kan Heap klassifiseres i to former, dvs. Min heap og Max heap. La oss forstå begge en etter en og implementere koden i Java.

Min haug

Min heap er en spesiell type heap-datastruktur som er et komplett binært tre i seg selv. Min haug har følgende egenskaper:

  1. Verdien av rotnoden er alltid mindre sammenlignet med de andre nodene i haugen.
  2. Hver intern node har en nøkkelverdi som alltid er mindre eller lik dens underordnede node.

Vi kan utføre følgende tre operasjoner i Min haug:

insertNode()

Vi kan utføre innsetting i Min-haugen ved å legge til en ny nøkkel på slutten av treet. Hvis verdien av den innsatte nøkkelen er mindre enn dens overordnede node, må vi krysse nøkkelen oppover for å oppfylle heap-egenskapen. Innsettingsprosessen tar O(log n) tid.

extractMin()

Det er en av de viktigste operasjonene vi utfører for å fjerne minimumsverdinoden, dvs. rotnoden til haugen. Etter å ha fjernet rotnoden, må vi sørge for at heap-egenskapen skal opprettholdes. ExtractMin()-operasjonen tar O(Logn)-tid for å fjerne minimumselementet fra heapen.

getMin()

De getMin() operasjon brukes for å få rotnoden til haugen, dvs. minimumselement i O(1) tid.

Eksempel:

Heap-implementering i Java

Min haug-algoritme

 proceduredesign_min_heap Array arr: of size n =&gt; array of elements // call min_heapify procedure for each element of the array to form min heap repeat for (k = n/2 ; k &gt;= 1 ; k--) call procedure min_heapify (arr, k); proceduremin_heapify (vararr[ ] , var k, varn) { varleft_child = 2*k; varright_child = 2*k+1; var smallest; if(left_child<= n and arr[left_child ] <arr[ k ) smallest="left_child;" else if(right_child<="n" arr[right_child <arr[smallest] if(smallest !="k)" { swaparr[ arr[ ]); callmin_heapify (arr, smallest, n); } < pre> <p> <strong>MinHeapJavaImplementation.java</strong> </p> <pre> // import required classes and packages packagejavaTpoint.javacodes; importjava.util.Scanner; // create class MinHeap to construct Min heap in Java classMinHeap { // declare array and variables privateint[] heapData; privateintsizeOfHeap; privateintheapMaxSize; private static final int FRONT = 1; //use constructor to initialize heapData array publicMinHeap(intheapMaxSize) { this.heapMaxSize = heapMaxSize; this.sizeOfHeap = 0; heapData = new int[this.heapMaxSize + 1]; heapData[0] = Integer.MIN_VALUE; } // create getParentPos() method that returns parent position for the node privateintgetParentPosition(int position) { return position / 2; } // create getLeftChildPosition() method that returns the position of left child privateintgetLeftChildPosition(int position) { return (2 * position); } // create getRightChildPosition() method that returns the position of right child privateintgetRightChildPosition(int position) { return (2 * position) + 1; } // checks whether the given node is leaf or not privatebooleancheckLeaf(int position) { if (position &gt;= (sizeOfHeap / 2) &amp;&amp; position heapData[getLeftChildPosition(position)] || heapData[position] &gt;heapData[getRightChildPosition(position)]) { // swap with left child and then heapify the left child if (heapData[getLeftChildPosition(position)] = heapMaxSize) { return; } heapData[++sizeOfHeap] = data; int current = sizeOfHeap; while (heapData[current] <heapdata[getparentposition(current)]) { swap(current, getparentposition(current)); current="getParentPosition(current);" } crreatedisplayheap() method to print the data of heap public void displayheap() system.out.println('parent node' + '	' 'left child 'right node'); for (int k="1;" position--) minheapify(position); create removeroot() removing minimum element from publicintremoveroot() intpopelement="heapData[FRONT];" heapdata[front]="heapData[sizeOfHeap--];" minheapify(front); returnpopelement; minheapjavaimplementation class in java classminheapjavaimplementation{ main() start static main(string[] arg) declare variable intheapsize; scanner object sc="new" scanner(system.in); system.out.println('enter size min heap'); heapsize="sc.nextInt();" minheapheapobj="new" minheap(heapsize); for(inti="1;" i<="heapSize;" i++) system.out.print('enter '+i+' element: '); int heapobj.insertnode(data); close obj sc.close(); construct a given heapobj.designminheap(); display system.out.println('the is heapobj.displayheap(); root node system.out.println('after element(root node) '+heapobj.removeroot()+', is:'); < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/java-tutorial/97/heap-implementation-java-2.webp" alt="Heap implementation in Java"> <h2>Max heap</h2> <p>Max heap is another special type of heap data structure that is also a complete binary tree in itself in Java. Max heap has the following properties:</p> <ol class="points"> <li>Root node value is always greater in comparison to the other nodes of the heap.</li> <li>Each internal node has a key value that is always greater or equal to its children.</li> </ol> <p>We can perform the following three operations in Max heap:</p> <h3>insertNode()</h3> <p>We can perform insertion in the Max heap by adding a new key at the end of the tree. If the value of the inserted key is greater than its parent node, we have to traverse the key upwards for fulfilling the heap property. The insertion process takes O(log n) time.</p> <h3>extractMax()</h3> <p>It is one of the most important operations which we perform to remove the maximum value node, i.e., the root node of the heap. After removing the root node, we have to make sure that heap property should be maintained. The extractMax() operation takes O(Log n) time to remove the maximum element from the heap.</p> <h3>getMax()</h3> <p>The <strong>getMax()</strong> operation is used to get the root node of the heap, i.e., maximum element in O(1) time.</p> <p> <strong>Example:</strong> </p> <img src="//techcodeview.com/img/java-tutorial/97/heap-implementation-java-3.webp" alt="Heap implementation in Java"> <p> <strong>Min heap Algorithm</strong> </p> <pre> proceduredesign_max_heap Array arr: of size n =&gt; array of elements // call min_heapify procedure for each element of the array to form max heap repeat for (k = n/2 ; k &gt;= 1 ; k--) call procedure max_heapify (arr, k); proceduremin_heapify (vararr[ ] , var k, varn) { varleft_child = 2*k + 1; varright_child = 2*k+ 2; if(left_childarr[ largest ] ) largest = left_child; else largest = k; if(right_childarr[largest] ) largest = right_child; if(largest != k) { swaparr[ k ] and arr[ largest ]); callmax_heapify (arr, largest, n); } } </pre> <p> <strong>MaxHeapJavaImplementation.java</strong> </p> <pre> //import required classes and packages packagejavaTpoint.javacodes; importjava.util.Scanner; //create class MinHeap to construct Min heap in Java classMaxHeap { // declare array and variables privateint[] heapData; privateintsizeOfHeap; privateintheapMaxSize; private static final int FRONT = 1; //use constructor to initialize heapData array publicMaxHeap(intheapMaxSize) { this.heapMaxSize = heapMaxSize; this.sizeOfHeap = 0; heapData = new int[this.heapMaxSize]; } // create getParentPos() method that returns parent position for the node privateintgetParentPosition(int position) { return (position - 1) / 2; } // create getLeftChildPosition() method that returns the position of left child privateintgetLeftChildPosition(int position) { return (2 * position); } // create getRightChildPosition() method that returns the position of right child privateintgetRightChildPosition(int position) { return (2 * position) + 1; } // checks whether the given node is leaf or not privatebooleancheckLeaf(int position) { if (position &gt; (sizeOfHeap / 2) &amp;&amp; position <= sizeofheap) { return true; } false; create swapnodes() method that perform swapping of the given nodes heap firstnode and secondnode are positions private void swap(intfirstnode, intsecondnode) int temp; temp="heapData[firstNode];" heapdata[firstnode]="heapData[secondNode];" heapdata[secondnode]="temp;" maxheapify() to heapify node for maintaining property maxheapify(int position) check whether is non-leaf greater than its right left child if (!checkleaf(position)) (heapdata[position] <heapdata[getleftchildposition(position)] || heapdata[position] heapdata[getrightchildposition(position)]) swap(position, getleftchildposition(position)); maxheapify(getleftchildposition(position)); swap with else getrightchildposition(position)); maxheapify(getrightchildposition(position)); insertnode() insert element in public insertnode(int data) heapdata[sizeofheap]="data;" current="sizeOfHeap;" while (heapdata[current]>heapData[getParentPosition(current)]) { swap(current, getParentPosition(current)); current = getParentPosition(current); } sizeOfHeap++; } // create displayHeap() method to print the data of the heap public void displayHeap() { System.out.println(&apos;PARENT NODE&apos; + &apos;	&apos; + &apos;LEFT CHILD NODE&apos; + &apos;	&apos; + &apos;RIGHT CHILD NODE&apos;); for (int k = 0; k <sizeofheap 2; k++) { system.out.print(' ' + heapdata[k] '		' heapdata[2 * k 1] 2]); system.out.println(); } create designmaxheap() method to construct min heap public void for (int position="0;" < (sizeofheap 2); position++) maxheapify(position); removeroot() removing maximum element from the publicintremoveroot() intpopelement="heapData[FRONT];" heapdata[front]="heapData[sizeOfHeap--];" maxheapify(front); returnpopelement; minheapjavaimplementation class in java classmaxheapjavaimplementation{ main() start static main(string[] arg) declare variable intheapsize; scanner object sc="new" scanner(system.in); system.out.println('enter size of max heap'); heapsize="sc.nextInt();" maxheapheapobj="new" maxheap(50); for(inti="1;" i<="heapSize;" i++) system.out.print('enter '+i+' element: '); int data="sc.nextInt();" heapobj.insertnode(data); close obj sc.close(); a given heapobj.designmaxheap(); display system.out.println('the is heapobj.displayheap(); root node system.out.println('after element(root node) '+heapobj.removeroot()+', is:'); pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/java-tutorial/97/heap-implementation-java-4.webp" alt="Heap implementation in Java"> <hr></sizeofheap></=></pre></heapdata[getparentposition(current)])></pre></=>

MaxHeapJavaImplementation.java

 //import required classes and packages packagejavaTpoint.javacodes; importjava.util.Scanner; //create class MinHeap to construct Min heap in Java classMaxHeap { // declare array and variables privateint[] heapData; privateintsizeOfHeap; privateintheapMaxSize; private static final int FRONT = 1; //use constructor to initialize heapData array publicMaxHeap(intheapMaxSize) { this.heapMaxSize = heapMaxSize; this.sizeOfHeap = 0; heapData = new int[this.heapMaxSize]; } // create getParentPos() method that returns parent position for the node privateintgetParentPosition(int position) { return (position - 1) / 2; } // create getLeftChildPosition() method that returns the position of left child privateintgetLeftChildPosition(int position) { return (2 * position); } // create getRightChildPosition() method that returns the position of right child privateintgetRightChildPosition(int position) { return (2 * position) + 1; } // checks whether the given node is leaf or not privatebooleancheckLeaf(int position) { if (position &gt; (sizeOfHeap / 2) &amp;&amp; position <= sizeofheap) { return true; } false; create swapnodes() method that perform swapping of the given nodes heap firstnode and secondnode are positions private void swap(intfirstnode, intsecondnode) int temp; temp="heapData[firstNode];" heapdata[firstnode]="heapData[secondNode];" heapdata[secondnode]="temp;" maxheapify() to heapify node for maintaining property maxheapify(int position) check whether is non-leaf greater than its right left child if (!checkleaf(position)) (heapdata[position] <heapdata[getleftchildposition(position)] || heapdata[position] heapdata[getrightchildposition(position)]) swap(position, getleftchildposition(position)); maxheapify(getleftchildposition(position)); swap with else getrightchildposition(position)); maxheapify(getrightchildposition(position)); insertnode() insert element in public insertnode(int data) heapdata[sizeofheap]="data;" current="sizeOfHeap;" while (heapdata[current]>heapData[getParentPosition(current)]) { swap(current, getParentPosition(current)); current = getParentPosition(current); } sizeOfHeap++; } // create displayHeap() method to print the data of the heap public void displayHeap() { System.out.println(&apos;PARENT NODE&apos; + &apos;	&apos; + &apos;LEFT CHILD NODE&apos; + &apos;	&apos; + &apos;RIGHT CHILD NODE&apos;); for (int k = 0; k <sizeofheap 2; k++) { system.out.print(\' \' + heapdata[k] \'		\' heapdata[2 * k 1] 2]); system.out.println(); } create designmaxheap() method to construct min heap public void for (int position="0;" < (sizeofheap 2); position++) maxheapify(position); removeroot() removing maximum element from the publicintremoveroot() intpopelement="heapData[FRONT];" heapdata[front]="heapData[sizeOfHeap--];" maxheapify(front); returnpopelement; minheapjavaimplementation class in java classmaxheapjavaimplementation{ main() start static main(string[] arg) declare variable intheapsize; scanner object sc="new" scanner(system.in); system.out.println(\'enter size of max heap\'); heapsize="sc.nextInt();" maxheapheapobj="new" maxheap(50); for(inti="1;" i<="heapSize;" i++) system.out.print(\'enter \'+i+\' element: \'); int data="sc.nextInt();" heapobj.insertnode(data); close obj sc.close(); a given heapobj.designmaxheap(); display system.out.println(\'the is heapobj.displayheap(); root node system.out.println(\'after element(root node) \'+heapobj.removeroot()+\', is:\'); pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/java-tutorial/97/heap-implementation-java-4.webp" alt="Heap implementation in Java"> <hr></sizeofheap></=>