Java implementation of heap sorting algorithm

Source: Internet
Author: User

Stacking Sort (Heapsort) is a sort algorithm designed using the data structure of a stacked tree (heap), which can quickly locate the elements of the specified index using the characteristics of the array. Heap ordering is an unstable sorting method, the auxiliary space is O (1), the worst time complexity is O (nlog2n), and the average performance of heap sequencing is closer to the worst performance.

The central idea is to construct a large top heap or a small top heap each time from the bottom up to the top of the complete binary tree using the array storage, and then put the number of heap tops found at the end of the array, leaving the array to continue constructing the heap structure.

Mainly refers to the online more common two kinds of heap sorting Java implementation, and added some comments

Implementation 1

Recursive, each time the parent node is exchanged with the maximum child node, recursively constructs the sub-tree after being swapped

     Public Static voidHeapsort (int[] Array) {        if(Array = =NULL|| Array.Length <= 1) {            return;        } buildmaxheap (array); System.out.println ("Buildmaxheap" +arrays.tostring (array));  for(inti = array.length-1; I >= 1; i--) {exchangeelements (array,0, i); Maxheap (Array, I,0); System.out.println ("Maxheap" + arrays.tostring (array) + "I is" +i); }    }    Private Static voidBuildmaxheap (int[] Array) {        if(Array = =NULL|| Array.Length <= 1) {            return; }        intHalf = ARRAY.LENGTH/2-1; //depending on the nature of the binary tree, a two-tree with a depth of K has a maximum of 2 K-squares-1 nodes (k≥1)//so if the last node is the right node and the array.length is odd, then the number of the parent node on the previous level should be (array.length-1)/2=ARRAY.LENGTH/2//so if the last node is the left node and the Array.Length is even, then the number of the parent node on the previous level is also ARRAY.LENGTH/2//since the array subscript starts at 0, it should be based on the number of the heap corresponding to-1//From the bottom of the comparison of the largest value to the top, and after the risk of being replaced by the value of the corresponding sub-tree to do the heap adjustment again.          for(inti = half; I >= 0; i--) {maxheap (array, array.length, i); }    }    Private Static voidMaxheap (int[] Array,intHeapSize,intindex) {        //heap number x, array number index, a=index+1; //so the left node array number =2a-1=index * 2 + 1//Right Node array number =2a+1-1=index * 2 + 2        intleft = index * 2 + 1; intright = Index * 2 + 2; intlargest =index; if(Left < heapsize && Array[left] >Array[index]) {Largest=Left ; }        if(Right < HeapSize && Array[right] >Array[largest]) {Largest=Right ; }        if(Index! =largest) {exchangeelements (array, index, largest);//swap a larger value of a child node to the parent nodeSystem.out.println ("Maxheap" +arrays.tostring (Array)+ ' index is ' + index + ' left is ' + left + ' right ' + right + ' largest is ' + largest + ' heaps Ize is "+heapsize); Maxheap (array, heapsize, largest);//The value of the original parent node may not satisfy the nature of the heap after it has been placed on the child node, and the subtree corresponding to the modified largest node needs to be adjusted        }    }    Private Static voidExchangeelements (int[] Array,intIndex1,intindex2) {        inttemp =ARRAY[INDEX1]; ARRAY[INDEX1]=Array[index2]; ARRAY[INDEX2]=temp; }

Implementation 2

While loop, the same parent-child node is exchanged to record the location of the changed child nodes, using while (2 * k + 1 <= lastIndex) loop to determine whether the corresponding subtree conforms to the heap properties and adjusts

     Public Static voidHeapSort2 (int[] Array) {         for(inti = 0; i < Array.Length; i++) {maxHeap2 (array, Array.Length-1-i); Exchangeelements (Array,0, Array.length-1-i);        System.out.println (arrays.tostring (array)); }    }    Private Static voidExchangeelements (int[] Array,intIndex1,intindex2) {        inttemp =ARRAY[INDEX1]; ARRAY[INDEX1]=Array[index2]; ARRAY[INDEX2]=temp; }    Private Static voidMAXHEAP2 (int[] Data,intLastIndex) {        //lastindex= array.length-1//SO (lastindex+1)/2-1 equals the index of the last node in the array that has a child node//(lastindex+1)/2-1= (lastIndex-1)/2         for(inti = (lastIndex-1)/2; I >= 0; i--) {            //Save the node currently being judged            intK =i; //if the left node of the current node exists             while(2 * k + 1 <= lastIndex) {//                                //Biggerindex always records the value of a larger node, first assigning the left child node of the current judgment node                intBiggerindex = 2 * k + 1; if(Biggerindex <LastIndex) {                    //If the right child node exists, compare the size of the left and right child nodes, there is no Biggerindex left node                    if(Data[biggerindex] < Data[biggerindex + 1]) {                        //If the right child node value is greater than the left dial hand node value, then the value of the right child node is biggerindex recorded.biggerindex++; }                }                if(Data[k] <Data[biggerindex]) {                    //if the current node value is smaller than the maximum child node value, then the exchange of 2 is the value of the Biggerindex value assigned to Kexchangeelements (data, K, biggerindex); K= Biggerindex;//K Records where the original parent node was swapped, and the original parent node is not necessarily larger than the child node .//The While loop continues to determine that its corresponding sub-tree character does not conform to the nature of the heap and adjustsSystem.out.println ("K is" +k+ "" +arrays.tostring (data)); } Else {                    //The parent node is already larger than the child node and does not need to be adjusted                     Break; }                                //System.out.println ();            }        }    }

Resources

http://blog.csdn.net/apei830/article/details/6584645

http://blog.csdn.net/kimylrong/article/details/17150475

Java implementation of heap sorting algorithm

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.