Heap sorting exercise questions

Source: Internet
Author: User
#include 
  
    using namespace STD; Class heapsort {PRIVATE: int Len; vector 
   
     list; void swapnode (int I, int heapsize); Public: void sort (); void print (); heapsort (void );~ Heapsort (void) ;}; 
   
  
# Include <iostream> # include "heapsort. H" using namespace STD; heapsort: heapsort (void) {Len = 10;} heapsort ::~ Heapsort (void) {} void heapsort: swapnode (int I, int heapsize) {int L = I * 2; int r = I * 2 + 1; int max = I; if (L <= heapsize & list [L-1]> list [I-1]) max = L; If (r <= heapsize & list [r-1]> list [L-1]) max = r; If (max! = I) {int TMP = list [max-1]; list [max-1] = list [I-1]; list [I-1] = TMP; swapnode (max, heapsize );}} void heapsort: Sort () {for (INT I = Len/2; I> 0; I --) {swapnode (I, Len);} int heapsize = Len; for (INT I = len-1; I> 0; I --) {int TMP = list [I]; list [I] = list [0]; list [0] = TMP; swapnode (1, -- heapsize) ;}} void heapsort: Print () {for (INT I = 0; I <Len; I ++) {int RND = rand () % 100; List. push_back (RND); cout <RND <"" ;}cout <Endl; sort (); For (INT I = 0; I <Len; I ++) {cout <list [I] <";}cout <Endl ;}

By default, heap sorting regards arrays as a binary tree. The first step is to adjust the order of arrays from small to large from top to bottom (maximum heap ),

Step 2: extract the last number in the heap (tree), place the number on the heap top, and take out the maximum number on the heap top. Change the number of heap elements (the number has been removed) and adjust the smaller number on the top of the heap.

Step 2 clearly shows a lot of meaningless comparisons. In general, the heap sorting performance is not high, and the lowest complexity is nlogn.

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.