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