Introduction to Algorithms 9.1-1

Source: Internet
Author: User

Look for the second small element:

If we use the heap sort method, we build a heap only after we have to compare the size of the left son and right son of the root node to get the second small node. And the price of Buildheap is only O (n).

1#include <iostream>2 3 using namespacestd;4 5 #defineLeft (i) i*2+16 #defineRight (i) i*2+27 8 intSize =Ten;9 Ten voidExchange (int&a,int&b) One { A     intc =A; -A =b; -b =C; the } -  - voidMaxheap (intA[],inti) - { +     intL =Left (i); -     intR =Right (i); +     intlargest =i; A     if(L < Size&&a[l] <A[largest]) atlargest =l; -     if(R < Size&&a[r] <A[largest]) -largest =R; -     if(Largest! =i) -     { - Exchange (A[largest], a[i]); in Maxheap (A, largest); -     } to } +  - voidBuildheap (inta[]) the { *      for(inti = (Size-1) /2; I >=0; i--) $     {Panax Notoginseng Maxheap (A, i); -     } the } +  A intMain () the { +     intA[] = { -,4,Ten, -, -,9,3,2,8,1 }; - Buildheap (a); $      for(inti =0; I <Ten; i++) $cout << A[i] <<"    "; -     if(A[left (0)] < A[right (0)]) -cout << Endl << a[left (0)] <<Endl; the     Else -cout << endl<< A[right (0)] <<Endl;Wuyi}

However, this practice does not conform to the requirements of the topic, not reflected in the topic of N+ceil (LGN)-2 of the elaboration, so I am in the realization of the idea of the topic.

Introduction to Algorithms 9.1-1

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.