sorting | Heap Sort

Source: Internet
Author: User

Start with a C + + code to see the process of push sequencing:

1#include <iostream>2#include <algorithm>3 using namespacestd;4 5 BOOLcmpConst intLhsConst intRHS)6 {7     returnLHS >RHS;8 }9 Ten intMain () One { A     intArr[] = {4,2,Ten,9,5,6,8,6,7,1,3}; -Make_heap (arr, arr+Ten); -      for(inti = One; I >=0; --i) { thePop_heap (arr, arr+i); -          for(inti =0; I < One; ++i) cout << Arr[i] <<' '; -cout <<Endl; -     } +  -     return 0; +}

Mainly Make_heap, pop_heap

Make_heap: Build heap, default Max heap-"Get increment array (because POP_HEAP is to take the heap top out and then put it back)

Pop_heap:arr[0] and Arr[i] exchange, and maintain the heap structure of arr[0] to arr[i-1].

Meke_heap can be subdivided into a heap from the bottom to the top, the recursive is to maintain I, you have to maintain the i.left and i.right.

And Pop_heap is the N-Times maintenance root node.

So, in fact, just write a maxheapify.

1 voidMaxheapify (intArr[],intNinti)2 {3     intL =2*i;4     intR =2*i +1;5     intlargest = i;6     if(L < n && Arr[l] >Arr[largest])7largest =L9     if(R < n && Arr[r] >Arr[largest])Tenlargest =R; One  A     if(Largest = = i)return; - swap (Arr[i], arr[largest]); - maxheapify (arr, n, largest); the}

The process of maintaining the heap is simply to keep sinking.

The back of the Meke_heap and pop_heap is not difficult to write.

Makeheap (arr, n):

For i = N/2 Downto 1:

Maxheap (arr, n, i);

Popheap (arr, n):

Swap (arr[0], arr[--n]);

Maxheap (arr, n, 0);

Then the sortHeap is easy to write:

SortHeap (arr, n):

Makeheap (arr, n);

For i = n Downto 0:

Popheap (arr, i);

sorting | 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.