java - maxheap method of heapSort with index 0 and not index 1 -
I have this code for heapSort
that works fine. I also understand that algorithm
then works when the start is index
and 1
and not 0
. My question is that under the maxheap
method, all the more than zero works for all the indexes, but not index 0. Although sorting
method index 0
and array
becomes sorted
. When index i = 0
, maxheap
will call left = 2 * i = 0 and right = 2 * i + 1 = 1
, which will be i
and on the left side
0
and right
on index 1
Which means that root
and left
are identical and only the right
tree is confusing to me. Here's the code:
Public class HeapSort {Private Static Ent Hepsism; / * Sort Function * / Public Static Virus Sort (Ent Ar []) {Hephafe (AR); System.out.println ("arrays" + arrays.toString (arr)); For (int i = hep size; i> i--) {swap (ar, 0, i); Heape size = heap size-1; MaxHeap (ARM, 0); }} / * Function to create a pile * / Public stable zero Hepapheer (ant ar []) {heapSize = arr.length-1; For (IntiI = Hap Size / 2; I> = 0; I -) Maxhep (ARI, I); System.out.println ("Max Ended"); } / * Function to swap the largest element in the heap * / Public Static Zero Maxhep (Ent Ar [], Int I.) {// Heap Size = arr.length-1; // If you have defined 'hepseys' Heapfy method int bound = 2 * i; Int correct = 2 * I + 1; Int max = i; If (left & lt; = heapSize & amp; amp; [left] & gt; arr [i]) max = left; If (right & lt; = heapSize & amp; AR [rights] & gt; arr [max]) max = true; // system Out.printfaltes (% s; left is% s; true% s; maximum% s% n, i, left, right, max); if (maximum! = I) {swap (arr, i, max); MaxHeap (ARM, Max);}} / * function to swap two numbers in an array * / public static zero swap (int AR [], int i, int j) {//System.out.println (- Called "); Int tmp = arr [i]; ARR [ii] = ARR [ja]; ARR [j] = tmp; } / * Main method * / Public static zero main (string [] Args) {System.out.println ("Heap sort test \ n"); / * Sort call method * / int [] arr = {34,5,6,712,90}; Type (arrival); System.out.println ("\ nAllments after sorting"); Println (Arrays.toString (Arrival)); / * Maximize call method; Make sure that you comment in heapSize = arr.length in the method * / int [] arr2 = {2,1,3}; MaxHeap (AR2, 1); // maxhet (ARR-3.0) will not work, so output system. Out.printline (arrays.toString (arr2)) gives the same arr2 as; }}
Edit: These two blogs use the same code: sanfoundry.com/java-program-implement-heap-sort, sciencetechpedia.blogspot.com/2012 / 11 / When your array is 0-based, you can use your enter-orange. The child nodes are
(2 * i) + 1
and (2 * i) +2
.
To normalize, the child nodes (2 * i) + 1-array_base
and (2 * i) + 2-array_base
.
Comments
Post a Comment