id
int64
0
25.6k
text
stringlengths
0
4.59k
25,000
as you single-step through the algorithmyou'll notice that the explanation we gave in the last section is slightly simplified the sequence for the -sort is not actually ( , , )( , , )( , )and ( , instead the first two elements of each group of three are sorted firstthen the first two elements of the second groupand so ...
25,001
is largethe number of items per pass is smalland items move long distances this is very efficient as grows smallerthe number of items per pass increasesbut the items are already closer togetherwhich is more efficient for the insertion sort it' the combination of these trends that makes the shellsort so effective notice...
25,002
int innerouterdouble tempint while( <nelems/ * /find initial value of while( > /decreasing huntil = /( / -sort the file for(outer=houter<nelemsouter++temp thearray[outer]inner outer/one subpass (eg while(inner - &thearray[inner- >thearray[innerthearray[inner- ]inner -hthearray[innertemp/end for ( - /decrease /end while...
25,003
/end main(/display sorted array /end class shellsortapp in main(we create an object of type arrayshcapable of holding itemsfill it with random datadisplay itshellsort itand display it again here' some sample outputa= = you can change maxsize to higher numbersbut don' go too high , items take fraction of minute to sort ...
25,004
no one so far has been able to analyze the shellsort' efficiency theoreticallyexcept in special cases based on experimentsthere are various estimateswhich range from / / ( down to ( table shows some of these estimated (valuescompared with the slower insertion sort and the faster quicksort the theoretical times correspo...
25,005
bars before partitioningand figure shows them again after partitioning figure twelve bars before partitioning figure twelve bars after partitioning the horizontal line represents the pivot value this is the value used to determine into which of the two groups an item is placed items with key value less than the pivot v...
25,006
originally in factpartitioning tends to reverse the order of some of the data in each group the partition java program how is the partitioning process carried outlet' look at some sample code listing shows the partition java programwhich includes the partitionit(method for partitioning an array listing the partition ja...
25,007
int leftptr left /right of first elem int rightptr right /left of pivot while(truewhile(leftptr right &/find bigger item thearray[++leftptrpivot/(nopwhile(rightptr left &/find smaller item thearray[--rightptrpivot/(nopif(leftptr >rightptr/if pointers crossbreak/partition done else /not crossedso swap(leftptrrightptr)/s...
25,008
int size arr size()/partition array int partdex arr partitionit( size- pivot)system out println("partition is at index partdex)arr display()/display sorted array /end main(/end class partitionapp the main(routine creates an arraypar object that holds items of type double the pivot value is fixed at the routine inserts ...
25,009
exits when an item smaller than pivot is found when both these loops exitboth leftptr and rightptr point to items that are in the wrong part of the arrayso these items are swapped after the swapthe two pointers continue onagain stopping at items that are in the wrong part of the array and swapping them all this activit...
25,010
while loop would be required to bump the pointers the nop version is the most efficient solution efficiency of the partition algorithm the partition algorithm runs in (ntime it' easy to see this when running the partition workshop appletthe two pointers start at opposite ends of the array and move toward each other at ...
25,011
public void recquicksort(int leftint rightif(right-left < /if size is return/it' already sorted else /size is or larger /partition range int partition partitionit(leftright)recquicksort(leftpartition- )/sort left side recquicksort(partition+ right)/sort right side as you can seethere are three basic steps partition the...
25,012
part of its arrayfrom left to partition- and once for the right partfrom partition+ to right note that the data item at the index partition is not included in either of the recursive calls why notdoesn' it need to be sortedthe explanation lies in how the pivot value is chosen choosing pivot value what pivot value shoul...
25,013
once it' swapped into the partition' locafiguretionthe pivot is in its final resting place all subsequent activity will take place on one side of it or on the otherbut the pivot itself won' be moved (or indeed even accessedagain to incorporate the pivot selection process into our recquicksort(methodlet' make it an over...
25,014
private double[thearrayprivate int nelems/ref to array thearray /number of data items //public arrayins(int max/constructor thearray new double[max]/create the array nelems /no items yet //public void insert(double value/put element into array thearray[nelemsvalue/insert it nelems++/increment size //public void display...
25,015
int leftptr left- /left (after ++int rightptr right/right- (after --while(true/find bigger item while(thearray[++leftptrpivot/(nop/find smaller item while(rightptr &thearray[--rightptrpivot/(nopif(leftptr >rightptrbreakelse swap(leftptrrightptr)/end while(trueswap(leftptrright)return leftptr/end partitionit(/if pointer...
25,016
/end main(/display them again /end class quicksort app the main(routine creates an object of type arrayinsinserts random data items of type double in itdisplays itsorts it with the quicksort(methodand displays the results here' some typical outputa= = an interesting aspect of the code in the partitionit(method is that ...
25,017
by partitioning it into two partsand so oncreating smaller and smaller subarrays when the sorting process is completeeach dotted line provides visual record of one of the sorted subarrays the horizontal range of the line shows which bars were part of the subarrayand its vertical position is the pivot value (the height ...
25,018
sometimesas in steps and the pivot ends up in its original position on the right side of the array being sorted in this situationthere is only one subarray remaining to be sortedthat to the left of the pivot there is no second subarray to its right the different steps in figure occur at different levels of recursionas ...
25,019
enough space for sets of arguments and return valuesone for each recursion level this isas we'll see latersomewhat greater than the logarithm to the base of the number of itemslog the size of the machine stack is determined by your particular system sorting very large numbers of data items using recursive procedures ma...
25,020
items being sorted that ishalf the items should be larger than the pivotand half smaller this would result in the array being partitioned into two subarrays of equal size two equal subarrays is the optimum situation for the quicksort algorithm if it has to sort one large and one small arrayit' less efficient because th...
25,021
the itemsand yet it successfully avoids picking the largest or smallest item in cases where the data is already sorted or inversely sorted there are probably some pathological arrangements of data where the median-of-three scheme works poorlybut normally it' fast and effective technique for finding the pivot besides pi...
25,022
the partitionit(method listing the quicksort java program /quicksort java /demonstrates quick sort with median-of-three partitioning /to run this programc>java quicksort app ///////////////////////////////////////////////////////////////class arrayins private double[thearray/ref to array thearray private int nelems/num...
25,023
/quicksort if large double median medianof (leftright)int partition partitionit(leftrightmedian)recquicksort(leftpartition- )recquicksort(partition+ right)/end recquicksort(//public double medianof (int leftint rightint center (left+right)/ /order left center ifthearray[leftthearray[centerswap(leftcenter)/order left ri...
25,024
swap(leftptrrightptr)/end while(trueswap(leftptrright- )/swap elements return leftptr/end partitionit(/return pivot location /restore pivot //public void manualsort(int leftint rightint size right-left+ if(size < return/no sort necessary if(size = / -sort left and right ifthearray[leftthearray[rightswap(leftright)retur...
25,025
/end main(/display them again /end class quicksort app this program uses another new methodmanualsort()to sort subarrays of or fewer elements it returns immediately if the subarray is cell (or less)swaps the cells if necessary if the range is and sorts cells if the range is the recquicksort(routine can' be used to sort...
25,026
private double[thearrayprivate int nelems/ref to array thearray /number of data items //public arrayins(int max/constructor thearray new double[max]/create the array nelems /no items yet //public void insert(double value/put element into array thearray[nelemsvalue/insert it nelems++/increment size //public void display...
25,027
int center (left+right)/ /order left center ifthearray[leftthearray[centerswap(leftcenter)/order left right ifthearray[leftthearray[rightswap(leftright)/order center right ifthearray[centerthearray[rightswap(centerright)swap(centerright- )return thearray[right- ]/end medianof (/put pivot on right /return median value /...
25,028
int inoutout right /sorted on left of for(out=left+ out<=rightout++double temp thearray[out]/remove marked item in out/start shifts at out /until one is smallerwhile(in>left &thearray[in- >tempthearray[inthearray[in- ]/shift item to --inthearray[intemp/end for /end insertionsort(/go left one position /insert marked ite...
25,029
smaller than the cutoff when quicksort is finishedthe array will be almost sorted you then apply the insertion sort to the entire array the insertion sort is supposed to operate efficiently on almost-sorted arraysand this approach is recommended by some expertsbut on our installation it runs very slowly the insertion s...
25,030
in this figure solid horizontal lines represent the dotted horizontal lines in the quicksort appletsand captions like / cells long indicate averagenot actualline lengths the circled numbers on the left show the order in which the lines are created each series of lines (the eight / linesfor examplecorresponds to level o...
25,031
log *log comparisons( + )*log swapsfewer than / *log the log quantity used in table is actually true only in the best-case scenariowhere each subarray is partitioned exactly in half for random data the figure is slightly greater neverthelessthe quicksort and quicksort workshop applets approximate these results for and ...
25,032
in the partitioning algorithmtwo array indiceseach in its own while loopstart at opposite ends of the array and step toward each otherlooking for items that need to be swapped when an index finds an item that needs to be swappedits while loop exits when both while loops exitthe items are swapped when both while loops e...
25,033
the insertion sort can also be applied to the entire arrayafter it has been sorted down to cutoff point by quicksort binary trees overview in this we switch from algorithmsthe focus of the last on sortingto data structures binary trees are one of the fundamental data storage structures used in programming they provide ...
25,034
trees to the rescue it would be nice if there were data structure with the quick insertion and deletion of linked listand also the quick searching of an ordered array trees provide both these characteristicsand are also one of the most interesting data structures what is treewe'll be mostly interested in particular kin...
25,035
why use binary treeswhy might you want to use treeusuallybecause it combines the advantages of two other structuresan ordered array and linked list you can search tree quicklyas you can an ordered arrayand you can also insert and delete items quicklyas you can with linked list let' explore these topics bit before delvi...
25,036
of tree (or in our workshop appletthe nodes are represented as circlesand the edges as lines connecting the circles trees have been studied extensively as abstract mathematical entitiesso there' large amount of theoretical knowledge about them tree is actually an instance of more general category called graphbut we don...
25,037
hierarchical file structure differs in significant way from the trees we'll be discussing here in the file structuresubdirectories contain no dataonly references to other subdirectories or to files only files contain data in treeevery node contains data ( personnel recordcar-part specificationsor whateverin addition to...
25,038
figure an unbalanced tree (with an unbalanced subtreetrees become unbalanced because of the order in which the data items are inserted if these key values are inserted randomlythe tree will be more or less balanced howeverif an ascending sequence (like and so onor descending sequence is generatedall the values will be ...
25,039
objects being stored (employees in an employee databasefor exampleand also references to each of the node' two children here' how that looksclass node int idatafloat fdatanode leftchildnode rightchild/data used as key value /other data /this node' left child /this node' right child public void displaynode(/(see listing...
25,040
private node root/the only data field in tree public void find(int keypublic void insert(int iddouble ddpublic void delete(int id/various other methods /end class tree the treeapp class finallywe need way to perform operations on the tree here' how you might write class with main(routine to create treeinsert three node...
25,041
information they could be person objectswith an employee number as the key and also perhaps nameaddresstelephone numbersalaryand other fields or they could represent car partswith part number as the key value and fields for quantity on handpriceand so on howeverthe only characteristics of each node that we can see in t...
25,042
node current root/find node with given key /(assumes non-empty tree/start at root while(current idata !key/while no matchif(key current idata/go leftcurrent current leftchildelse current current rightchild/or go rightif(current =null/if no childreturn null/didn' find it return current/found it this routine uses variabl...
25,043
to insert new node with the workshop appletpress the ins button you'll be asked to type the key value of the node to be inserted let' assume we're going to insert new node with the value type this into the text field the first step for the program in inserting node is to find where it should be inserted figure shows ho...
25,044
node newnode new node()/make new node newnode idata id/insert data newnode ddata ddif(root==null/no node in root root newnodeelse /root occupied node current root/start at root node parentwhile(true/(exits internallyparent currentif(id current idata/go leftcurrent current leftchildif(current =null/if end of the line/in...
25,045
the algorithm is interesting (it' also simpler than deletionthe discussion of which we want to defer as long as possible there are three simple ways to traverse tree they're called preorderinorderand postorder the order most commonly used for binary search trees is inorderso let' look at that firstand then return brief...
25,046
let' look at simple example to get an idea of how this recursive traversal routine works imagine traversing tree with only three nodesa root (awith left child (band right child ( )as shown in figure figure inorder(method applied to -node tree we start by calling inorder(with the root as an argument this incarnation of ...
25,047
here' what happens when you use the tree workshop applet to traverse inorder the tree shown in figure this is slightly more complex than the -node tree seen previously the red arrow starts at the root table shows the sequence of node keys and the corresponding messages the key sequence is displayed at the bottom of the...
25,048
will visit this node will check right child will check left child will visit this node will check for right child will go to root of previous subtree done traversal it may not be obviousbut for each nodethe routine traverses the node' left subtreevisits the nodeand traverses the right subtree for examplefor node this h...
25,049
what' all this got to do with preorder and postorder traversalslet' see what' involved for these other traversals the same three steps are used as for inorderbut in different sequence here' the sequence for preorder(method visit the node call itself to traverse the node' left subtree call itself to traverse the node' r...
25,050
shown in figure figure minimum value of tree here' some code that returns the node with the minimum key valuepublic node minimum(/returns node with minimum key value node currentlastcurrent root/start at root while(current !null/until the bottomlast current/remember node current current leftchild/go to left child retur...
25,051
the third quite complicated case the node to be deleted has no children to delete leaf nodeyou simply change the appropriate child field in the node' parent to point to null instead of to the node the node will still existbut it will no longer be part of the tree this is shown in figure figure deleting node with no chi...
25,052
isleftchild falsecurrent current rightchildif(current =null/end of the linereturn false/didn' find it /end while /found node to delete /continues once we've found the nodewe check first to see whether it has no children when this is true we check the special case of the rootif that' the node to be deletedwe simply set ...
25,053
let' assume we're using the workshop on the tree in figure and deleting node which has left child but no right child press del and enter when prompted keep pressing del until the arrow rests on node has only one child it doesn' matter whether has children of its ownin this caseit has one pressing del once more causes t...
25,054
now the fun begins if the deleted node has two childrenyou can' just replace it with one of these childrenat least if the child has its own children why notexamine figure and imagine deleting node and replacing it with its right subtreewhose root is which left child would havethe deleted node' left child or the new nod...
25,055
than the node then it goes to this right child' left child (if it has one)and to this left child' left childand so onfollowing down the path of left children the last left child in this path is the successor of the original nodeas shown in figure figure finding the successor why does this workwhat we're really looking ...
25,056
will be replaced by java code to find the successor here' some code for method getsuccessor()which returns the successor of the node specified as its delnode argument (this routine assumes that delnode does indeed have right childbut we know this is true because we've already determined that the node to be deleted has ...
25,057
deleted node was this requires only two steps unplug current from the rightchild field of its parent (or leftchild field if appropriate)and set this field to point to successor unplug current' left child from currentand plug it into the leftchild field of successor here are the code statements that carry out these step...
25,058
these two steps step if the node to be deletedcurrentis the rootit has no parent so we merely set the root to the successor otherwisethe node to be deleted can be either left or right child (the figure shows it as right child)so we set the appropriate field in its parent to point to successor once delete(returns and cu...
25,059
here' the code for these four steps successorparent leftchild successor rightchild successor rightchild delnode rightchild parent rightchild successor successor leftchild current leftchild(step could also refer to the left child of its parent the numbers in figure show the connections affected by the four steps step in...
25,060
node doesn' change the structure of the tree of courseit also means that memory can fill up with "deletednodes this approach is bit of cop-outbut it may be appropriate where there won' be many deletions in tree (if ex-employees remain in the personnel file foreverfor example the efficiency of binary trees as you've see...
25,061
, , , this situation is very much like the ordered array discussed in in that casethe number of comparisons for binary search was approximately equal to the base- logarithm of the number of cells in the array hereif we call the number of nodes in the first column nand the number of levels in the second column lthen we ...
25,062
index is the rootthe node at index is the root' left childand so onprogressing from left to right along each level of the tree this is shown in figure figure tree represented by an array every position in the treewhether it represents an existing node or notcorresponds to cell in the array adding node at given position...
25,063
inserted as the right child of its twin the problem is that the find(routine will find only the first of two (or moreduplicate nodes the find(routine could be modified to check an additional data itemto distinguish data items even when the keys were the samebut this would be (at least somewhattime-consuming one option ...
25,064
an unbalanced tree is one whose root has many more left descendents than right descendantsor vice versa searching for node involves comparing the value to be found with the key value of nodeand going to that node' left child if the key search value is lessor to the node' right child if the search value is greater inser...
25,065
this and examine onethe treein tables and external storage howeverthe red-black tree is in most cases the most efficient balanced treeat least when data is stored in memory as opposed to external files our approach to the discussion we'll explain insertion into red-black trees little differently than we have explained ...
25,066
than the previously inserted oneevery node is right childso all the nodes are on one side of the root the tree is maximally unbalanced if you inserted items in descending orderevery node would be the left child of its parentthe tree would be unbalanced on the other side degenerates to (nwhen there are no branchesthe tr...
25,067
ignore that for the momentas an item is being insertedthe insertion routine checks that certain characteristics of the tree are not violated if they areit takes corrective actionrestructuring the tree as necessary by maintaining these characteristicsthe tree is kept balanced red-black tree characteristics what are thes...
25,068
balanced treebut they dosome very clever people invented them copy them onto sticky noteand keep it on your computer you'll need to refer to them often in the course of this you can see how the rules work by using the rbtree workshop applet we'll do some experiments with the applet in momentbut first you should underst...
25,069
there are quite few buttons in the rbtree applet we'll briefly review what they doalthough at this point some of the descriptions may be bit puzzling soon we'll do some experimenting with these buttons clicking on node the red arrow points to the currently selected node it' this node whose color is changed or which is ...
25,070
if there is black parent with two red childrenand you place the red arrow on the parent by clicking on the node with the mousethen when you press the flip button the parent will become red and the children will become black that isthe colors are flipped between the parent and children you'll learn later why this is des...
25,071
insert new node with value smaller than the rootsay by typing the number into the number box and pressing the ins button this doesn' cause any rule violationsso the message continues to say tree is red-black correct insert second node that' larger than the rootsay the tree is still red-black correct it' also balancedth...
25,072
insteadrotate the other way position the red arrow on which is now the root (the arrow should already point to after the previous rotationclick the rol button to rotate left the nodes will return to the position of figure experiment start with the position of figure with nodes and inserted in addition to in the root po...
25,073
how can we fix things so rule isn' violatedan obvious approach is to change one of the offending nodes to black let' try changing the child node position the red arrow on it and press the / button the node becomes black the good news is we fixed the problem of both parent and child being red the bad news is that now th...
25,074
the term black height is used to describe the number of black nodes from between given node and the root in figure the black height of is of is still of is and so on rotations to balance treeit' necessary to physically rearrange the nodes if all the nodes are on the left of the rootfor exampleyou need to move some of t...
25,075
the rotation we described in experiment was performed with the root as the top nodebut of course any node can be the top node in rotationprovided it has the appropriate child mind the children you must be sure thatif you're doing right rotationthe top node has left child otherwise there' nothing to rotate into the top ...
25,076
whenever you can' complete an insertion because of the can' insertneeds color flip message the resulting arrangement is shown in figure figure subtree motion during rotation position the arrow on the root now press ror wow(or is it wow? lot of nodes have changed position the result is shown in figure here' what happens...
25,077
they can follow few simple rules that' what the red-black scheme providesin the form of color coding and the four color rules inserting new node now you have enough background to see how red-black tree' insertion routine uses rotations and the color rules to maintain the tree' balance preview we're going to briefly pre...
25,078
node should be insertedgoing left or right at each node depending on the relative size of the node' key and the search key howeverin red-black treegetting to the insertion point is complicated by color flips and rotations we introduced color flips in experiment now we'll look at them in more detail imagine the insertio...
25,079
more nodes black and none red thusrule isn' violated alsobecause the root and one or the other of its two children are in every paththe black height of every path is increased the same amountthat isby thusrule isn' violated either finallyjust insert it once you've worked your way down to the appropriate place in the tr...
25,080
is black is red and is an outside grandchild of is red and is an inside grandchild of it might seem that this list doesn' cover all the possibilities we'll return to this question after we've explored these three possibility is black if is blackwe get free ride the node we've just inserted is always red if its parent i...
25,081
in this situationwe can take three steps to restore red-black correctness and thereby balance the tree here are the steps switch the color of ' grandparent ( in this example switch the color of ' parent ( rotate with ' grandparent ( at the topin the direction that raises ( this is right rotation in the example as you'v...
25,082
note that the node is an inside grandchild it and its parent are both redso again you see the error message errorparent and child both red fixing this arrangement is slightly more complicated if we try to rotate right with the grandparent node ( at the topas we did in possibility the inside grandchild ( moves across ra...
25,083
and the null child howeverwe know is redso we conclude that it' impossible for to have sibling unless is red another possibility is that gthe grandparent of phas child uthe sibling of and the uncle of againthis would complicate any necessary rotations howeverif is blackthere' no need for rotations when inserting xas we...
25,084
figure outside grandchild on the way down the procedure used to fix this is similar to the post-insertion operation with an outside grandchilddescribed earlier we must perform two color switches and one rotation so we can discuss this in the same terms we did when inserting nodewe'll call the node at the top of the tri...
25,085
but when you perform the flip and are both redand you get the errorparent and child are both red message don' press ins again in this situation is is and is as shown in figure figure inside grandchild on the way down to cure the red-red conflictyou must do the same two color changes and two rotations as in possibility ...
25,086
like ordinary binary search treesa red-black tree allows for searchinginsertionand deletion in (log ntime search times should be almost the same in the red-black tree as in the ordinary tree because the red-black characteristics of the tree aren' used during searches the only penalty is that the storage required for ea...
25,087
different from the height of its right subtree following insertionthe root of the lowest subtree into which the new node was inserted is checked if the height of its children differs by more than single or double rotation is performed to equalize their heights the algorithm then moves up and checks the node aboveequali...
25,088
list trees and external storage hash tables heaps trees and external storage overview in binary treeeach node has one data item and can have up to two children if we allow more data items and children per nodethe result is multiway tree treesto which we devote the first part of this are multiway trees that can have up ...
25,089
the and in the name tree refer to how many links to child nodes can potentially be contained in given node for non-leaf nodesthree arrangements are possiblea node with one data item always has two children node with two data items always has three children node with three data items always has four children in shorta n...
25,090
to as shown in figure the data items in node are arranged in ascending key orderby convention from left to right (lower to higher numbersan important aspect of any tree' structure is the relationship of its links to the key values of its data items in binary treeall children with keys less than the node' key are in sub...
25,091
changed to maintain the structure of the treewhich stipulates that there should be one more child than data items in node insertion into tree is sometimes quite easy and sometimes rather complicated in any case the process begins by searching for the appropriate leaf node if no full nodes are encountered during the sea...
25,092
notice that the effect of the node split is to move data up and to the right it' this rearrangement that keeps the tree balanced here the insertion required only one node splitbut more than one full node may be encountered on the path to the insertion point when this is the case there will be multiple splits splitting ...
25,093
another way to describe splitting the root is to say that -node is split into three nodes following node splitthe search for the insertion point continues down the tree in figure the data item with key of is inserted into the appropriate leaf figure insertions into tree splitting on the way down notice thatbecause all ...
25,094
encounters it figure shows series of insertions into an empty tree there are four node splitstwo of the root and two of leaves the tree workshop applet operating the tree workshop applet provides quick way to see how trees work when you start the applet you'll see screen similar to figure figure the tree workshop apple...
25,095
in the tree the algorithm first searches for the appropriate node if it encounters full node along the wayit splits it before continuing on experiment with the insertion process watch what happens when there are no full nodes on the path to the insertion point this is straightforward process then try inserting at the e...
25,096
the blue triangles to them if the children aren' currently visiblethere are no linesbut the blue triangles indicate that the node nevertheless has children if you click on the parent nodeits children and the lines to them will appear by clicking the appropriate nodes you can navigate all over the tree for convenienceal...
25,097
to see if you're right as the tree gets larger you'll need to move around it to see all the nodes click on node to see its children (and their childrenand so onif you lose track of where you areuse the zoom key to see the big picture how many data items can you insert in the treethere' limit because only four levels ar...
25,098
with particular keyinsert new item into the nodemoving existing items if necessaryand remove an itemagain moving existing items if necessary don' confuse these methods with the find(and insert(routines in the tree classwhich we'll look at next display routine displays node with slashes separating the data itemslike ///...
25,099
in the tree app classthe main(routine inserts few data items into the tree it then presents character-based interface for the userwho can enter to see the treei to insert new data itemand to find an existing item here' some sample interactionenter first letter of showinsertor finds level= child= / level= child= / / lev...