Introduction to algorithms Java Implementation of heap sorting

Source: Internet
Author: User

The time complexity of heap sorting is O (nlogn), which has a great advantage over O (n ^ 2) of insert sorting. For Merge Sorting, the time complexity is the same as that of the two, however, heap sorting has a space source and does not require array replication operations like merging. Therefore, heap sorting has many advantages,

The following describes the java Implementation of heap sorting in the introduction to algorithms.

/*** Heap sorting **/public void heapSort (int [] A) {// create the maximum heap buildMaxHeap (A,. length); for (int I =. length-1; I> 0; I --) {// exchange data between the root node and the last node int temp = A [I]; A [I] = A [0]; A [0] = temp; // extract the root node from the max heap, // reduce the heap size by 1 and re-maintain the maximum heap nature to implement maxHeapify (A, 1, I );}} /** create Max heap * @ param A * @ param heapSize, */private void buildMaxHeap (int [] A, int heapSize) {for (int I = heapSize/2; I> 0; I --) {maxHeapify (A, I, heapSize ); }/** Process of maintaining the maximum heap attributes, * The maximum heap attribute is that the value of each node is at most as big as its root node * @ param A * @ param I root node * @ param heapSize heap size */private void maxHeapify (int [] a, int I, int heapSize) {int largest = I; // The index int left = 2 * I used to record the maximum value of the parent and son nodes; // left son node int right = left + 1; // right son node if (left <= heapSize & A [left-1]> A [I-1]) {largest = left;} else {largest = I;} if (right <= heapSize & A [right-1]> A [largest-1]) {largest = right;} if (lar Gest! = I) {int temp = A [I-1]; A [I-1] = A [largest-1]; A [largest-1] = temp; // re-maintain the heap with largest as the root node after the switch, // keep it maxHeapify (A, largest, heapSize );}}

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.