Sort algorithm-heap sort

Source: Internet
Author: User

Some of the content goes from:

Dreamcatcher-cx

Source:

This article is copyrighted by the author and the blog Park, welcome reprint, but without the consent of the author must retain this paragraph, and in the page obvious location to give the original link.

Pre-knowledge

Heap Sort

Heap sorting is a sort algorithm designed by using the data structure of heap , heap sort is a sort of choice, its worst, best, average time complexity is O (NLOGN), it is also unstable sort. Start with a simple understanding of the next heap structure.

Heap

 A heap is a complete binary tree with the following properties: The value of each node is greater than or equal to the value of its left and right child nodes, called the Big Top heap, or the value of each node is less than or equal to the value of its left and right child nodes, called the small top heap. Such as:

At the same time, we are numbering the nodes in the heap by layer, mapping this logical structure to the array is what it looks like below.

The array is logically a heap structure, and we use simple formulas to describe the definition of a heap:

Big Top pile: arr[i] >= arr[2i+1] && arr[i] >= arr[2i+2]

Small top pile: arr[i] <= arr[2i+1] && arr[i] <= arr[2i+2]

OK, these definitions are understood. Next, let's look at the basic idea and basic steps of heap sequencing:

Basic ideas and steps of heap sequencing

  The basic idea of heap ordering is to construct the sequence to be sorted into a large top heap, at which point the maximum value of the entire sequence is the root node of the heap top. Swap it with the end element, which is the maximum value at the end. The remaining n-1 elements are then reconstructed into a heap, which gives the minor values of the n elements. So repeatedly, you get an ordered sequence.

Step one constructs the initial heap. Constructs the given unordered sequence into a large top heap (generally ascending with a large top heap, and descending with a small top heap).

A. Assume that the given unordered sequence structure is as follows

2. At this point we start from the last non-leaf node (the leaf node naturally does not have to adjust, the first non-leaf node arr.length/2-1=5/2-1=1, that is, the following 6 nodes), from left to right, from bottom to top to adjust.

4. Find the second non-leaf node 4, because [4,9,8] 9 elements are the largest, 4 and 9 are exchanged.

At this point, the interchange resulted in a sub-root [4,5,6] structure confusion, continued adjustment, [4,5,6] 6 Max, Exchange 4 and 6.

At this point, we will construct a large top heap without a sequence.

Step two swaps the top element of the heap with the end element, making the end element the largest. Then continue to adjust the heap, and then swap the top element of the heap with the end element to get the second largest element. So repeated exchange, reconstruction, exchange.

A. Swapping the top element 9 and the end element 4 of the heap

B. Restructure the structure so that it continues to meet the heap definition

C. Then exchange the top element 8 of the heap with the end element 5 to get the second largest element 8.

The subsequent process, which continues to be adjusted, exchanged, and so repeated, which ultimately makes the entire sequence orderly

Briefly summarize the basic idea of heap sorting:

  A. Build a heap with no sequence, and select a large top heap or a small top heap according to the ascending descending order requirement;

B. Swap the top element of the heap with the end element and "sink" the largest element to the end of the array;

C. Restructure the structure so that it satisfies the heap definition, and then proceed to swap the top element of the heap with the current end element, repeatedly performing the adjustment + Exchange step until the entire sequence is ordered.

Code implementation:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespace_011_ Heap Sort {classProgram {Static voidMain (string[] args) {            int[] data = {4,6,8,5,9};            Heapsort (data); foreach(varIteminchdata) {Console.Write (item+" "); }        }         Public Static voidHeapsort (int[] data) {            //Traverse all the non-leaf nodes of this number, turning all the subtrees into a sub-large top heap .             for(inti = data. length/2; I>0; i--)            {                //adjusts the structure from the first non-leaf node from bottom to top, right to left .Heapajust (i, data, data.            Length); }            //2. Adjusting the heap structure + Exchange heap top element and end element             for(inti = data. length-1; i >0; i--)            {                //Exchange the number 0 and the position of the number ISwap (data,0, i); ////re-adjust the heapHeapajust (1, Data,i); }        }        /// <summary>        ///adjustment of large top piles built on large top piles has been built on the foundation/// </summary>        /// <param name= "Numbertojust" ></param>        /// <param name= "Data" ></param>        /// <param name= "MaxNumber" ></param>         Public Static voidHeapajust (intNumbertojust,int[] Data,intmaxnumber) {            intMaxnodenumber = Numbertojust;//number of maximum nodes            intTempi =Numbertojust;  while(true)            {                //Turn the sub-tree of I node into a big top heap                intLeftchildnumber = Tempi *2; intRightchildnumber = Leftchildnumber +1; if(Leftchildnumber <= maxnumber && data[leftchildnumber-1] > Data[maxnodenumber-1]) Maxnodenumber=Leftchildnumber; if(Rightchildnumber <= maxnumber && data[rightchildnumber-1] > Data[maxnodenumber-1]) Maxnodenumber=Rightchildnumber; if(Maxnodenumber! = tempi)//found a larger sub-node than I exchange data inside I and Maxnodenumber{Swap (Data,tempi-1, maxnodenumber-1); Tempi=Maxnodenumber; }                Else                {                     Break; }            }        }         Public Static voidSwap (int[] arr,intAintb) {inttemp =Arr[a]; Arr[a]=Arr[b]; ARR[B]=temp; }    }}
At last

Heap sorting is a sort of selection, the whole consists of building the initial heap + Exchange heap top and end elements and rebuilding the heap two parts. The construction of the initial heap by derivation of the complexity of O (n), in the process of exchanging and rebuilding the heap, the exchange of n-1 times, and the process of rebuilding the heap, according to the nature of the complete binary tree, [log2 (N-1), log2 (n-2) ... 1] gradually decreasing, approximate to Nlogn. So the heap sorting time complexity is generally considered to be O (Nlogn) level.

Sort algorithm-heap sort

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.