Heap sorting of sorting algorithms

Source: Internet
Author: User

Algorithm idea: heap definition: source [I] <= source [2 * I] & source [I] <= source [2 * I + 1] or source [I] <= source [2 * I] & source [I] <= source [2 * I + 1];

Heap sorting thought: (1) Build the waiting sequence into a heap; (2) Take the first element of the heap as the last element of the sequence,

And rebuild the remaining elements into a heap. (3) Repeat the second step until the sequence ends.


C # implementation:

/// <Summary> /// heap sorting /// </Summary> /// <Param name = "Source"> sequence to be sorted </param> private void heapsort (int [] source) {for (INT I = source. length/2; I> = 0; I --) {heapadjust (source, I, source. length);} For (Int J = source. length-1; j> = 0; j --) {int temp = source [0]; source [0] = source [J]; source [J] = temp; heapadjust (source, 0, j) ;}/// <summary> /// change to heap /// </Summary> /// <Param name = "soure "> Sequence to be sorted </param> // <Param name =" I "> the I-th element in the sequence </param> /// <Param name =" len"> length of the sorting sequence </param> private void heapadjust (INT [] soure, int I, int Len) {int Index = 0; For (Int J = I; 2 * j + 1 <len-1; j = index) {Index = 2 * j + 1; // left subnode number if (index <len-1 & soure [Index] <soure [index + 1]) // find the large value in the left and right subnodes. {Index ++;} If (soure [Index]> soure [J]) // compare the root node and the larger child node, if the root node is small, {int temp = soure [Index]; soure [Index] = soure [J]; soure [J] = temp ;}}}
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.