Heaps(PriorityQueues)Aheapisadatastructurewhichsupportsefficientimplementationofthreeoperations:insert,findMin,anddeleteMin.(Suchaheapisamin-heap,tobemoreprecise.)Twoobviousimplementationsarebasedonanarray(assumingthesizenisknown):insertfindMindeleteMinSortedarrayO(n) O(1)O(1)(fromlarge(tomove(findatend) (deletetheend)tosmall)elements) LinkedlistO(1)O(1)O(n) (append)(apointertoMin)(resetMinpointer)Asimplerbutrelatedproblem:Findthesmallestandthesecondsmallestelementsinanarray(ofsizen):Astraightforwardmethod:Findthesmallestusingn–1comparisons;swapittotheendofthearray,findthenextsmallestinn–2comparisons,foratotalof2n–“saves”parisons:(1)Dividethearrayintotwohalves,findthesmallestelementsofeachhalf,callthemmin1andmin2,respectively;(paremin1andmin2,tofindthesmallest;(3)hesecondsmallest;(n–1)+(n/2–1)=(3n/2–:min1min2minFirsthalfofarraySecondhalfofarrayInthefigure,alinkconnectsasmallerelementtoalargeronegoingdownward;forexample,minmin1andminmin2,andmin1eachelementinthefirsthalfofthearray,-heaps:pletebinarytreeifthetreeisfullateachlevelexceptpossiblyatthemaximumlevel(depth),wherethetreeisfullatlevelimeansthereare2inodesatthatlevel(recalltherootisatlevel0);andatthetree’smaximumlevelh,,then2hn2h+1–,hlgn<(h+1).Inparticular,h=O(lgn).Abinarytreesatisfiesthe(min-)heap-orderpropertyifthevalueateachislessthanorequaltothevalueateachofthechildnodes(ifexist).Abinarymin-pletebinarytreethatalsosatisfiestheheap-;also,-heapTwobasicoperationsonbinarymin-heaps:Supposethevalu
Heaps(PriorityQueues)Aheapisadatastructurewhich 来自淘豆网www.taodocs.com转载请标明出处.