Académique Documents
Professionnel Documents
Culture Documents
Chapter10
SortingAlgorithms
Heapsort:ArrayBasedLists
Overcomesquicksortworstcase
Heap:listinwhicheachelementcontainsakey
Keyintheelementatpositionkinthelist
Atleastaslargeasthekeyintheelementatposition
2k+1(ifitexists)and2k+2(ifitexists)
C++arrayindexstartsatzero
Elementatpositionk
k+1thelementofthelist
FIGURE1041Aheap
DataStructuresUsingC++2E
Heapsort:ArrayBasedLists(contd.)
DatagiveninFigure1041
Canbeviewedinacompletebinarytree
Heapsort
Firststep:convertlistintoaheap
CalledbuildHeap
Afterconvertingthearrayintoaheap
Sortingphasebegins
FIGURE1042Completebinarytree
correspondingtothelistinFigure1041
DataStructuresUsingC++2E
BuildHeap
DataStructuresUsingC++2E
BuildHeap(contd.)
Functionheapify
Restorestheheapinasubtree
ImplementsthebuildHeapfunction
Convertslistintoaheap
DataStructuresUsingC++2E
DataStructuresUsingC++2E
BuildHeap(contd.)
DataStructuresUsingC++2E
BuildHeap(contd.)
Theheapsortalgorithm
FIGURE1048Heapsort
DataStructuresUsingC++2E
Analysis:Heapsort
GivenLalistofnelementswheren>0
Worstcase
NumberofkeycomparisonstosortL
2nlog2n+O(n)
NumberofitemassignmentstosortL
nlog2n+O(n)
AveragenumberofcomparisonstosortL
O(nlog2n)
Heapsorttakestwiceaslongasquicksort
Avoidstheslightpossibilityofpoorperformance
DataStructuresUsingC++2E
PriorityQueues(Revisited)
Customersorjobswithhigherpriorities
Pushedtofrontofthequeue
Assumepriorityofthequeueelementsisassigned
usingtherelationaloperators
Inaheap,largestlistelementisalwaysthefirst
elementofthelist
Afterremovinglargestlistelement
Functionheapifyrestorestheheapinthelist
Implementpriorityqueuesasheaps
Toensurelargestelementofthepriorityqueueis
alwaysthefirstelementofthequeue
DataStructuresUsingC++2E
10
PriorityQueues(Revisited)(contd.)
Insertanelementinthepriorityqueue
Insertnewelementinfirstavailablelistposition
Ensuresarrayholdingthelistisacompletebinarytree
Afterinsertingnewelementintheheap,thelistmight
nolongerbeaheap
Restoretheheap(mightresultinmovingthenewentry
totherootnode)
DataStructuresUsingC++2E
11
PriorityQueues(Revisited)(contd.)
Removeanelementfromthepriorityqueue
Assumepriorityqueueimplementedasaheap
Copylastelementofthelistintofirstarrayposition
Reducelistlengthbyone
Restoreheapinthelist
Otheroperationsforpriorityqueues
Canbeimplementedinthesamewayasimplemented
forqueues
DataStructuresUsingC++2E
12
Summary
Searchalgorithmsmayrequiresorteddata
Severalsortingalgorithmsavailable
Selectionsort,insertionsort,Shellsort,quicksort,
mergesort,andheapsort
Canbeappliedtoeitherarraybasedlistsorlinkedlists
Comparealgorithmperformancethroughanalysis
Numberofkeycomparisons
Numberofdatamovements
Functionsimplementingsortingalgorithms
Includedaspublicmembersoftherelatedclass
DataStructuresUsingC++2E
13
DataStructuresUsingC++2E
Chapter11
BinaryTreesandBTrees
Objectives
Learnaboutbinarytrees
Explorevariousbinarytreetraversalalgorithms
Learnhowtoorganizedatainabinarysearchtree
Discoverhowtoinsertanddeleteitemsinabinary
searchtree
DataStructuresUsingC++2E
15
Objectives(contd.)
Explorenonrecursivebinarytreetraversal
algorithms
LearnaboutAVL(heightbalanced)trees
LearnaboutBtrees
DataStructuresUsingC++2E
16
BinaryTrees
Definition:abinarytree,T,iseitheremptyorsuch
that
Thasaspecialnodecalledtherootnode
Thastwosetsofnodes,LTandRT,calledtheleft
subtreeandrightsubtreeofT,respectively
LTandRTarebinarytrees
Canbeshownpictorially
Parent,leftchild,rightchild
Noderepresentedasacircle
Circlelabeledbythenode
DataStructuresUsingC++2E
17
BinaryTrees(contd.)
Rootnodedrawnatthetop
Leftchildoftherootnode(ifany)
Drawnbelowandtotheleftoftherootnode
Rightchildoftherootnode(ifany)
Drawnbelowandtotherightoftherootnode
Directededge(directedbranch):arrow
FIGURE111Binarytree
DataStructuresUsingC++2E
18
BinaryTrees(contd.)
FIGURE112Binarytreewithone,two,orthreenodes
FIGURE113Variousbinarytreeswiththreenodes
DataStructuresUsingC++2E
19
BinaryTrees(contd.)
Everynodeinabinarytree
Hasatmosttwochildren
structdefiningnodeofabinarytree
Foreachnode
Thedatastoredininfo
Apointertotheleftchildstoredinllink
Apointertotherightchildstoredinrlink
DataStructuresUsingC++2E
20
BinaryTrees(contd.)
Pointertorootnodeisstoredoutsidethebinarytree
Inpointervariablecalledtheroot
OftypebinaryTreeNode
FIGURE114Binarytree
DataStructuresUsingC++2E
21
BinaryTrees(contd.)
Levelofanode
Numberofbranchesonthepath
Heightofabinarytree
Numberofnodesonthelongestpathfromtherootto
aleaf
Seecodeonpage604
DataStructuresUsingC++2E
22
CopyTree
Shallowcopyofthedata
Obtainedwhenvalueofthepointeroftherootnode
usedtomakeacopyofabinarytree
Identicalcopyofabinarytree
Needtocreateasmanynodesasthereareinthe
binarytreetobecopied
Nodesmustappearinthesameorderasinthe
originalbinarytree
FunctioncopyTree
Makesacopyofagivenbinarytree
Seecodeonpages604605
DataStructuresUsingC++2E
23
BinaryTreeTraversal
Muststartwiththeroot,andthen
Visitthenodefirstor
Visitthesubtreesfirst
Threedifferenttraversals
Inorder
Preorder
Postorder
DataStructuresUsingC++2E
24
BinaryTreeTraversal(contd.)
Inordertraversal
Traversetheleftsubtree
Visitthenode
Traversetherightsubtree
Preordertraversal
Visitthenode
Traversetheleftsubtree
Traversetherightsubtree
DataStructuresUsingC++2E
25
BinaryTreeTraversal(contd.)
Postordertraversal
Traversetheleftsubtree
Traversetherightsubtree
Visitthenode
Eachtraversalalgorithm:recursive
Listingofnodes
Inordersequence
Preordersequence
Postordersequence
DataStructuresUsingC++2E
26
BinaryTreeTraversal(contd.)
FIGURE115Binarytree
foraninordertraversal
DataStructuresUsingC++2E
27
BinaryTreeTraversal(contd.)
Functionstoimplementthepreorderandpostorder
traversals
DataStructuresUsingC++2E
28
ImplementingBinaryTrees
Operationstypicallyperformedonabinarytree
Determineifbinarytreeisempty
Searchbinarytreeforaparticularitem
Insertaniteminthebinarytree
Deleteanitemfromthebinarytree
Findtheheightofthebinarytree
Findthenumberofnodesinthebinarytree
Findthenumberofleavesinthebinarytree
Traversethebinarytree
Copythebinarytree
DataStructuresUsingC++2E
29
ImplementingBinaryTrees(contd.)
class binaryTreeType
Specifiesbasicoperationstoimplementabinarytree
Seecodeonpage609
Containsstatementtooverloadtheassignment
operator,copyconstructor,destructor
Containsseveralmemberfunctionsthatareprivate
membersoftheclass
BinarytreeemptyifrootisNULL
SeeisEmptyfunctiononpage611
DataStructuresUsingC++2E
30
ImplementingBinaryTrees(contd.)
Defaultconstructor
Initializesbinarytreetoanemptystate
Seecodeonpage612
Otherfunctionsforbinarytrees
Seecodeonpages612613
Functions:copyTree,destroy,destroyTree
Seecodeonpage614
Copyconstructor,destructor,andoverloaded
assignmentoperator
Seecodeonpage615
DataStructuresUsingC++2E
31
BinarySearchTrees
Dataineachnode
Largerthanthedatainitsleftchild
Smallerthanthedatainitsrightchild
FIGURE116Arbitrarybinarytree
DataStructuresUsingC++2E
FIGURE117Binarysearchtree
32
BinarySearchTrees(contd.)
Abinarysearchtree,T,iseitheremptyorthe
followingistrue:
Thasaspecialnodecalledtherootnode
Thastwosetsofnodes,LTandRT,calledtheleft
subtreeandrightsubtreeofT,respectively
Thekeyintherootnodeislargerthaneverykeyin
theleftsubtreeandsmallerthaneverykeyintheright
subtree
LTandRTarebinarysearchtrees
DataStructuresUsingC++2E
33
BinarySearchTrees(contd.)
Operationsperformedonabinarysearchtree
Searchthebinarysearchtreeforaparticularitem
Insertaniteminthebinarysearchtree
Deleteanitemfromthebinarysearchtree
Findtheheightofthebinarysearchtree
Findthenumberofnodesinthebinarysearchtree
Findthenumberofleavesinthebinarysearchtree
Traversethebinarysearchtree
Copythebinarysearchtree
DataStructuresUsingC++2E
34
BinarySearchTrees(contd.)
Everybinarysearchtreeisabinarytree
Heightofabinarysearchtree
Determinedthesamewayastheheightofabinary
tree
Operationstofindnumberofnodes,numberof
leaves,todoinorder,preorder,postordertraversals
ofabinarysearchtree
Sameasthoseforabinarytree
Caninheritfunctions
DataStructuresUsingC++2E
35
BinarySearchTrees(contd.)
class bSearchTreeType
Illustratesbasicoperationstoimplementabinary
searchtree
Seecodeonpage618
Functionsearch
Functioninsert
Functiondelete
DataStructuresUsingC++2E
36
BinarySearchTree:Analysis
Worstcase
T:linear
Successfulcase
Algorithmmakes(n+1)/2keycomparisons(average)
Unsuccessfulcase:makesncomparisons
FIGURE1110Linearbinarytrees
DataStructuresUsingC++2E
37
BinarySearchTree:Analysis(contd.)
Averagecasebehavior
Successfulcase
Searchwouldendatanode
nitemsexist,providingn!possibleorderingsofthe
keys
Numberofcomparisonsrequiredtodetermine
whetherxisinT
Onemorethanthenumberofcomparisonsrequiredto
insertxinT
NumberofcomparisonsrequiredtoinsertxinT
Sameasnumberofcomparisonsmadeinthe
unsuccessfulsearchreflectingthatxisnotinT
DataStructuresUsingC++2E
38
BinarySearchTree:Analysis(contd.)
DataStructuresUsingC++2E
39
BinarySearchTree:Analysis(contd.)
Theorem:letTbeabinarysearchtreewithnnodes,
wheren>0
TheaveragenumberofnodesvisitedinasearchofT
isapproximately1.39log2n=O(log2n)
Thenumberofkeycomparisonsisapproximately
2.77log2n=O(log2n)
DataStructuresUsingC++2E
40
NonrecursiveInorderTraversal
DataStructuresUsingC++2E
41
NonrecursiveInorderTraversal
(contd.)
DataStructuresUsingC++2E
42
NonrecursivePreorderTraversal
DataStructuresUsingC++2E
43
NonrecursivePreorderTraversal
(contd.)
DataStructuresUsingC++2E
44
NonrecursivePostorderTraversal
DataStructuresUsingC++2E
45
BinaryTreeTraversalandFunctions
asParameters
Passingafunctionasaparametertothetraversal
algorithms
Enhancesprogramsflexibility
C++functionnamewithoutanyparentheses
Consideredapointertothefunction
Specifyingafunctionasaformalparameterto
anotherfunction
SeeExample113
DataStructuresUsingC++2E
46
AVL(HeightBalanced)Trees
AVLtree(heightbalancedtree)
Resultingbinarysearchisnearlybalanced
Perfectlybalancedbinarytree
Heightsofleftandrightsubtreesoftheroot:equal
Leftandrightsubtreesoftherootareperfectly
balancedbinarytrees
DataStructuresUsingC++2E
FIGURE1112Perfectlybalancedbinarytree
47
AVL(HeightBalanced)Trees(contd.)
AnAVLtree(orheightbalancedtree)isabinary
searchtreesuchthat
Theheightsoftheleftandrightsubtreesoftheroot
differbyatmostone
TheleftandrightsubtreesoftherootareAVLtrees
FIGURE1113AVLandnonAVLtrees
DataStructuresUsingC++2E
48
AVL(HeightBalanced)Trees(contd.)
DataStructuresUsingC++2E
49
AVL(HeightBalanced)Trees(contd.)
DefinitionofanodeintheAVLtree
DataStructuresUsingC++2E
50
AVL(HeightBalanced)Trees(contd.)
AVLbinarysearchtreesearchalgorithm
Sameasforabinarysearchtree
OtheroperationsonAVLtrees
Implementedexactlythesamewayasbinarytrees
IteminsertionanddeletionoperationsonAVLtrees
Somewhatdifferentfrombinarysearchtreesoperations
DataStructuresUsingC++2E
51
Insertion
Firstsearchthetreeandfindtheplacewherethe
newitemistobeinserted
Cansearchusingalgorithmsimilartosearch
algorithmdesignedforbinarysearchtrees
Iftheitemisalreadyintree
Searchendsatanonemptysubtree
Duplicatesarenotallowed
IfitemisnotinAVLtree
Searchendsatanemptysubtree;inserttheitemthere
Afterinsertingnewiteminthetree
ResultingtreemightnotbeanAVLtree
DataStructuresUsingC++2E
52
Insertion(contd.)
FIGURE1114AVLtreebeforeandafterinserting90
FIGURE1115AVLtreebeforeandafterinserting75
DataStructuresUsingC++2E
53
Insertion(contd.)
FIGURE1116AVLtreebeforeandafterinserting95
FIGURE1117AVLtreebeforeandafterinserting88
DataStructuresUsingC++2E
54
AVLTreeRotations
Rotatingtree:reconstructionprocedure
Leftrotationandrightrotation
Supposethattherotationoccursatnodex
Leftrotation:certainnodesfromtherightsubtreeofx
movetoitsleftsubtree;therootoftherightsubtreeof
xbecomesthenewrootofthereconstructedsubtree
Rightrotationatx:certainnodesfromtheleftsubtree
ofxmovetoitsrightsubtree;therootoftheleft
subtreeofxbecomesthenewrootofthe
reconstructedsubtree
DataStructuresUsingC++2E
55
FIGURE1118Rightrotationatb
FIGURE1119Leftrotationata
DataStructuresUsingC++2E
56
FIGURE1120Doublerotation:Firstrotateleftataandthenrightatc
FIGURE1121Leftrotationatafollowedbyarightrotationatc
DataStructuresUsingC++2E
57
AVLTreeRotations(contd.)
FIGURE1122Doublerotation:Firstrotaterightatc,
thenrotateleftata
DataStructuresUsingC++2E
58
DataStructuresUsingC++2E
59
DataStructuresUsingC++2E
60
DataStructuresUsingC++2E
61
AVLTreeRotations(contd.)
StepsdescribingthefunctioninsertIntoAVL
Createnodeandcopyitemtobeinsertedintothe
newlycreatednode
Searchthetreeandfindtheplaceforthenewnodein
thetree
Insertnewnodeinthetree
Backtrackthepath,whichwasconstructedtofindthe
placeforthenewnodeinthetree,totherootnode
Ifnecessary,adjustbalancefactorsofthenodes,or
reconstructthetreeatanodeonthepath
DataStructuresUsingC++2E
62
FIGURE1123IteminsertionintoaninitiallyemptyAVLtree
DataStructuresUsingC++2E
63
AVLTreeRotations(contd.)
Functioninsert
Createsanode,storestheinfointhenode,andcalls
thefunctioninsertIntoAVLtoinsertthenewnode
intheAVLtree
DataStructuresUsingC++2E
64
DeletionfromAVLTrees
Fourcases
Case1:Thenodetobedeletedisaleaf
Case2:Thenodetobedeletedhasnorightchild,
thatis,itsrightsubtreeisempty
Case3:Thenodetobedeletedhasnoleftchild,that
is,itsleftsubtreeisempty
Case4:Thenodetobedeletedhasaleftchildanda
rightchild
Cases13
EasiertohandlethanCase4
DataStructuresUsingC++2E
65
Analysis:AVLTrees
ConsiderallpossibleAVLtreesofheighth
LetThbeanAVLtreeofheighthsuchthatThhasthe
fewestnumberofnodes
LetThl denotetheleftsubtreeofThandThr denotethe
rightsubtreeofTh
Then:
where|Th|denotesthenumberofnodesinTh
DataStructuresUsingC++2E
66
Analysis:AVLTrees(contd.)
Suppose:
Thl isofheighth1andThr isofheighth2
Thl isanAVLtreeofheighth1suchthatThl hasthe
fewestnumberofnodesamongallAVLtreesofheight
h1
Thr isanAVLtreeofheighth2thathasthefewest
numberofnodesamongallAVLtreesofheighth2
Thl isoftheformTh1andThr isoftheformTh2
Hence:
DataStructuresUsingC++2E
67
DataStructuresUsingC++2E
68
BTrees
Leavesonthesamelevel
Nottoofarfromtheroot
mwaysearchtree
Treeinwhicheachnodehasatmostmchildren
Ifthetreeisnonempty,ithasthefollowingproperties:
DataStructuresUsingC++2E
69
BTrees(contd.)
Btreeoforderm
mwaysearchtree
Eitheremptyorhasthefollowingproperties:
Basicoperations
Searchthetree,insertanitem,deleteanitem,
traversethetree
DataStructuresUsingC++2E
70
BTrees(contd.)
FIGURE1124A5waysearchtree
FIGURE1125ABtreeoforder5
DataStructuresUsingC++2E
71
BTrees(contd.)
Constantexpressions
Maybepassedasparameterstotemplates
DefinitionofaBtreenode
ClassimplementingBtreeproperties
Seecodeonpages664665
ImplementsBtreebasicpropertiesasanADT
DataStructuresUsingC++2E
72
Search
Searchesbinarysearchtreeforagivenitem
Ifitemfoundinthebinarysearchtree:returnstrue
Otherwise:returnsfalse
Searchmuststartatrootnode
Morethanoneiteminanode(usually)
Mustsearcharraycontainingthedata
Twofunctionsrequired
Functionsearch
FunctionsearchNode
Searchesanodesequentially
DataStructuresUsingC++2E
73
TraversingaBTree
Btreetraversalmethods
Inorder,preorder,postorder
DataStructuresUsingC++2E
74
InsertionintoaBTree
Algorithm:searchtreetoseeifkeyalreadyexists
Ifkeyalreadyinthetree:outputanerrormessage
Ifkeynotinthetree:searchterminatesataleaf
Recordinsertedintotheleaf:ifroomexists
Ifleaffull:splitnodeintotwonodes
Mediankeymovedtoparentnode(mediandetermined
byconsideringallkeysinthenodeandnewkey)
Splittingcanpropagateupward(eventotheroot)
Causingtreetoincreaseinheight
DataStructuresUsingC++2E
75
InsertionintoaBTree(contd.)
FunctioninsertBTree
RecursivelyinsertsanitemintoaBtree
FunctioninsertusesfunctioninsertBTree
FunctioninsertNode
Insertsiteminthenode
FunctionsplitNode
Splitsnodeintotwonodes
Insertsnewitemintherelevantnode
Returnsmediankeyandpointertosecondhalfofthe
node
DataStructuresUsingC++2E
76
FIGURE1126IteminsertionintoaBtreeoforder5
FIGURE1127Insertionof73,54,98,and37
FIGURE1128Insertionof25,62,81,150,and79
DataStructuresUsingC++2E
77
FIGURE1129Insertionof200
DataStructuresUsingC++2E
78
DeletionfromaBTree
Casetoconsider
DataStructuresUsingC++2E
79
FIGURE1130ABtreeoforder5
FIGURE1131Deleting18from
aBtreeoforder5
FIGURE1132Btreebeforeandafterdeleting30
DataStructuresUsingC++2E
80
FIGURE1133Deletionof70fromtheBtree
DataStructuresUsingC++2E
81
Summary
Thischapterdiscussed
Binarytrees
Binarysearchtrees
Recursivetraversalalgorithms
Nonrecursivetraversalalgorithms
AVLtrees
Btrees
DataStructuresUsingC++2E
82