for every node i other than the root. After the heap is built, the root (leftmost position in the array) has the minimum element. Sorting then repeatedly moves ...
Home
Public
Questions
Tags
Users
Companies
Collectives
ExploreCollectives
Teams
StackOverflowforTeams
–Startcollaboratingandsharingorganizationalknowledge.
CreateafreeTeam
WhyTeams?
Teams
CreatefreeTeam
Collectives™onStackOverflow
Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost.
Learnmore
Teams
Q&Aforwork
Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch.
Learnmore
HeapsortAlgorithmusingmin-heap
AskQuestion
Asked
8years,10monthsago
Modified
4years,2monthsago
Viewed
25ktimes
7
4
WhenIimplementheapsortusingamin-heapitsortsthearrayfromlargesttosmallest.Isthisthedesiredoutputforaheapsortusingmin-heap?Itseemsredundanttosortagaintooutputsmallesttolargestafterthesortiscompletesincetheheapitselfhasasmallesttolargeststructure.
CODE:
#include
#include
#include"random.h"
#include"print.h"
intparent(inti)
{
return(i-1)/2;
}
intleft(inti)
{
if(i==0)
return1;
else
return2*i;
}
intright(inti)
{if(i==0)
return2;
else
return2*i+1;
}
voidmin_heapify(std::vector&A,inti,intheapsize)
{
intsmallest;
intl=left(i);
//std::cout<&A)
{
intheapsize=A.size()-1;
for(inti=(A.size()-1)/2;i>=0;i--)
min_heapify(A,i,heapsize);
}
voidheapsort(std::vector&A)
{
intheapsize=A.size()-1;
build_min_heap(A);
std::cout<0;i--){
exchange(A,0,i);
heapsize--;
std::cout<B;
fill(B,5);
print(B);
heapsort(B);
print(B);
return0;
}
Outputfromcode:
4165314119
4165314119
4165194131
4119654131
4119314165
1941314165
heapsortafterbuildmaxheap
1931414165
heapsize=3
6531414119
3165414119
heapsize=2
heapsize=1
6541413119
heapsize=0
6541413119
Outputfor20elements:
41653141191572117869372329637545497599
afterbuildmaxheap
45151119232941316937417263756578497599
aftersort
99787575726965634941413731292319151154
c++heapsort
Share
Improvethisquestion
Follow
editedMay27,2018at12:59
JeJo
27.1k66goldbadges4444silverbadges8383bronzebadges
askedSep20,2013at17:27
MarsMars
4,21588goldbadges3939silverbadges6363bronzebadges
3
Canyoushowyourcode?
– ReinstateMonica--notmaynard
Sep20,2013at17:31
1
Lettherebeabinarytreeontheheap.Tosortanarray,youinsertelementsonebyoneintothetree.Obvioussly,theelementsareinacertainorderinthetree,butyouwantthembackinanarray.Soyoutraversethetreetakingthesmallestelementsfirstandyouputthembackintoanarray.
– cpp
Sep20,2013at17:38
Relatedblogpostanddemocode.
– JerryCoffin
Sep20,2013at18:58
Addacomment
|
3Answers
3
Sortedby:
Resettodefault
Highestscore(default)
Trending(recentvotescountmore)
Datemodified(newestfirst)
Datecreated(oldestfirst)
6
Order:Usemax-heapifytosortinascedingorder,min-heapifytosortindescendingorder.
Sorting:Buildingtheheapwithmin-heapifydoesnotsortyourarray;itonlyenforcesthe(weaker)min-heapproperty,thatis
A[parent(i)]<=A[i]
foreverynodeiotherthantheroot.Aftertheheapisbuilt,theroot(leftmostpositioninthearray)hastheminimumelement.Sortingthenrepeatedlymoveselementsfromtheroottotherightandcallsmin-heapifyontheroot(bringingtheretheminimumofwhatremains),hencethedescendingorder.
Thecodeyouarepostingappearscorrectataglancebutdoesnotcompileasis,soIcannottest.Ifyourarrayappearssortedrightafterbuildingtheheap,itshouldbeacoincidence.Tryalargertest.
Share
Improvethisanswer
Follow
editedSep20,2013at18:01
answeredSep20,2013at17:38
iavriavr
7,43711goldbadge1515silverbadges5252bronzebadges
7
1
Try15-20elementsandyou'llsee!
– iavr
Sep20,2013at17:56
Whenyousaymyarrayappearssorted,youmeanafterIbuildtheheap?
– Mars
Sep20,2013at18:41
Ipostedmyoutputwith20elements.Isthisheapwrong?It'snotinsortedorderbutIdon'tthinkitneedstobe.Allthechildnodesaresmallerinvaluethantheparentnode.
– Mars
Sep20,2013at18:47
1
@ComradeYes.Youroutputshows1931414165rightafterbuildingtheheap.Yousaythisissorted,butitonlysatisfiesthemin-heapproperty,whichhappenstobethesameinthiscase.Min-heappropertyonlysays19<=31,19<=41,31<=41,31<=65.
– iavr
Sep20,2013at18:47
1
Yes.ThatisallIwasreallyasking.Ifthepurposeofusingamin-heapwastosortindescendingorder.IamgladIaskedthoughbecausethefirstoutputcoincidentallyhadtheelementssortedandIhadbelievedthatbuildingtheheapwasalsosortingtheelements,whichitwasn'tofcourse.
– Mars
Sep20,2013at19:10
|
Show2morecomments
2
Normallyyouuseamax-heaptosortinascendingorder,becauseitseasier.
Usingamax-heap,you'float'themaxtothefront,andbuildthesortedlistfromtheback.
Ifyouwanttouseamin-heaptosortinascendingorder,youhavetobuilditbackwards.(iethelowestisthelastindex).Otherwiseyouwillbechurningyourheap.
start18706131255
min-heap(backwards)->18705513126
then
swap6w18->6,7055131218->sink18->7055131812
swap12w70->612,55131870->sink70->55701813
swap13w55->61213,701855->sink55->705518
swap18w70->6121318,5570->sink70->7055
swap55w70->612131855,70
done
Share
Improvethisanswer
Follow
editedSep20,2013at22:37
answeredSep20,2013at17:37
SanjayaRSanjayaR
6,01611goldbadge1616silverbadges1919bronzebadges
1
3
Thatseemstodefeatthepurposeofbuildingaheapinthefirstplace.
– Mars
Sep20,2013at17:53
Addacomment
|
2
Iwasjustwonderingaboutthatveryproblem(isn'tHeapsorthavinganextrastepattheend,theunnecessaryswappingofelements.Justusemin-heapsandletcallmin-heapifyandgetyourworkdone).
Regardingthisway,wecouldhaveachievedO(logn)timewhichsomewhatdisqualifiesthebinarydecisiontreemodel-whichsaysO(nlogn)isacceptabletightestupperboundoncomparisonsortingalgorithms.
Theshortansweris:heapdatastructurearen'tbinarysearchtrees.Aheapmayguaranteeorderingofelementsinsortedtop->bottomway,butabinarysearchtreeguaranteesthey'llbeorderedlefttorightaswell.Wewerejustmixingupbinarytreesandheaps.
Aminheaponlyguarantees,
Amin[Parent]<=A[either_of_the_children]//saysnothingaboutorderingofchildren
Hereisabinarytree(althoughunbalancedandnotsorted):
AndhereisaHeap:
Hopeyougetmypoint.Ifstillnot,thenthinkofitas,aminheaprepresentedanarrayguaranteesthatparentissmallerthanitschild,butsaysnothingaboutareallchildrenarrangedinsortedorderlefttoright?
We'llstillbeperformingmin-heapifyoneachchildofcurrentroottobeswapped.
Share
Improvethisanswer
Follow
editedDec9,2017at4:13
answeredMay13,2015at12:32
AbhinavGauniyalAbhinavGauniyal
6,38577goldbadges4646silverbadges9090bronzebadges
1
2
aheapISabinarytree(aparentcanhavemax2children),butitisn'tabinarySEARCHtree(leftchild