id
int64
0
25.6k
text
stringlengths
0
4.59k
25,400
ted fred adam mary eva fig an example of recursive data structure the important role of the variant facility becomes clearit is the only means by which recursive data structure can be boundedand it is therefore an inevitable companion of every recursive definition the analogy between program and data structuring concepts is particularly pronounced in this case conditional (or selectivestatement must necessarily be part of every recursive procedure in order that execution of the procedure can terminate in practicedynamic structures involve references or pointers to its elementsand the concept of an alternative (to terminate the recursionis implied in the pointeras shown in the next paragraph pointers the characteristic property of recursive structures which clearly distinguishes them from the fundamental structures (arraysrecordssetsis their ability to vary in size henceit is impossible to assign fixed amount of storage to recursively defined structureand as consequence compiler cannot associate specific addresses to the components of such variables the technique most commonly used to master this problem involves dynamic allocation of storagei allocation of store to individual components at the time when they come into existence during program executioninstead of at translation time the compiler then allocates fixed amount of storage to hold the address of the dynamically allocated component instead of the component itself for instancethe pedigree illustrated in fig would be represented by individual -quite possibly noncontiguous -recordsone for each person these persons are then linked by their addresses assigned to the respective father and mother fields graphicallythis situation is best expressed by the use of arrows or pointers (fig
25,401
ted fred adam mary eva fig data structure linked by pointers it must be emphasized that the use of pointers to implement recursive structures is merely technique the programmer need not be aware of their existence storage may be allocated automatically the first time new component is referenced howeverif the technique of using references or pointers is made explicitmore general data structures can be constructed than those definable by purely recursive data definiton in particularit is then possible to define potentially infinite or circular (graphstructures and to dictate that certain structures are shared it has therefore become common in advanced programming languages to make possible the explicit manipulation of references to data in additon to the data themeselves this implies that clear notational distinction must exist between data and references to data and that consequently data types must be introduced whose values are pointers (referencesto other data the notation we use for this purpose is the followingtype pointer to this type declaration expresses that values of type are pointers to data of type it is fundamentally important that the type of elements pointed to is evident from the declaration of we say that is bound to this binding distinguishes pointers in higher-level languages from addresses in assembly codesand it is most important facility to increase security in programming through redundancy of the underlying notation ppointer to ^ fig dynamic allocation of variable pvalues of pointer types are generated whenever data item is dynamically allocated we will adhere to the convention that such an occasion be explicitly mentioned at all times this is in contrast to the situation in which the first time that an item is mentioned it is automatically allocated for this purposewe introduce procedure new given pointer variable of type the statement new(peffectively allocates variable of type and assigns the pointer referencing this new variable to (see fig the pointer value itself can now be referred to as ( as the value of the pointer variable pin contrastthe variable which is referenced by is denoted by pthe referenced structures are typically records if the referenced record hasfor examplea field xthen it is denoted by px because it is clear that not the
25,402
pointer has any fieldsbut only the referenced record ^we allow the abbreviated notation in place of px it was mentioned above that variant component is essential in every recursive type to ensure finite instances the example of the family predigree is of pattern that exhibits most frequently occurring constellationnamelythe case in which one of the two cases features no further components this is expressed by the following declaration schematype record if nonterminalboolean then (tend end (tdenotes sequence of field definitions which includes one or more fields of type thereby ensuring recursivity all structures of type patterned after this schema exhibit tree (or liststructure similar to that shown in fig its peculiar property is that it contains pointers to data components with tag field onlyi without further relevant information the implementation technique using pointers suggests an easy way of saving storage space by letting the tag information be included in the pointer value itself the common solution is to extend the range of values of all pointer types by single value that is pointing to no element at all we denote this value by the special symbol niland we postulate that the value nil can be assumed by all pointer typed variables this extension of the range of pointer values explains why finite structures may be generated without the explicit presence of variants (conditionsin their (recursivedeclaration the new formulations of the explicitly recursive data types declared above are reformulated using pointers as shown below note that the field known has vanishedsince ~ known is now expressed as nil the renaming of the type ped to person reflects the difference in the viewpoint brought about by the introduction of explicit pointer values instead of first considering the given structure in its entirety and then investigating its substructure and its componentsattention is focused on the components in the first placeand their interrelationship (represented by pointersis not evident from any fixed declaration type term pointer to termdescriptortype exp pointer to expdescriptortype expdescriptor record opintegeropd opd term endtype termdescriptor record idarray of char end type person pointer to record namearray of charfathermotherperson end note the type person points to records of an anonymous type (persondescriptorthe data structure representing the pedigree shown in figs and is again shown in fig in which pointers to unknown persons are denoted by nil the resulting improvement in storage economy is obvious again referring to fig assume that fred and mary are siblingsi have the same father and mother this situation is easily expressed by replacing the two nil values in the respective fields of the two records an implementation that hides the concept of pointers or uses different technique of storage handling would force the programmer to represent the ancestor records of adam and evatwice although in accessing their data for inspection it does not matter whether the two fathers (and the two mothersare duplicated or represented by single recordthe difference is essential when selective updating is permitted treating pointers as explicit data items instead of as hidden implementation aids allows the programmer to express clearly where storage sharing is intended and where it is not
25,403
adam fred ted nil nil nil mary nil eva nil nil fig data structure with nil pointers further consequence of the explicitness of pointers is that it is possible to define and manipulate cyclic data structures this additional flexibility yieldsof coursenot only increased power but also requires increased care by the programmerbecause the manipulation of cyclic data structures may easily lead to nonterminating processes this phenomenon of power and flexibility being intimately coupled with the danger of misuse is well known in programmingand it particularly recalls the goto statement indeedif the analogy between program structures and data structures is to be extendedthe purely recursive data structure could well be placed at the level corresponding with the procedurewhereas the introduction of pointers is comparable to the use of goto statements foras the goto statement allows the construction of any kind of program pattern (including loops)so do pointers allow for the composition of any kind of data structure (including ringsthe parallel development of corresponding program and data structures is shown in condensed form in table construction pattern program statement data type atomic element assignment scalar type enumeration compound statement record type repetition (known factorfor statement array type choice conditional statement type union (variant recordrepetition while or repeat statement sequence type recursion procedure statement recursive data type general graph go to statement structure linked by pointers table correspondences of program and data structures in chap we have seen that iteration is special case of recursionand that call of recursive procedure defined according to the following schemaprocedure pbegin if then end end where is statement not involving pis equivalent to and replaceable by the iterative statement while do end the analogies outlined in table reveal that similar relationship holds between recursive data types and the sequence in facta recursive type defined according to the schema type record
25,404
if bboolean then tt end end where is type not involving is equivalent and replaceable by sequence of the remainder of this is devoted to the generation and manipulation of data structures whose components are linked by explicit pointers structures with specific simple patterns are emphasized in particularrecipes for handling more complex structures may be derived from those for manipulating basic formations these are the linear list or chained sequence -the simplest case -and trees our preoccupation with these building blocks of data structuring does not imply that more involved structures do not occur in practice in factthe following story appeared in zurich newspaper in july and is proof that irregularity may even occur in cases which usually serve as examples for regular structuressuch as (familytrees the story tells of man who laments the misery of his life in the following wordsi married widow who had grown-up daughter my fatherwho visited us quite oftenfell in love with my step-daughter and married her hencemy father became my son-in-lawand my stepdaughter became my mother some months latermy wife gave birth to sonwho became the brother-in-law of my father as well as my uncle the wife of my fatherthat is my stepdaughteralso had son therebyi got brother and at the same time grandson my wife is my grandmothersince she is my mother' mother hencei am my wife' husband and at the same time her stepgrandsonin other wordsi am my own grandfather linear lists basic operations the simplest way to interrelate or link set of elements is to line them up in single list or queue forin this caseonly single link is needed for each element to refer to its successor assume that types node and nodedesc are defined as shown below every variable of type nodedesc consists of three componentsnamelyan identifying keythe pointer to its successorand possibly further associated information for our further discussiononly key and next will be relevant type node pointer to nodedesctype nodedesc record keyintegernextnodedataendvar pqnode (*pointer variables* list of nodeswith pointer to its first component being assigned to variable pis illustrated in fig probably the simplest operation to be performed with list as shown in fig is the insertion of an element at its head firstan element of type nodedesc is allocatedits reference (pointerbeing assigned to an auxiliary pointer variablesay thereaftera simple reassignment of pointers completes the operation note that the order of these three statements is essential new( ) next :pp : nil fig example of linked list the operation of inserting an element at the head of list immediately suggests how such list can be
25,405
generatedstarting with the empty lista heading element is added repeatedly the process of list generation is expressed in by the following piece of programhere the number of elements to be linked is :nil(*start with empty list*while do new( ) next :pp :qq key :ndec(nend this is the simplest way of forming list howeverthe resulting order of elements is the inverse of the order of their insertion in some applications this is undesirableand consequentlynew elements must be appended at the end instead of the head of the list although the end can easily be determined by scan of the listthis naive approach involves an effort that may as well be saved by using second pointersay qalways designating the last element this method isfor exampleapplied in the program crossref (sec )which generates cross-references to given text its disadvantage is that the first element inserted has to be treated differently from all later ones the explicit availability of pointers makes certain operations very simple which are otherwise cumbersomeamong the elementary list operations are those of inserting and deleting elements (selective updating of list)andof coursethe traversal of list we first investigate list insertion assume that an element designated by pointer (variableq is to be inserted in list after the element designated by the pointer the necessary pointer assignments are expressed as followsand their effect is visualized by fig next : nextp next : fig insertion after pif insertion before instead of after the designated element pis desiredthe unidirectional link chain seems to cause problembecause it does not provide any kind of path to an element' predecessors howevera simple trick solves our dilemma it is illustrated in fig assume that the key of the new element is new( ) : ^ key :kp next :
25,406
fig insertion before pthe trick evidently consists of actually inserting new component after pand thereafter interchanging the values of the new element and pnextwe consider the process of list deletion deleting the successor of pis straightforward this is shown here in combination with the reinsertion of the deleted element at the head of another list (designated by qfigure illustrates the situation and shows that it constitutes cyclic exchange of three pointers : nextp next : nextr next :qq : fig deletion and re-insertion the removal of designated element itself (instead of its successoris more difficultbecause we encounter the same problem as with insertiontracing backward to the denoted element' predecessor is impossible but deleting the successor after moving its value forward is relatively obvious and simple solution it can be applied whenever phas successori is not the last element on the list howeverit must be assured that there exist no other variables pointing to the now deleted element we now turn to the fundamental operation of list traversal let us assume that an operation (xhas to be performed for every element of the list whose first element is pthis task is expressible as followswhile list designated by is not empty do perform operation pproceed to the successor end in detailthis operation is descibed by the following statementwhile nil do ( ) : next
25,407
end it follows from the definitions of the while statement and of the linking structure that is applied to all elements of the list and to no other ones very frequent operation performed is list searching for an element with given key unlike for arraysthe search must here be purely sequential the search terminates either if an element is found or if the end of the list is reached this is reflected by logical conjunction consisting of two terms againwe assume that the head of the list is designated by pointer while ( nil( key xdo : next end nil implies that pdoes not existand hence that the expression key is undefined the order of the two terms is therefore essential ordered lists and reorganizing lists the given linear list search strongly resembles the search routines for scanning an array or sequence in facta sequence is precisely linear list for which the technique of linkage to the successor is left unspecified or implicit since the primitive sequence operators do not allow insertion of new elements (except at the endor deletion (except removal of all elements)the choice of representation is left wide open to the implementorand he may well use sequential allocationleaving successive components in contiguous storage areas linear lists with explicit pointers provide more flexibilityand therefore they should be used whenever this additional flexibility is needed to exemplifywe will now consider problem that will occur throughout this in order to illustate alternative solutions and techniques it is the problem of reading textcollecting all its wordsand counting the frequency of their occurrence it is called the construction of concordance or the generation of cross-reference list an obvious solution is to construct list of words found in the text the list is scanned for each word if the word is foundits frequency count is incrementedotherwise the word is added to the list we shall simply call this process searchalthough it may actually also include an insertion in order to be able to concentrate our attention on the essential part of list handlingwe assume that the words have already been extracted from the text under investigationhave been encoded as integersand are available in the from of an input sequence the formulation of the procedure called search follows in straightforward manner the variable root refers to the head of the list in which new words are inserted accordingly the complete algorithm is listed belowit includes routine for tabulating the constructed cross-reference list the tabulation process is an example in which an action is executed once for each element of the list type word pointer to (adens _list *record keycountintegernextword endprocedure search (xintegervar rootword)var wwordbegin :rootwhile ( nil( key xdo : next end(( nilor ( key *if nil then (*novyi element* :rootnew(root)root key :xroot count : root next : else inc( count
25,408
end end searchprocedure printlist (wword)begin (*uses global writer *while nil do texts writeint(ww key )texts writeint(ww count )texts writeln( ) : next end end printlistthe linear scan algorithm resembles the search procedure for arraysand reminds us of simple technique used to simplify the loop termination conditionthe use of sentinel sentinel may as well be used in list searchit is represented by dummy element at the end of the list the new procedure is listed below we must assume that global variable sentinel is added and that the initialization of root :nil is replaced by the statements new(sentinel)root :sentinel which generate the element to be used as sentinel procedure search (xintegervar rootword)(adens _list *var wwordbegin :rootsentinel key :xwhile key do : next endif sentinel then (*new entry* :rootnew(root)root key :xroot count : root next : else inc( countend end search obviouslythe power and flexibility of the linked list are ill used in this exampleand the linear scan of the entire list can only be accepted in cases in which the number of elements is limited an easy improvementhoweveris readily at handthe ordered list search if the list is ordered (say by increasing keys)then the search may be terminated at the latest upon encountering the first key that is larger than the new one ordering of the list is achieved by inserting new elements at the appropriate place instead of at the head in effectordering is practically obtained free of charge this is because of the ease by which insertion in linked list is achievedi by making full use of its flexibility it is possibility not provided by the array and sequence structures (notehoweverthat even in ordered lists no equivalent to the binary search of arrays is availableordered list search is typical example of the situationwhere an element must be inserted ahead of given itemhere in front of the first one whose key is too large the technique shown herehoweverdiffers from the one used shown earlier instead of copying valuestwo pointers are carried along in the list traversalw lags one step behind and thus identifies the proper insertion place when has found too large key the general insertion step is shown in fig the pointer to the new element ( is to be assigned to nextexcept when the list is still empty for reasons of simplicity and effectivenesswe prefer to avoid this distinction by using conditional statement the only way to avoid this is to introduce dummy element at the list head the initializing statement root :nil is accordingly replaced by new(root)root next :nil
25,409
nil fig insertion in ordered list referring to fig we determine the condition under which the scan continues to proceed to the next elementit consists of two factorsnamely( nil( key xthe resulting search procedure isprocedure search (xintegervar rootword)(adens _list *var wordbegin (* nil* :rootw : nextwhile ( nil( key xdo : : next end(( nilor ( key > *if ( nilor ( key xthen (*new entry*new( ) next : key :xw count : next : else inc( countend end search in order to speed up the searchthe continuation condition of the while statement can once again be simplified by using sentinel this requires the initial presence of dummy header as well as sentinel at the tail it is now high time to ask what gain can be expected from ordered list search remembering that the additional complexity incurred is smallone should not expect an overwhelming improvement assume that all words in the text occur with equal frequency in this case the gain through lexicographical ordering is indeed also nilonce all words are listedbecause the position of word does not matter if only the total of all access steps is significant and if all words have the same frequency of occurrence howevera gain is obtained whenever new word is to be inserted instead of first scanning the entire liston the average only half the list is scanned henceordered list insertion pays off only if concordance is to be generated with many distinct words compared to their frequency of occurrence the preceding examples are therefore suitable primarily as programming exercises rather than for practical applications the arrangement of data in linked list is recommended when the number of elements is relatively small
25,410
( )variesandmoreoverwhen no information is given about their frequencies of access typical example is the symbol table in compilers of programming languages each declaration causes the addition of new symboland upon exit from its scope of validityit is deleted from the list the use of simple linked lists is appropriate for applications with relatively short programs even in this case considerable improvement in access method can be achieved by very simple technique which is mentioned here again primarily because it constitutes pretty example for demonstrating the flexibilities of the linked list structure characteristic property of programs is that occurrences of the same identifier are very often clusteredthat isone occurrence is often followed by one or more reoccurrences of the same word this information is an invitation to reorganize the list after each access by moving the word that was found to the top of the listthereby minimizing the length of the search path the next time it is sought this method of access is called list search with reorderingor -somewhat pompously -self-organizing list search in presenting the corresponding algorithm in the form of procedurewe take advantage of our experience made so far and introduce sentinel right from the start in facta sentinel not only speeds up the searchbut in this case it also simplifies the program the list must initially not be emptybut contains the sentinel element already the initialization statements are new(sentinel)root :sentinel note that the main difference between the new algorithm and the straight list search is the action of reordering when an element has been found it is then detached or deleted from its old position and inserted at the top this deletion again requires the use of two chasing pointerssuch that the predecessor of an identified element is still locatable thisin turncalls for the special treatment of the first element ( the empty listto conceive the linking processwe refer to fig it shows the two pointers when was identified as the desired element the configuration after correct reordering is represented in fig and the complete new search procedure is listed below sentinel root nil fig list before re-ordering sentinel root nil fig list after re-ordering
25,411
procedure search (xintegervar rootword)(adens _list *var wordbegin :rootsentinel key :xif sentinel then (*first element*new(root)root key :xroot count : root next :sentinel elsif key then inc( countelse (*search*repeat : : next until key xif sentinel then (*new entry* :rootnew(root)root key :xroot count : root next : else (*foundnow reorder*inc( count) next : nextw next :rootroot : end end end search the improvement in this search method strongly depends on the degree of clustering in the input data for given factor of clusteringthe improvement will be more pronounced for large lists to provide an idea of how much gain can be expectedan empirical measurement was made by applying the above cross-reference program to short and relatively long text and then comparing the methods of linear list ordering and of list reorganization the measured data are condensed into table unfortunatelythe improvement is greatest when different data organization is needed anyway we will return to this example in sect number of distinct keys number of occurrences of keys time for search with ordering time for search with reordering improvement factor table comparsion of list search methods test test
25,412
an applicationpartial ordering (topological sortingan appropriate example of the use of flexibledynamic data structure is the process of topological sorting this is sorting process of items over which partial ordering is definedi where an ordering is given over some pairs of items but not between all of them the following are examples of partial orderings in dictionary or glossarywords are defined in terms of other words if word is defined in terms of word wwe denote this by topological sorting of the words in dictionary means arranging them in an order such that there will be no forward references task ( an engineering projectis broken up into subtasks completion of certain subtasks must usually precede the execution of other subtasks if subtask must precede subtask wwe write topological sorting means their arrangement in an order such that upon initiation of each subtask all its prerequisite subtasks have been completed in university curriculumcertain courses must be taken before others since they rely on the material presented in their prerequisites if course is prerequisite for course wwe write topological sorting means arranging the courses in such an order that no course lists later course as prerequisite in programsome procedures may contain calls of other procedures if procedure is called by procedure wwe write topological sorting implies the arrangement of procedure declarations in such way that there are no forward references in generala partial ordering of set is relation between the elements of it is denoted by the symbol "<"verbalized by precedesand satisfies the following three properties (axiomsfor any distinct elements xyz of if and zthen (transitivity if ythen not (asymmetry not (irreflexivityfor evident reasonswe will assume that the sets to be topologically sorted by an algorithm are finite hencea partial ordering can be illustrated by drawing diagram or graph in which the vertices denote the elements of and the directed edges represent ordering relationships an example is shown in fig fig partially ordered set the problem of topological sorting is to embed the partial order in linear order graphicallythis implies the arrangement of the vertices of the graph in rowsuch that all arrows point to the rightas shown in fig properties ( and ( of partial orderings ensure that the graph contains no loops this is exactly the prerequisite condition under which such an embedding in linear order is possible
25,413
fig linear arrangement of the partially ordered set of fig how do we proceed to find one of the possible linear orderingsthe recipe is quite simple we start by choosing any item that is not preceded by another item (there must be at least oneotherwise loop would existthis object is placed at the head of the resulting list and removed from the set the remaining set is still partially orderedand so the same algorithm can be applied again until the set is empty in order to describe this algorithm more rigorouslywe must settle on data structure and representation of and its ordering the choice of this representation is determined by the operations to be performedparticularly the operation of selecting elements with zero predecessors every item should therefore be represented by three characteristicsits identification keyits set of successorsand count of its predecessors since the number of elements in is not given priorithe set is conveniently organized as linked list consequentlyan additional entry in the description of each item contains the link to the next item in the list we will assume that the keys are integers (but not necessarily the consecutive integers from to nanalogouslythe set of each item' successors is conveniently represented as linked list each element of the successor list is described by an identification and link to the next item on this list if we call the descriptors of the main listin which each item of occurs exactly onceleadersand the descriptors of elements on the successor chains trailerswe obtain the following declarations of data typestype leader pointer to leaderdesctrailer pointer to trailerdescleaderdesc record keycountintegertrailtrailernextleader endtrailerdesc record idleadernexttrailer end assume that the set and its ordering relations are initially represented as sequence of pairs of keys in the input file the input data for the example in fig are shown belowin which the symbols are added for the sake of claritysymbolizing partial order < < < < < < < < < < < the first part of the topological sort program must read the input and transform the data into list structure this is performed by successively reading pair of keys and ( ylet us denote the pointers to their representations on the linked list of leaders by and these records must be located by list search andif not yet presentbe inserted in the list this task is perfomed by function procedure called find subsequentlya new entry is added in the list of trailers of xalong with an identification of qthe count of predecessors of is incremented by this algorithm is called input phase figure illustrates the data structure generated during processing the given input data the function find(wyields the pointer to the list element with key in the following poece of program we make use of text scanninga feature of the oberon system' text concept instead of considering text (fileas sequence of charactersa text is considered as sequence of tokenswhich are identifiersnumbersstringsand special characters (such as +*<etc the procedure texts scan(sscans the textreading the next token the scanner plays the role of text rider
25,414
(*input phase*new(head)tail :headtexts scan( )while class texts int do : itexts scan( ) : ip :find( ) :find( )new( ) id :qt next : trailp trail :tinc( count)texts scan(send tail head key count next trail id next id next fig list structure generated by topsort program after the data structure of fig has been constructed in this input phasethe actual process of topological sorting can be taken up as described above but since it consists of repeatedly selecting an element with zero count of predecessorsit seems sensible to first gather all such elements in linked chain since we note that the original chain of leaders will afterwards no longer be neededthe same field called next may be used again to link the zero predecessor leaders this operation of replacing one chain by another chain occurs frequently in list processing it is expressed in detail hereand for reasons of convenience it constructs the new chain in reverse order (*search for leaders without predecessors* :headhead :nilwhile tail do :pp : nextif count then (*insert qin new chain* next :headhead : end end referring to fig we see that the next chain of leaders is replaced by the one of fig in which the pointers not depicted are left unchanged nil head
25,415
fig list of leaders with zero count after all this preparatory establishing of convenient representation of the partially ordered set swe can finally proceed to the actual task of topological sortingi of generating the output sequence in first rough version it can be described as followsq :headwhile nil do (*output this elementthen delete it*texts writeint(wq key )dec( ) : trailq : nextdecrement the predecessor count of all its successors on trailer list tif any count becomes insert this element in the leader list end the statement that is to be still further refined constitutes one more scan of list in each stepthe auxiliary variable designates the leader element whose count has to be decremented and tested while nil do : iddec( count)if count then (*insert pin leader list* next :qq : endt : next end this completes the program for topological sorting note that counter was introduced to count the leaders generated in the input phase this count is decremented each time leader element is output in the output phase it should therefore return to zero at the end of the program its failure to return to zero is an indication that there are elements left in the structure when none is without predecessor in this case the set is evidently not partially ordered the output phase programmed above is an example of process that maintains list that pulsatesi in which elements are inserted and removed in an unpredictable order it is therefore an example of process which utilizes the full flexibility offered by the explicitly linked list var headtailleaderninteger(adens _topsort *procedure find (winteger)leadervar hleaderbegin :headtail key : (*sentinel*while key do : next endif tail then new(tail)inc( ) count : trail :nilh next :tail endreturn end findprocedure topsort (var rtexts reader)var pqleaderttrailer(*uses global writer *xyintegerbegin (*initialize list of leaders with dummy acting as sentinel*new(head)tail :headn :
25,416
(*input phase*texts scan( )while class texts int do : itexts scan( ) : ip :find( ) :find( )new( ) id :qt next : trailp trail :tinc( count)texts scan(send(*search for leaders without predecessors* :headhead :nilwhile tail do :pp : nextif count then (*insert in new chain* next :headhead : end end(*output phase* :headwhile nil do texts writeln( )texts writeint(wq key )dec( ) : trailq : nextwhile nil do : iddec( count)if count then (*insert in leader list* next :qq : endt : next end endif then texts writestring( "this set is not partially ordered"endtexts writeln(wend topsort tree structures basic concepts and definitions we have seen that sequences and lists may conveniently be defined in the following waya sequence (listwith base type is either the empty sequence (list the concatenation (chainof and sequence with base type hereby recursion is used as an aid in defining structuring principlenamelysequencing or iteration sequences and iterations are so common that they are usually considered as fundamental patterns of structure and behaviour but it should be kept in mind that they can be defined in terms of recursionwhereas the reverse is not truefor recursion may be effectively and elegantly used to define much more sophisticated structures trees are well-known example let tree structure be defined as followsa tree structure with base type is either the empty structure
25,417
node of type with finite number of associated disjoint tree structures of base type called subtrees from the similarity of the recursive definitions of sequences and tree structures it is evident that the sequence (listis tree structure in which each node has at most one subtree the list is therefore also called degenerate tree ab( ( ( ( ), ( , , )), ( ( ), ( , ), ( ))) cn di fig representation of tree structure by (anested sets(bnested parentheses(cindented textand (dgraph there are several ways to represent tree structure for examplea tree structure with its base type ranging over the letters is shown in various ways in fig these representations all show the same structure and are therefore equivalent it is the graph structure that explicitly illustrates the branching relationships whichfor obvious reasonsled to the generally used name tree strangely enoughit is customary to depict trees upside downor -if one prefers to express this fact differently -to show the roots of trees the latter formulationhoweveris misleadingsince the top node (ais commonly called the root an ordered tree is tree in which the branches of each node are ordered hence the two ordered trees in fig are distinctdifferent objects node that is directly below node is called (direct
25,418
descendant of xif is at level ithen is said to be at level + converselynode is said to be the (directancestor of the root of tree is defined to be at level the maximum level of any element of tree is said to be its depth or height fig two distinct trees if an element has no descendantsit is called terminal node or leafand an element that is not terminal is an interior node the number of (directdescendants of an interior node is called its degree the maximum degree over all nodes is the degree of the tree the number of branches or edges that have to be traversed in order to proceed from the root to node is called the path length of the root has path length its direct descendants have path length etc in generala node at level has path length the path length of tree is defined as the sum of the path lengths of all its components it is also called its internal path length the internal path length of the tree shown in fig for instanceis evidentlythe average path length is pint (si < <nn in where is the number of nodes at level in order to define what is called the external path lengthwe extend the tree by special node wherever subtree was missing in the original tree in doing sowe assume that all nodes are to have the same degreenamely the degree of the tree extending the tree in this way therefore amounts to filling up empty brancheswhereby the special nodesof coursehave no further descendants the tree of fig extended with special nodes is shown in fig in which the special nodes are represented by squares the external path length is now defined as the sum of the path lengths over all special nodes if the number of special nodes at level is mi then the average external path length is pext (si < <mi im in the tree shown in fig the external path length is the number of special nodes to be added in tree of degree directly depends on the number of original nodes note that every node has exactly one edge pointing to it thusthere are + edges in the extended tree on the other handd edges are emanating from each original nodenone from the special nodes thereforethere exist * + edgesthe resulting from the edge pointing to the root the two results yield the following equation between the number of special nodes and of original nodesd + +nor ( - the maximum number of nodes in tree of given height is reached if all nodes have subtreesexcept those at level hall of which have none for tree of degree dlevel then contains node (namelythe root)level contains its descendantslevel contains the descendants of the nodes at level etc this yields nd(hsi < hd as the maximum number of nodes for tree with height and degree for we obtain (
25,419
fig ternary tree extended with special nodes of particular importance are the ordered trees of degree they are called binary trees we define an ordered binary tree as finite set of elements (nodeswhich either is empty or consists of root (nodewith two disjoint binary trees called the left and the right subtree of the root in the following sections we shall exclusively deal with binary treesand we therefore shall use the word tree to mean ordered binary tree trees with degree greater than are called multiway trees and are discussed in sect familiar examples of binary trees are the family tree (pedigreewith person' father and mother as descendants (!)the history of tennis tournament with each game being node denoted by its winner and the two previous games of the combatants as its descendantsor an arithmetic expression with dyadic operatorswith each operator denoting branch node with its operands as subtrees (see fig fig tree representation of expression ( / ( *fwe now turn to the problem of representation of trees it is plain that the illustration of such recursive structures in terms of branching structures immediately suggests the use of our pointer facility there is evidently no use in declaring variables with fixed tree structureinsteadwe define the nodes as variables with fixed structurei of fixed typein which the degree of the tree determines the number of pointer components referring to the node' subtrees evidentlythe reference to the empty tree is denoted by nil hencethe tree of fig consists of components of type defined as follows and may then be constructed as shown in fig type node pointer to nodedesctype nodedesc record opcharleftrightnode end
25,420
root nil nil nil nil nil nil nil nil nil nil nil nil fig tree of fig represented as linked data structure before investigating how trees might be used advantageously and how to perform operations on treeswe give an example of how tree may be constructed by program assume that tree is to be generated containing nodes with the values of the nodes being numbers read from an input file in order to make the problem more challenginglet the task be the construction of tree with nodes and minimal height in order to obtain minimal height for given number of nodesone has to allocate the maximum possible number of nodes of all levels except the lowest one this can clearly be achieved by distributing incoming nodes equally to the left and right at each node this implies that we structure the tree for given as shown in fig for = = = = = = = fig perfectly balanced trees the rule of equal distribution under known number of nodes is best formulated recursively use one node for the root generate the left subtree with nl div nodes in this way generate the right subtree with nr nl nodes in this way the rule is expressed as recursive procedure which reads the input file and constructs the perfectly balanced tree we note the following definitiona tree is perfectly balancedif for each node the numbers of nodes in its left and right subtrees differ by at most type node pointer to record (adens _balancedtree *
25,421
keyintegerleftrightnode endvar rtexts readerwtexts writerrootnodeprocedure tree (ninteger)nodevar newnodexnlnrintegerbegin (*construct perfectly balanced tree with nodes*if then new :nil else nl : div nr : -nl- new(new)texts readint(rnew key)new key :xnew left :tree(nl)new right :tree(nrendreturn new end treeprocedure printtree (tnodehinteger)var iintegerbegin (*print tree with indentation *if nil then printtree( lefth+ )for : to do texts write(wtabendtexts writeint(wt key )texts writeln( )printtree( righth+ end end printtreeassumefor examplethe following input data for tree with nodes the call root :tree( reads the input dara while constructing the perfectly balanced tree shown in fig fig tree generated by preceding program note the simplicity and transparency of this program that is obtained through the use of recursive procedures it is obvious that recursive algorithms are particularly suitable when program is to manipulate information whose structure is itself defined recursively this is again manifested in the procedure which
25,422
prints the resulting treethe empty tree results in no printingthe subtree at level in first printing its own left subtreethen the nodeproperly indented by preceding it with tabsand finally in printing its right subtree basic operations on binary trees there are many tasks that may have to be perfomed on tree structurea common one is that of executing given operation on each element of the tree is then understood to be parameter of the more general task of visting all nodes oras it is usually calledof tree traversal if we consider the task as single sequential processthen the individual nodes are visited in some specific order and may be considered as being laid out in linear arrangement in factthe description of many algorithms is considerably facilitated if we can talk about processing the next element in the tree based in an underlying order there are three principal orderings that emerge naturally from the structure of trees like the tree structure itselfthey are conveniently expressed in recursive terms referring to the binary tree in fig in which denotes the root and and denote the left and right subtreesthe three orderings are rab (visit root before the subtrees preorder inorder postorderarb abr (visit root after the subtreesr fig binary tree traversing the tree of fig and recording the characters seen at the nodes in the sequence of encounterwe obtain the following orderings preorder inorder postorder+ + + we recognize the three forms of expressionspreorder traversal of the expression tree yields prefix notationpostorder traversal generates postfix notationand inorder traversal yields conventional infix notationalthough without the parentheses necessary to clarify operator precedences let us now formulate the three methods of traversal by three concrete programs with the explicit parameter denoting the tree to be operated upon and with the implicit parameter denoting the operation to be performed on each node assume the following definitionstype node pointer to record leftrightnode end the three methods are now readily formulated as recursive proceduresthey demonstrate again the fact that operations on recursively defined data structures are most conveniently defined as recursive algorithms
25,423
procedure preorder (tnode)begin if nil then ( )preorder( left)preorder( rightend end preorder procedure inorder (tnode)begin if nil then inorder( left) ( )inorder( rightend end inorder procedure postorder (tnode)begin if nil then postorder( left)postorder( right) (tend end postorder note that the pointer is passed as value parameter this expresses the fact that the relevant entity is the reference to the considered subtree and not the variable whose value is the pointerand which could be changed in case were passed as variable parameter an example of tree traversal routine is that of printing treewith appropriate indentation indicating each node' level binary trees are frequently used to represent set of data whose elements are to be retrievable through unique key if tree is organized in such way that for each node iall keys in the left subtree of are less than the key of iand those in the right subtree are greater than the key of ithen this tree is called search tree in search tree it is possible to locate an arbitrary key by starting at the root and proceeding along search path switching to node' left or right subtree by decision based on inspection of that node' key only as we have seenn elements may be organized in binary tree of height as little as log(nthereforea search among items may be performed with as few as log(ncomparsions if the tree is perfectly balanced obviouslythe tree is much more suitable form for organizing such set of data than the linear list used in the previous section as this search follows single path from the root to the desired nodeit can readily be programmed by iterationprocedure locate (xintegertnode)nodebegin while ( nil( key xdo if key then : right else : left end endreturn end locate the function locate(xtyields the value nilif no key with value is found in the tree with root as in the case of searching listthe complexity of the termination condition suggests that better solution may existnamely the use of sentinel this technique is equally applicable in the case of tree the use of pointers makes it possible for all branches of the tree to terminate with the same sentinel the resulting structure is no longer treebut rather tree with all leaves tied down by strings to single anchor point
25,424
(fig the sentinel may be considered as commonshared representative of all external nodes by which the original tree was extended (see fig )procedure locate (xintegertnode)nodebegin key : (*sentinel*while key do if key then : right else : left end endreturn end locate note that in this case locate(xtyields the value instead of nili the pointer to the sentinelif no key with value is found in the tree with root fig search tree with sentinel tree search and insertion the full power of the dynamic allocation technique with access through pointers is hardly displayed by those examples in which given set of data is builtand thereafter kept unchanged more suitable examples are those applications in which the structure of the tree itself variesi grows and/or shrinks during the execution of the program this is also the case in which other data representationssuch as the arrayfail and in which the tree with elements linked by pointers emerges as the most appropriate solution we shall first consider only the case of steadily growing but never shrinking tree typical example is the concordance problem which was already investigated in connection with linked lists it is now to be revisited in this problem sequence of words is givenand the number of occurrences of each word has to be determined this means thatstarting with an empty treeeach word is searched in the tree if it is foundits occurrence count is incrementedotherwise it is inserted as new word (with count initialized to we call the underlying task tree search with insertion the following data type definitions are assumedtype node pointer to record keycountintegerleftrightnode end finding the search path is again straightforward howeverif it leads to dead end ( to an empty subtree designated by pointer value nil)then the given word must be inserted in the tree at the place of
25,425
the empty subtree considerfor examplethe binary tree shown in fig and the insertion of the name paul the result is shown in dotted lines in the same picture norma george ann nil er mary nil nil paul nil nil walter nil nil nil fig insertion in ordered binary tree the search process is formulated as recursive procedure note that its parameter is variable parameter and not value parameter this is essential because in the case of insertion new pointer value must be assigned to the variable which previously held the value nil using the input sequence of numbers that had been used above to construct the tree of fig the search and insertion procedure yields the binary tree shown in fig with call search(krootfor each key kwhere root is variable of type node fig search tree generated by preceding program procedure printtree (tnodehinteger)var iintegerbegin (*print tree with indentation *if nil then printtree( lefth+ )for : to do texts write(wtabendtexts writeint(wt key )texts writeln( )printtree( righth+ end end printtree(adens _tree *
25,426
procedure search (xintegervar pnode)begin if nil then (* not in treeinsert*new( ) key :xp count : left :nilp right :nil elsif key then search(xp leftelsif key then search(xp rightelse inc( countend end search the use of sentinel again simplifies the task somewhat clearlyat the start of the program the variable root must be initialized by the pointer to the sentinel instead of the value niland before each search the specified value must be assigned to the key field of the sentinel procedure search (xintegervar pnode)begin if key then search(xp leftelsif key then search(xp rightelsif then inc( countelse (*insert*new( ) key :xp left :sp right :sp count : end end search although the purpose of this algorithm is searchingit can be used for sorting as well in factit resembles the sorting by insertion method quite stronglyand because of the use of tree structure instead of an arraythe need for relocation of the components above the insertion point vanishes tree sorting can be programmed to be almost as efficient as the best array sorting methods known but few precautions must be taken after encountering matchthe new element must also be inserted if the case key is handled identically to the case keythen the algorithm represents stable sorting methodi items with identical keys turn up in the same sequence when scanning the tree in normal order as when they were inserted in generalthere are better ways to sortbut in applications in which searching and sorting are both neededthe tree search and insertion algorithm is strongly recommended it isin factvery often applied in compilers and in data banks to organize the objects to be stored and retrieved an appropriate example is the construction of cross-reference index for given textan example that we had already used to illustrate list generation our task is to construct program that (while reading text and printing it after supplying consecutive line numberscollects all words of this textthereby retaining the numbers of the lines in which each word occurred when this scan is terminateda table is to be generated containing all collected words in alphabetical order with lists of their occurrences obviouslythe search tree (also called lexicographic treeis most suitable candidate for representing the words encountered in the text each node now not only contains word as key valuebut it is also the head of list of line numbers we shall call each recording of an occurrence an item hencewe encounter both trees and linear lists in this example the program consists of two main partsnamelythe scanning phase and the table printing phase the latter is straightforward application of tree traversal routine in which visiting each node implies the printing of the key value (wordand the scanning of its associated list of line numbers (itemsthe following are further clarifications regarding the program listed below table shows the results of processing the text of the preceding procedure search
25,427
word is considered as any sequence of letters and digits starting with letter since words may be of widely different lengthsthe actual characters are stored in an array bufferand the tree nodes contain the index of the key' first character it is desirable that the line numbers be printed in ascending order in the cross-reference index thereforethe item lists must be generated in the same order as they are scanned upon printing this requirement suggests the use of two pointers in each word nodeone referring to the firstand one referring to the last item on the list we assume the existence of global writer wand variable representing the current line number in the text const wordlen (adens _crossref *type word array wordlen of charitem pointer to recordlnointegernextitem endnode pointer to record keywordfirstlastitem(*list*leftrightnode (*tree*endvar lineintegerprocedure search (var wnodevar aword)var qitembegin if nil then (*word not in treenew entryinsert*new( )new( ) lno :linecopy(aw key) first :qw last :qw left :nilw right :nil elsif key then search( rightaelsif key then search( leftaelse (*old entry*new( ) lno :linew last next :qw last : end end searchprocedure tabulate (wnode)var mintegeritemitembegin if nil then tabulate( left)texts writestring(ww key)texts write(wtab)item : firstm : repeat if then texts writeln( )texts write(wtab) : endinc( )texts writeint(witem lno )item :item next until item niltexts writeln( )tabulate( rightend end tabulateprocedure crossref (var rtexts reader)var rootnode(*uses global writer *
25,428
iintegerchcharwwordbegin root :nilline : texts writeint( )texts write(wtab)texts read(rch)while ~ eot do if ch dx then (*line end*texts writeln( )inc(line)texts writeint(wline )texts write( )texts read(rchelsif (" <ch(ch <" "or (" <ch(ch <" "then : repeat if wordlen- then [ :chinc(iendtexts write(wch)texts read(rchuntil ( wordlen- or ~((" <ch(ch <" ")~((" <ch(ch <" ")~((" <ch(ch <" ")) [ : (*string terminator*search(rootwelse texts write(wch)texts read(rchendendtexts writeln( )texts writeln( )tabulate(rootend crossref procedure search (xintegervar pnode)begin if key then search(xp leftelsif ^key then search(xp rightelsif then inc( countelse (*insert*new( ) key :xp left :sp right :sp count : end end begin else elsif end if inc integer new node procedure then var count insert key left right search table sample output of cross reference generator
25,429
tree deletion we now turn to the inverse problem of insertiondeletion our task is to define an algorithm for deletingi removing the node with key in tree with ordered keys unfortunatelyremoval of an element is not generally as simple as insertion it is straightforward if the element to be deleted is terminal node or one with single descendant the difficulty lies in removing an element with two descendantsfor we cannot point in two directions with single pointer in this situationthe deleted element is to be replaced by either the rightmost element of its left subtree or by the leftmost node of its right subtreeboth of which have at most one descendant the details are shown in the recursive procedure delete this procedure distinguishes among three cases there is no component with key equal to the component with key has at most one descendant the component with key has two descendants procedure delete (xintegervar pnode)(adens _deletion *procedure del (var rnode)begin if right nil then del( rightelse key : keyp count : countr : left end end delbegin (*delete*if nil then (*word is not in tree*elsif key then delete(xp leftelsif key then delete(xp rightelse (*delete ^:*if right nil then : left elsif left nil then : right else del( leftend end end delete the auxiliaryrecursive procedure del is activated in case only it descends along the rightmost branch of the left subtree of the element pto be deletedand then it replaces the relevant information (key and countin pby the corresponding values of the rightmost component rof that left subtreewhereafter rmay be disposed we note that we do not mention procedure that would be the inverse of newindicating that storage is no longer needed and therefore disposable and reusable it is generally assumed that computer system recognizes disposable variable through the circumstance that no other variables are pointing to itand that it therefore can no longer be referenced such system is called garbage collector it is not feature of programming languagebut rather of its implementations in order to illustrate the functioning of procedure we refer to fig consider the tree ( )then delete successively the nodes with keys the resulting trees are shown in fig ( -
25,430
ab fig tree deletion analysis of tree search and insertion it is natural reaction to be suspicious of the algorithm of tree search and insertion at least one should retain some skepticism until having been given few more details about its behaviour what worries many programmers at first is the peculiar fact that generally we do not know how the tree will growwe have no idea about the shape that it will assume we can only guess that it will most probably not be the perfectly balanced tree since the average number of comparisons needed to locate key in perfectly balanced tree with nodes is approximately log( )the number of comparisons in tree generated by this algorithm will be greater but how much greaterfirst of allit is easy to find the worst case assume that all keys arrive in already strictly ascending (or descendingorder then each key is appended immediately to the right (leftof its predecessorand the resulting tree becomes completely degeneratei it turns out to be linear list the average search effort is then / comparisons this worst case evidently leads to very poor performance of the search algorithmand it seems to fully justify our skepticism the remaining question isof coursehow likely this case will be more preciselywe should like to know the length an of the search path averaged over all keys and averaged over all ntrees that are generated from the npermutations of the original distinct keys this problem of algorithmic analysis turns out to be fairly straightforwardand it is presented here as typical example of analyzing an algorithm as well as for the practical importance of its result given are distinct keys with values assume that they arrive in random order the probability of the first key -which notably becomes the root node -having the value is / its left subtree will eventually contain - nodesand its right subtree - nodes (see fig let the average path length in the left subtree be denoted by ai- and the one in the right subtree is an-iagain assuming that all possible permutations of the remaining - keys are equally likely the average path length in tree with nodes is the sum of the products of each node' level and its probability of access if all nodes are assumed to be searched with equal likelihoodthen an (si < <npin where pi is the path length of node
25,431
- - fig weight distribution of branches in the tree in fig we divide the nodes into three classes the - nodes in the left subtree have an average path length ai- the root has path length of the - nodes in the right subtree have an average path length an- hencethe equation above can be expressed as sum of two terms and an( (( - ai- ( -ian-in the desired quantity an is the average of an(iover all ni over all trees with the key at the root an (si < < ( - ai- ( -ian-in (si < < ( - ai- (si < ni ain this equation is recurrence relation of the form an ( an- from this we derive simpler recurrence relation of the form an (an- we derive directly ( by splitting off the last termand ( by substituting - for ( an *( - an- / (si < - ain ( an- (si < - ai( - ) multiplying ( by - ) / yields ( (si < - ain an- ( - ) / and substituting the right part of ( in ( )we find an ( - an- an- ( - ) an- ( - ) it turns out that an can be expressed in non-recursiveclosed form in terms of the harmonic sum hn / / / an (hn ( + )/ from euler' formula (using euler' constant )hn ln / we derivefor large nthe approximate value an (ln since the average path length in the perfectly balanced tree is approximately anlog we obtainneglecting the constant terms which become insignificant for large nlim (an/an' ln(nlog( ln( what does this result teach usit tells us that by taking the pains of always constructing perfectly balanced tree instead of the random treewe could always provided that all keys are looked up with
25,432
equal probability expect an average improvement in the search path length of at most emphasis is to be put on the word averagefor the improvement may of course be very much greater in the unhappy case in which the generated tree had completely degenerated into listwhichhoweveris very unlikely to occur in this connection it is noteworthy that the expected average path length of the random tree grows also strictly logarithmically with the number of its nodeseven though the worst case path length grows linearly the figure of imposes limit on the amount of additional effort that may be spent profitably on any kind of reorganization of the tree' structure upon insertion of keys naturallythe ratio between the frequencies of access (retrievalof nodes (informationand of insertion (updatesignificantly influences the payoff limits of any such undertaking the higher this ratiothe higher is the payoff of reorganization procedure the figure is low enough that in most applications improvements of the straight tree insertion algorithm do not pay off unless the number of nodes and the access vs insertion ratio are large balanced trees from the preceding discussion it is clear that an insertion procedure that always restores the treesstructure to perfect balance has hardly any chance of being profitablebecause the restoration of perfect balance after random insertion is fairly intricate operation possible improvements lie in the formulation of less strict definitions of balance such imperfect balance criteria should lead to simpler tree reorganization procedures at the cost of only slight deterioration of average search performance one such definition of balance has been postulated by adelson-velskii and landis [ - the balance criterion is the followinga tree is balanced if and only if for every node the heights of its two subtrees differ by at most trees satisfying this condition are often called avl-trees (after their inventorswe shall simply call them balanced trees because this balance criterion appears most suitable one (note that all perfectly balanced trees are also avl-balanced the definition is not only simplebut it also leads to manageable rebalancing procedure and an average search path length practically identical to that of the perfectly balanced tree the following operations can be performed on balanced trees in (log nunits of timeeven in the worst case locate node with given key insert node with given key delete the node with given key these statements are direct consequences of theorem proved by adelson-velskii and landiswhich guarantees that balanced tree will never be more than higher than its perfectly balanced counterpartno matter how many nodes there are if we denote the height of balanced tree with nodes by hb( )then log( + hb( *log( + the optimum is of course reached if the tree is perfectly balanced for - but which is the structure of the worst avl-balanced treein order to find the maximum height of all balanced trees with nodeslet us consider fixed height and try to construct the balanced tree with the minimum number of nodes this strategy is recommended becauseas in the case of the minimal heightthe value can be attained only for certain specific values of let this tree of height be denoted by clearlyt is the empty treeand is the tree with single node in order to construct the tree for we will provide the root with two subtrees which again have minimal number of nodes hencethe subtrees are also evidentlyone subtree must have height - and the other is then allowed to have height of one lessi - figure shows the trees with height and since their composition principle very
25,433
strongly resembles that of fibonacci numbersthey are called fibonacci-trees (see fig they are defined as follows the empty tree is the fibonacci-tree of height single node is the fibonacci-tree of height if - and - are fibonacci-trees of heights - and - then is fibonacci-tree no other trees are fibonacci-trees fig fibonacci-trees of height and the number of nodes of is defined by the following simple recurrence relationn nh nh- nh- the nh are those numbers of nodes for which the worst case (upper limit of hcan be attainedand they are called leonardo numbers balanced tree insertion let us now consider what may happen when new node is inserted in balanced tree given root with the left and right subtrees and rthree cases must be distinguished assume that the new node is inserted in causing its height to increase by hl hrl and become of unequal heightbut the balance criterion is not violated hl hrl and obtain equal heighti the balance has even been improved hl hrthe balance criterion is violatedand the tree must be restructured consider the tree in fig nodes with keys and may be inserted without rebalancingthe tree with root will become one-sided (case )the one with root will improve its balance (case insertion of nodes or howeverrequires subsequent rebalancing fig balanced tree some careful scrutiny of the situation reveals that there are only two essentially different constellations
25,434
needing individual treatment the remaining ones can be derived by symmetry considerations from those two case is characterized by inserting keys or in the tree of fig case by inserting nodes or the two cases are generalized in fig in which rectangular boxes denote subtreesand the height added by the insertion is indicated by crosses simple transformations of the two structures restore the desired balance their result is shown in fig note that the only movements allowed are those occurring in the vertical directionwhereas the relative horizontal positions of the shown nodes and subtrees must remain unchanged case case fig imbalance resulting from insertion case case fig restoring the balance an algorithm for insertion and rebalancing critically depends on the way information about the tree' balance is stored an extreme solution lies in keeping balance information entirely implicit in the tree structure itself in this casehowevera node' balance factor must be rediscovered each time it is affected by an insertionresulting in an excessively high overhead the other extreme is to attribute an explicitly stored balance factor to every node the definition of the type node is then extended into type node pointer to record keycountbalinteger(*bal - + *leftrightnode end we shall subsequently interpret node' balance factor as the height of its right subtree minus the height of its left subtreeand we shall base the resulting algorithm on this node type the process of node insertion consists essentially of the following three consecutive parts follow the search path until it is verified that the key is not already in the tree insert the new node and determine the resulting balance factor retreat along the search path and check the balance factor at each node rebalance if necessary although this method involves some redundant checking (once balance is establishedit need not be
25,435
checked on that node' ancestors)we shall first adhere to this evidently correct schema because it can be implemented through pure extension of the already established search and insertion procedures this procedure describes the search operation needed at each single nodeand because of its recursive formulation it can easily accommodate an additional operation on the way back along the search path at each stepinformation must be passed as to whether or not the height of the subtree (in which the insertion had been performedhad increased we therefore extend the procedure' parameter list by the boolean with the meaning the subtree height has increased clearlyh must denote variable parameter since it is used to transmit result assume now that the process is returning to node pfrom the left branch (see fig )with the indication that it has increased its height we now must distinguish between the three conditions involving the subtree heights prior to insertion hl hrp bal + the previous imbalance at has been equilibrated hl hrp bal the weight is now slanted to the left hl hrp bal - rebalancing is necessary in the third caseinspection of the balance factor of the root of the left subtree (sayp baldetermines whether case or case of fig is present if that node has also higher left than right subtreethen we have to deal with case otherwise with case (convince yourself that left subtree with balance factor equal to at its root cannot occur in this case the rebalancing operations necessary are entirely expressed as sequences of pointer reassignments in factpointers are cyclically exchangedresulting in either single or double rotation of the two or three nodes involved in addition to pointer rotationthe respective node balance factors have to be updated the details are shown in the searchinsertionand rebalancing procedures ab fig insertions in balanced tree the working principle is shown by fig consider the binary tree (awhich consists of two nodes only insertion of key first results in an unbalanced tree ( linear listits balancing involves rr single rotationresulting in the perfectly balanced tree (bfurther insertion of nodes and result in an imbalance of the subtree with root this subtree is balanced by an ll single rotation (dthe subsequent insertion of key immediately offsets the balance criterion at the root node balance is thereafter reestablished by the more complicated lr double rotationthe outcome is tree (ethe only candidate for losing balance after next insertion is node indeedinsertion of node must invoke the fourth case of rebalancing outlined belowthe rl double rotation the final tree is shown in fig (
25,436
procedure search (xintegervar pnodevar hboolean)var node(adens _avltrees *begin (*~ *if nil then (*insert*new( ) key :xp count : left :nilp right :nilp bal : :trueelsif key then search(xp lefth)if then (*left branch has grown*if bal then bal : :false elsif bal then bal :- else (*bal - rebalance* : leftif bal - then (*single ll rotation* left : rightp right :pp bal : : else (*double lr rotation* : rightp right : leftp left : left : rightp right :pif bal - then bal : else bal : endif bal + then bal :- else bal : endp : endp bal : :false end end elsif key then search(xp righth)if then (*right branch has grown*if bal - then bal : :false elsif bal then bal : else (*bal + rebalance* : rightif bal then (*sinlge rr rotation* right : leftp left :pp bal : : else (*double rl rotation* : leftp left : rightp right : right : leftp left :pif bal + then bal :- else bal : endif bal - then bal : else bal : endp : endp bal : :false end end else inc( countend end search two particularly interesting questions concerning the performance of the balanced tree insertion algorithm are the following
25,437
if all npermutations of keys occur with equal probabilitywhat is the expected height of the constructed balanced tree what is the probability that an insertion requires rebalancingmathematical analysis of this complicated algorithm is still an open problem empirical tests support the conjecture that the expected height of the balanced tree thus generated is log( )+cwhere is small constant ( this means that in practice the avl-balanced tree behaves as well as the perfectly balanced treealthough it is much simpler to maintain empirical evidence also suggests thaton the averagerebalancing is necessary once for approximately every two insertions here single and double rotations are equally probable the example of fig has evidently been carefully chosen to demonstrate as many rotations as possible in minimum number of insertions the complexity of the balancing operations suggests that balanced trees should be used only if information retrievals are considerably more frequent than insertions this is particularly true because the nodes of such search trees are usually implemented as densely packed records in order to economize storage the speed of access and of updating the balance factors -each requiring two bits only -is therefore often decisive factor to the efficiency of the rebalancing operation empirical evaluations show that balanced trees lose much of their appeal if tight record packing is mandatory it is indeed difficult to beat the straightforwardsimple tree insertion algorithm balanced tree deletion our experience with tree deletion suggests that in the case of balanced trees deletion will also be more complicated than insertion this is indeed truealthough the rebalancing operation remains essentially the same as for insertion in particularrebalancing consists again of either single or double rotations of nodes the basis for balanced tree deletion is the ordinary tree deletion algorithm the easy cases are terminal nodes and nodes with only single descendant if the node to be deleted has two subtreeswe will again replace it by the rightmost node of its left subtree as in the case of insertiona boolean variable parameter is added with the meaning "the height of the subtree has been reducedrebalancing has to be considered only when is true is made true upon finding and deleting nodeor if rebalancing itself reduces the height of subtree we now introduce the two (symmetricbalancing operations in the form of proceduresbecause they have to be invoked from more than one point in the deletion algorithm note that balancel is applied when the leftbalancer after the right branch had been reduced in height the operation of the procedure is illustrated in fig given the balanced tree ( )successive deletion of the nodes with keys and results in the trees ( (hdeletion of key is simple in itselfbecause it represents terminal node howeverit results in an unbalanced node its rebalancing operation invoves an ll single rotation rebalancing becomes again necessary after the deletion of node this time the right subtree of the root ( is rebalanced by an rr single rotation deletion of node although in itself straightforward since it has only single descendantcalls for complicated rl double rotation the fourth casean lr double rotationis finally invoked after the removal of node which at first was replaced by the rightmost element of its left subtreei by the node with key
25,438
gh fig deletions in balanced tree procedure balancel (var pnodevar hboolean)(adens _avltrees *var nodebegin (*hleft branch has shrunk*if bal - then bal : elsif bal then bal : :false else (*bal rebalance* : rightif bal > then (*sinlge rr rotation* right : leftp left :pif bal then bal : bal :- :false else bal : bal : endp : else (*double rl rotation* : leftp left : rightp right :
25,439
right : leftp left :pif bal + then bal :- else bal : endif bal - then bal : else bal : endp : bal : end end end balancelprocedure balancer (var pnodevar hboolean)var nodebegin (*hright branch has shrunk*if bal then bal : elsif bal then bal :- :false else (*bal - rebalance* : leftif bal < then (*single ll rotation* left : rightp right :pif bal then bal :- bal : :false else bal : bal : endp : else (*double lr rotation* : rightp right : leftp left : left : rightp right :pif bal - then bal : else bal : endif bal + then bal :- else bal : endp : bal : end end end balancerprocedure delete (xintegervar pnodevar hboolean)var qnodeprocedure del (var rnodevar hboolean)begin (*~ *if right nil then del( righth)if then balancer(rhend else key : keyq count : countq :rr : lefth :true end end delbegin (*~ *if nil then (*key not in tree*elsif key then delete(xp lefth)if then balancel(phend elsif key then delete(xp righth)if then balancer(phend
25,440
else (*delete ^* :pif right nil then : lefth :true elsif left nil then : righth :true else del( lefth)if then balancel(phend end end end delete fortunatelydeletion of an element in balanced tree can also be performed with -in the worst case - (log noperations an essential difference between the behaviour of the insertion and deletion procedures must not be overlookedhowever whereas insertion of single key may result in at most one rotation (of two or three nodes)deletion may require rotation at every node along the search path considerfor instancedeletion of the rightmost node of fibonacci-tree in this case the deletion of any single node leads to reduction of the height of the treein additiondeletion of its rightmost node requires the maximum number of rotations this therefore represents the worst choice of node in the worst case of balanced treea rather unlucky combination of chances how probable are rotationsthenin generalthe surprising result of empirical tests is that whereas one rotation is invoked for approximately every two insertionsone is required for every five deletions only deletion in balanced trees is therefore about as easy -or as complicated -as insertion optimal search trees so far our consideration of organizing search trees has been based on the assumption that the frequency of access is equal for all nodesthat isthat all keys are equally probable to occur as search argument this is probably the best assumption if one has no idea of access distribution howeverthere are cases (they are the exception rather than the rulein which information about the probabilities of access to individual keys is available these cases usually have the characteristic that the keys always remain the samei the search tree is subjected neither to insertion nor deletionbut retains constant structure typical example is the scanner of compiler which determines for each word (identifierwhether or not it is keyword (reserved wordstatistical measurements over hundreds of compiled programs may in this case yield accurate information on the relative frequencies of occurrenceand thereby of accessof individual keys assume that in search tree the probability with which node is accessed is pr { kipi(si < < pi we now wish to organize the search tree in way that the total number of search steps counted over sufficiently many trials becomes minimal for this purpose the definition of path length is modified by ( attributing certain weight to each node and by ( assuming the root to be at level (instead of )because it accounts for the first comparison along the search path nodes that are frequently accessed become heavy nodesthose that are rarely visited become light nodes the (internalweighted path length is then the sum of all paths from the root to each node weighted by that node' probability of access si < < pi hi hi is the level of node the goal is now to minimize the weighted path length for given probability distribution as an exampleconsider the set of keys with probabilities of access / / / these three keys can be arranged in five different ways as search trees (see fig
25,441
ab fig the search trees with nodes the weighted path lengths of trees (ato (eare computed according to their definition as ( / ( / ( / ( / ( / hencein this examplenot the perfectly balanced tree ( )but the degenerate tree (aturns out to be optimal the example of the compiler scanner immediately suggests that this problem should be viewed under slightly more general conditionwords occurring in the source text are not always keywordsas matter of facttheir being keywords is rather the exception finding that given word is not key in the search tree can be considered as an access to hypothetical "special nodeinserted between the next lower and next higher key (see fig with an associated external path length if the probability qi of search argument lying between the two keys ki and ki+ is also knownthis information may considerably change the structure of the optimal search tree hencewe generalize the problem by also considering unsuccessful searches the overall average weighted path length is now (si < < pi*hi(si < < qi* 'iwhere (si < < pi(si < < qi and wherehi is the level of the (internalnode and ' is the level of the external node the average weighted path length may be called the cost of the search treesince it represents measure for the expected amount of effort to be spent for searching the search tree that requires the minimal cost among all trees with given set of keys ki and probabilities pi and qi is called the optimal tree | | | | fig search tree with associated access frequencies for finding the optimal treethere is no need to require that the ' and ' sum up to in factthese probabilities are commonly determined by experiments in which the accesses to nodes are counted
25,442
instead of using the probabilities pi and qjwe will subsequently use such frequency counts and denote them by ai number of times the search argument equals ki bj number of times the search argument lies between kj and kj+ by conventionb is the number of times that is less than and bn is the frequency of being greater than kn (see fig we will subsequently use to denote the accumulated weighted path length instead of the average path lengthp (si < < ai*hi(si < < bi* 'ithusapart from avoiding the computation of the probabilities from measured frequency countswe gain the further advantage of being able to use integers instead of fractions in our search for the optimal tree considering the fact that the number of possible configurations of nodes grows exponentially with nthe task of finding the optimum seems rather hopeless for large optimal treeshoweverhave one significant property that helps to find themall their subtrees are optimal too for instanceif the tree in fig is optimalthen the subtree with keys and is also optimal as shown this property suggests an algorithm that systematically finds larger and larger treesstarting with individual nodes as smallest possible subtrees the tree thus grows from the leaves to the rootwhich issince we are used to drawing trees upside-downthe bottom-up direction [ - the equation that is the key to this algorithm is derived as followslet be the weighted path length of treeand let pl and pr be those of the left and right subtrees of its root clearlyp is the sum of pl and prand the number of times search travels on the leg to the rootwhich is simply the total number of search trials we call the weight of the tree its average path length is then /wp pl pr (si < < ai(si < < bithese considerations show the need for denotation of the weights and the path lengths of any subtree consisting of number of adjacent keys let ij be the optimal subtree consisting of nodes with keys ki+ ki+ kj then let wij denote the weight and let pij denote the path length of ij clearly , and , these quantities are defined by the following recurrence relationswii bi wij wi, - aj bj ( < <npii wii ( < <npij wij min ki < (pi, - pkj ( < < ( < <nthe last equation follows immediately from the definitions of and of optimality since there are approximately / values pijand because its definition calls for choice among all cases such that ji <nthe minimization operation will involve approximately / operations knuth pointed out that factor can be saved by the following considerationwhich alone makes this algorithm usable for practical purposes let rij be value of which achieves the minimum for it is possible to limit the search for rij to much smaller intervali to reduce the number of the - evaluation steps the key is the observation that if we have found the root rij of the optimal subtree ijthen neither extending the tree by adding node at the rightnor shrinking the tree by removing its leftmost node ever can cause the optimal root to move to the left this is expressed by the relation ri, - <rij <ri+ , which limits the search for possible solutions for rij to the range ri, - ri+ , this results in total number of elementary steps in the order of
25,443
we are now ready to construct the optimization algorithm in detail we recall the following definitionswhich are based on optimal trees ij consisting of nodes with keys ki+ kj aithe frequency of search for ki bjthe frequency of search argument between kj and kj+ wijthe weight of ij pijthe weighted path length of ij rijthe index of the root of ij we declare the following arraysabp, ,rarray + of integer(* [ not used*array + of integerarray + + of integerassume that the weights wij have been computed from and in straightforward way now consider as the argument of the procedure opttree to be developed and consider as its resultbecause describes the tree structure completely may be considered an intermediate result starting out by considering the smallest possible subtreesnamely those consisting of no nodes at allwe proceed to larger and larger trees let us denote the width - of the subtree ij by then we can trivially determine the values pii for all trees with according to the definition of pijfor : to do [ , : [iend in the case we deal with trees consisting of single nodewhich plainly is also the root (see fig for : to - do : + [ , : [ ,jp[ ,ip[ , ] [ , : end kj|aj bj- bj wj- - wj- fig optimal search tree with single node note that denotes the left index limit and the right index limit in the considered tree ij for the cases we use repetitive statement with ranging from to nthe case spanning the entire tree , in each case the minimal path length pij and the associated root index rij are determined by simple repetitive statement with an index ranging over the interval given for rijfor : to do for : to - do : +hfind and min min ki (pi, - pkj such that ri, - + ,jp[ , :min [ , ] [ , : end end
25,444
the details of the refinement of the statement in italics can be found in the program presented below the average path length of , is now given by the quotient , / ,nand its root is the node with index , let us now describe the structure of the program to be designed its two main components are the procedures to find the optimal search treegiven weight distribution wand to display the tree given the indices firstthe counts and and the keys are read from an input source the keys are actually not involved in the computation of the tree structurethey are merely used in the subsequent display of the tree after printing the frequency statisticsthe program proceeds to compute the path length of the perfectly balanced treein passing also determining the roots of its subtrees thereafterthe average weighted path length is printed and the tree is displayed in the third partprocedure opttree is activated in order to compute the optimal search treethereafterthe tree is displayed and finallythe same procedures are used to compute and display the optimal tree considering the key frequencies onlyignoring the frequencies of non-keys to summarizethe following are the global constants and variablesconst (*max no of keywords*wordlen (*max keyword length*var keyarray + wordlen of charabarray + of integerpwrarray + + of integerprocedure baltree (ijinteger)integervar kresintegerbegin :( + + div [ij:kif > then res : else res :baltree(ik- baltree(kjw[ijendreturn res end baltreeprocedure computeopttree (ninteger)var xmintmpintegerijkhmintegerbegin (*argumentwresultspr*for : to do [ii: endfor : to - do : + [ij: [ij] [ij: endfor : to do for : to - do : +hm : [ij- ]min : [im- [mj]for : + to [ + jdo tmp : [ik- ] : [kjtmpif min then :kmin : end endp[ij:min [ij] [ij: end end end computeopttree(adens _opttree *
25,445
procedure writetree (ijlevelinteger)var kinteger(*uses global writer *begin if then writetree(ir[ij]- level+ )for : to level do texts write(wtabendtexts writestring(wkey[ [ij]])texts writeln( )writetree( [ij]jlevel+ end end writetreeprocedure find (var stexts scanner)var ijninteger(*uses global writer *begin texts scan( ) [ :short( ) : texts scan( )(*inputakeyb*while class texts int do inc( ) [ :short( )texts scan( )copy( skey[ ])texts scan( ) [ :short( )texts scan(send(*compute from and *for : to do [ii: [ ]for : + to do [ij: [ij- [jb[jend endtexts writestring( "total weight ")texts writeint(ww[ ] )texts writeln( )texts writestring( "path length of balanced tree ")texts writeint(wbaltree( ) )texts writeln( )writetree( )texts writeln( )computeopttree( )texts writestring( "path length of optimal tree ")texts writeint(wp[ ] )texts writeln( )writetree( )texts writeln( )for : to do [ii: for : + to do [ij: [ij- [jend endcomputeopttree( )texts writestring( "optimal tree not considering ")texts writeln( )writetree( )texts writeln(wend findas an examplelet us consider the following input data of tree with keys albert ernst peter key albert
25,446
key ernst key peter the results of procedure find are shown in fig and demonstrate that the structures obtained for the three cases may differ significantly the total weight is the path length of the balanced tree is and that of the optimal tree is balanced tree optimal tree albert not considering key misses albert albert ernst ernst peter ernst peter peter fig the trees generated by the optimal tree procedure it is evident from this algorithm that the effort to determine the optimal structure is of the order of alsothe amount of required storage is of the order this is unacceptable if is very large algorithms with greater efficiency are therefore highly desirable one of them is the algorithm developed by hu and tucker [ - which requires only (nstorage and ( *log( )computations howeverit considers only the case in which the key frequencies are zeroi where only the unsuccessful search trials are registered another algorithmalso requiring (nstorage elements and ( *log( )computations was described by walker and gotlieb [ - instead of trying to find the optimumthis algorithm merely promises to yield nearly optimal tree it can therefore be based on heuristic principles the basic idea is the following consider the nodes (genuine and special nodesbeing distributed on linear scaleweighted by their frequencies (or probabilitiesof access then find the node which is closest to the center of gravity this node is called the centroidand its index is (si < < *ai(si < < *biw rounded to the nearest integer if all nodes have equal weightthen the root of the desired optimal tree evidently coincides with the centroid otherwise so the reasoning goes it will in most cases be in the close neighborhood of the centroid limited search is then used to find the local optimumwhereafter this procedure is applied to the resulting two subtrees the likelihood of the root lying very close to the centroid grows with the size of the tree as soon as the subtrees have reached manageable sizetheir optimum can be determined by the above exact algorithm -trees so farwe have restricted our discussion to trees in which every node has at most two descendantsi to binary trees this is entirely satisfactory iffor instancewe wish to represent family relationships with preference to the pedigree viewin which every person is associated with his parents after allno one has more than two parents but what about someone who prefers the posterity viewhe has to cope with the fact that some people have more than two childrenand his trees will contain nodes with many branches for lack of better termwe shall call them multiway trees of coursethere is nothing special about such structuresand we have already encountered all the programming and data definition facilities to cope with such situations iffor instancean absolute upper limit on the number of children is given (which is admittedly somewhat futuristic assumption)then one may represent the children as an array component of the record representing person if the number of children varies strongly among different personshoweverthis may result in poor utilization of available storage in this case it will be much more appropriate to arrange the offspring as linear listwith pointer
25,447
to the youngest (or eldestoffspring assigned to the parent possible type definition for this case is the followingand possible data structure is shown in fig type person =pointer to record namealfasiblingoffspringperson end john albert peter mary paul robert carol chris george pamela tina fig multiway tree represented as binary tree we now realize that by tilting this picture by degrees it will look like perfect binary tree but this view is misleading because functionally the two references have entirely different meanings one usually dosen' treat sibling as an offspring and get away unpunishedand hence one should not do so even in constructing data definitions this example could also be easily extended into an even more complicated data structure by introducing more components in each person' recordthus being able to represent further family relationships likely candidate that cannot generally be derived from the sibling and offspring references is that of husband and wifeor even the inverse relationship of father and mother such structure quickly grows into complex relational data bankand it may be possible to map serveral trees into it the algorithms operating on such structures are intimately tied to their data definitionsand it does not make sense to specify any general rules or widely applicable techniques howeverthere is very practical area of application of multiway trees which is of general interest this is the construction and maintenance of large-scale search trees in which insertions and deletions are necessarybut in which the primary store of computer is not large enough or is too costly to be used for long-time storage assumethenthat the nodes of tree are to be stored on secondary storage medium such as disk store dynamic data structures introduced in this are particularly suitable for incorporation of secondary storage media the principal innovation is merely that pointers are represented by disk store addresses instead of main store addresses using binary tree for data set ofsaya million itemsrequires on the average approximately log ( about search steps since each step now involves disk access (with inherent latency time) storage organization using fewer accesses will be highly desirable the multiway tree is perfect solution to this problem if an item located on secondary store is accessedan entire group of items may also be accessed without much additional cost this suggests that tree be subdivided into subtreesand that the subtrees are represented as units that are accessed all together we shall call these subtrees pages figure shows binary tree subdivided into pageseach page consisting of nodes
25,448
fig binary tree subdivided into pages the saving in the number of disk accesses -each page access now involves disk access -can be considerable assume that we choose to place nodes on page (this is reasonable figure)then the million item search tree will on the average require only log ( ( about page accesses instead of butof courseif the tree is left to grow at randomthen the worst case may still be as large as it is plain that scheme for controlled growth is almost mandatory in the case of multiway trees multiway -trees if one is looking for controlled growth criterionthe one requiring perfect balance is quickly eliminated because it involves too much balancing overhead the rules must clearly be somewhat relaxed very sensible criterion was postulated by bayer and mccreight [ in every page (except onecontains between and nodes for given constant hencein tree with items and maximum page size of nodes per pagethe worst case requires lognn page accessesand page accesses clearly dominate the entire search effort moreoverthe important factor of store utilization is at least since pages are always at least half full with all these advantagesthe scheme involves comparatively simple algorithms for searchinsertionand deletion we will subsequently study them in detail the underlying data structures are called -treesand have the following characteristicsn is said to be the order of the -tree every page contains at most items (keys every pageexcept the root pagecontains at least items every page is either leaf pagei has no descendantsor it has + descendantswhere is its number of keys on this page all leaf pages appear at the same level fig -tree of order figure shows -tree of order with levels all pages contain or itemsthe exception is the root which is allowed to contain single item only all leaf pages appear at level the keys appear in
25,449
increasing order from left to right if the -tree is squeezed into single level by inserting the descendants in between the keys of their ancestor page this arrangement represents natural extension of binary search treesand it determines the method of searching an item with given key consider page of the form shown in fig and given search argument assuming that the page has been moved into the primary storewe may use conventional search methods among the keys km- if is sufficiently largeone may use binary searchif it is rather smallan ordinary sequential search will do (note that the time required for search in main store is probably negligible compared to the time it takes to move the page from secondary into primary store if the search is unsuccessfulwe are in one of the following situations ki ki+ for - the search continues on page pi km- the search continues on page pm- the search continues on page - - pm- km- pm- fig -tree page with keys if in some case the designated pointer is nili if there is no descendant pagethen there is no item with key in the whole treeand the search is terminated surprisinglyinsertion in -tree is comparatively simple too if an item is to be inserted in page with itemsthe insertion process remains constrained to that page it is only insertion into an already full page that has consequences upon the tree structure and may cause the allocation of new pages to understand what happens in this caserefer to fig which illustrates the insertion of key in -tree of order it proceeds in the following steps key is found to be missinginsertion in page is impossible because is already full page is split into two pages ( new page is allocated the + keys are equally distributed onto and dand the middle key is moved up one level into the ancestor page fig insertion of key in -tree this very elegant scheme preserves all the characteristic properties of -trees in particularthe split pages contain exactly items of coursethe insertion of an item in the ancestor page may again cause that page to overflowthereby causing the splitting to propagate in the extreme case it may propagate up to the root this isin factthe only way that the -tree may increase its height the -tree has thus strange manner of growingit grows from its leaves upward to the root we shall now develop detailed program from these sketchy descriptions it is already apparent that recursive formulation will be most convenient because of the property of the splitting process to propagate
25,450
back along the search path the general structure of the program will therefore be similar to balanced tree insertionalthough the details are different first of alla definition of the page structure has to be formulated we choose to represent the items in the form of an array type page pointer to pagedescriptoritem record keyintegerppagecountinteger (*data*endpagedescriptor record minteger( * pageearray * of item end againthe item component count stands for all kinds of other information that may be associated with each itembut it plays no role in the actual search process note that each page offers space for items the field indicates the actual number of items on the page as > (except for the root page) storage utilization of least is guaranteed the algorithm of -tree search and insertion is formulated below as procedure called search its main structure is straightforward and similar to that for the balanced binary tree searchwith the exception that the branching decision is not binary choice insteadthe "within-page searchis represented as binary search on the array of elements the insertion algorithm is formulated as separate procedure merely for clarity it is activated after search has indicated that an item is to be passed up on the tree (in the direction toward the rootthis fact is indicated by the boolean result parameter hit assumes similar role as in the algorithm for balanced tree insertionwhere indicates that the subtree had grown if is truethe second result parameterurepresents the item being passed up note that insertions start in hypothetical pagesnamelythe "special nodesof fig the new item is immediately handed up via the parameter to the leaf page for actual insertion the scheme is sketched hereprocedure search (xintegerapagevar hbooleanvar uitem)begin if nil then (* not in treeinsert*assign to item uste to trueindicating that an item is passed up in the tree else binary search for in array eif found then process data else search(xdescendanthu)if then (*an item was passed up*if no of items on page then insert on page aand set to false else split page and pass middle item up end end end end end search if the paramerter is true after the call of search in the main programa split of the root page is requested since the root page plays an exceptional rolethis process has to be programmed separately it consists merely of the allocation of new root page and the insertion of the single item given by the paramerter
25,451
as consequencethe new root page contains single item only the details can be gathered from the program presented belowand fig shows the result of using the program to construct -tree with the following insertion sequence of keys the semicolons designate the positions of the snapshots taken upon each page allocation insertion of the last key causes two splits and the allocation of three new pages fig growth of -tree of order since each activation of search implies one page transfer to main storek logn(nrecursive calls are necessary at mostif the tree contains items hencewe must be capable of accommodating pages in main store this is one limiting factor on the page size in factwe need to accommodate even more than pagesbecause insertion may cause page splitting to occur corollary is that the root page is best allocated permanently in the primary storebecause each query proceeds necessarily through the root page another positive quality of the -tree organization is its suitability and economy in the case of purely sequential updating of the entire data base every page is fetched into primary store exactly once deletion of items from -tree is fairly straight-forward in principlebut it is complicated in the details we may distinguish two different circumstances the item to be deleted is on leaf pagehere its removal algorithm is plain and simple the item is not on leaf pageit must be replaced by one of the two lexicographically adjacent itemswhich happen to be on leaf pages and can easily be deleted in case finding the adjacent key is analogous to finding the one used in binary tree deletion we descend along the rightmost pointers down to the leaf page preplace the item to be deleted by the rightmost item on pand then reduce the size of by in any casereduction of size must be followed by check of the
25,452
number of items on the reduced pagebecauseif nthe primary characteristic of -trees would be violated some additional action has to be takenthis underflow condition is indicated by the boolean variable parameter the only recourse is to borrow or annect an item from one of the neighboring pagessay from since this involves fetching page into main store - relatively costly operation -one is tempted to make the best of this undesirable situation and to annect more than single item at once the usual strategy is to distribute the items on pages and evenly on both pages this is called page balancing of courseit may happen that there is no item left to be annected since has already reached its minimal size in this case the total number of items on pages and is - we may merge the two pages into oneadding the middle item from the ancestor page of and qand then entirely dispose of page this is exactly the inverse process of page splitting the process may be visualized by considering the deletion of key in fig once againthe removal of the middle key in the ancestor page may cause its size to drop below the permissible limit nthereby requiring that further special action (either balancing or mergingbe undertaken at the next level in the extreme case page merging may propagate all the way up to the root if the root is reduced to size it is itself deletedthereby causing reduction in the height of the btree this isin factthe only way that -tree may shrink in height figure shows the gradual decay of the -tree of fig upon the sequential deletion of the keys the semicolons again mark the places where the snapshots are takennamely where pages are being eliminated the similarity of its structure to that of balanced tree deletion is particularly noteworthy de fig decay of -tree of order type page pointer to pagerecentry record (adens _btrees *
25,453
keyintegerppage endpagerec record minteger(*no of entries on page* pageearray * of entry endvar rootpagewtexts writerprocedure search (xintegervar ppagevar kinteger)var ilrintegerfoundbooleanapagebegin :rootfound :falsewhile ( nil~found do : : (*binary search*while do :( +rdiv if < [ikey then : else : + end endif ( ( [rkey xthen found :true elsif then : else : [ - end endp :ak : end searchprocedure insert (xintegerapagevar hbooleanvar ventry)(* nil search key in -tree with rool ainsert new item with key if an entry is to be passed upassign it to :"tree has become higher"*var ilrintegerbpageuentrybegin (~ *if nil then key :xv :nilh :true else : : (*binary search*while do :( +rdiv if < [ikey then : else : + end endif ( ( [rkey xthen (*founddo nothing*else (*item not on this page*if then : else : [ - endinsert(xbhu)if then (*insert to the leeft of [ ]*if * then :false
25,454
for : to + by - do [ : [ - enda [ :uinc( melse (*overflowsplit into ab and assign the middle entry to *new( )if then (*insert in left pate * : [ - ]for : - to + by - do [ : [ - enda [ :ufor : to - do [ : [ +nend else (*insert in right page *dec(rn)if then : else : [ ]for : to - do [ : [ + + endb [ - : endfor : to - do [ : [ +nend enda :nb :nb : pv : end end end end end insertprocedure underflow (capagesintegervar hboolean)(* underflow pagec ancestor pages index of deleted entry in *var bpageikintegerbegin (* ( - ( [ - *if then (* :page to the right of * : [spk :( - + div (* nof items available on page * [ - : [ ] [ - : if then (*balance by moving - items from to *for : to - do [ + : [iendc [ : [ - ] : [spc [sp :bdec( mk)for : to - do [ : [ +kenda : - +kh :false else (*merge pages and bdiscard *for : to - do [ + : [ienddec( )for : to - do [ : [ + enda : *nh : end else (* :page to the left of *dec( )if then : else : [ - end
25,455
:( - + div (* nof items available on page *if then for : - to by - do [ + : [ienda [ - : [ ] [ - : (*move - items from to aone to *dec( mk)for : - to by - do [ : [ + + endc [ : [ ] : [spc [sp :aa : - +kh :false else (*merge pages and bdiscard * [sp : [ : [ ]for : to - do [ + + : [iendb : *ndec( ) : end end end underflowprocedure delete (xintegerapagevar hboolean)(*search and delete key in -tree aif page underflow arisesbalance with adjacent page or mergeh :"page is undersize"*var ilrintegerqpageprocedure del (ppagevar hboolean)var kintegerqpage(*global ar*begin : - : [kpif nil then del(qh)if then underflow(pqp mhend else [kp : [rpa [ : [ ]dec( ) : end end delbegin if nil then : : (*binary search*while do :( +rdiv if < [ikey then : else : + end endif then : else : [ - endif ( ( [rkey xthen (*found*if nil then (* is leaf page*dec( ) : nfor : to - do [ : [ + end else del(qh)if then underflow(aqrhend end else delete(xqh)if then underflow(aqrhend end
25,456
end end deleteprocedure showtree (var wtexts writerppagelevelinteger)var iintegerbegin if nil then for : to level do texts write( xendfor : to - do texts writeint(wp [ikey endtexts writeln( )if then showtree(wp level+ endfor : to - do showtree(wp [iplevel+ end end end showtreeextensive analysis of -tree performance has been undertaken and is reported in the referenced article (bayer and mccreightin particularit includes treatment of the question of optimal page sizewhich strongly depends on the characteristics of the storage and computing system available variations of the -tree scheme are discussed in knuthvol pp - the one notable observation is that page splitting should be delayed in the same way that page merging is delayedby first attempting to balance neighboring pages apart from thisthe suggested improvements seem to yield marginal gains comprehensive survey of -trees may be found in [ - binary -trees the species of -trees that seems to be least interesting is the first order -tree ( but sometimes it is worthwhile to pay attention to the exceptional case it is plainhoweverthat first-order -trees are not useful in representing largeorderedindexed data sets invoving secondary storesapproximately of all pages will contain single item only thereforewe shall forget secondary stores and again consider the problem of search trees involving one-level store only binary -tree (bb-treeconsists of nodes (pageswith either one or two items hencea page contains either two or three pointers to descendantsthis suggested the term - tree according to the definition of -treesall leaf pages appear at the same leveland all non-leaf pages of bb-trees have either two or three descendants (including the rootsince we now are dealing with primary store onlyan optimal economy of storage space is mandatoryand the representation of the items inside node in the form of an array appears unsuitable an alternative is the dynamiclinked allocationthat isinside each node there exists linked list of items of length or since each node has at most three descendants and thus needs to harbor only up to three pointersone is tempted to combine the pointers for descendants and pointers in the item list as shown in fig the -tree node thereby loses its actual identityand the items assume the role of nodes in regular binary tree it remains necessaryhoweverto distinguish between pointers to descendants (verticaland pointers to siblings on the same page (horizontalsince only the pointers to the right may be horizontala single bit is sufficient to record this distiction we therefore introduce the boolean field with the meaning horizontal the definition of tree node based on this representation is given below it was suggested and investigated by bayer [ - in and represents search tree organization guaranteeing *log(nas maximum path length type node pointer to record keyintegerleftrightnodehboolean (*right branch horizontal*
25,457
end fig representation of bb-tree nodes considering the problem of key insertionone must distinguish four possible situations that arise from growth of the left or right subtrees the four cases are illustrated in fig
25,458
fig node insertion in bb-tree remember that -trees have the characteristic of growing from the bottom toward the root and that the property of all leafs being at the same level must be maintained the simplest case ( is when the right subtree of node grows and when is the only key on its (hypotheticalpage thenthe descendant merely becomes the sibling of ai the vertical pointer becomes horizontal pointer this simple raising of the right arm is not possible if already has sibling then we would obtain page with nodesand we have to split it (case its middle node is passed up to the next higher level now assume that the left subtree of node has grown in height if is again alone on page (case ) its right pointer refers to descendantthen the left subtree (ais allowed to become ' sibling ( simple rotation of pointers is necessary since the left pointer cannot be horizontalifhoweverb already has siblingthe raising of yields page with three membersrequiring split this split is realized in very straightforward mannerc becomes descendant of bwhich is raised to the next higher level (case it should be noted that upon searching keyit makes no effective difference whether we proceed along horizontal or vertical pointer it therefore appears artificial to worry about left pointer in case becoming horizontalalthough its page still contains not more than two members indeedthe insertion algorithm reveals strange asymmetry in handling the growth of left and right subtreesand it lets the bbtree organization appear rather artificial there is no proof of strangeness of this organizationyet healthy intuition tells us that something is fishyand that we should remove this asymmetry it leads to the notion of the symmetric binary -tree (sbb-treewhich was also investigated by bayer [ - in on the average it leads to slightly more efficient search treesbut the algorithms for insertion and deletion are also slightly more complex furthermoreeach node now requires two bits (boolean variable lh and rhto indicate the nature of its two pointers since we will restrict our detail considerations to the problem of insertionwe have once again to distinguish among four cases of grown subtrees they are illustrated in fig which makes the gained symmetry evident note that whenever subtree of node without siblings growsthe root of the subtree becomes the sibling of this case need not be considered any further the four cases considered in fig all reflect the occurrence of page overflow and the subsequent page split they are labelled according to the directions of the horizontal pointers linking the three siblings in the middle figures the initial situation is shown in the left columnthe middle column illustrates the fact that the lower node has been raised as its subtree has grownthe figures in the right column show the result of node rearrangement
25,459
(llb (lra (rra (rla fig insertion in sbb-trees it is advisable to stick no longer to the notion of pages out of which this organization had developedfor we are only interested in bounding the maximum path length to *log(nfor this we need only ensure that two horizontal pointers may never occur in succession on any search path howeverthere is no reason to forbid nodes with horizontal pointers to the left and righti to treat the left and right sides differently we therefore define the symmetric binary -tree as tree that has the following properties every node contains one key and at most two (pointers tosubtrees every pointer is either horizontal or vertical there are no two consecutive horizontal pointers on any search path all terminal nodes (nodes without descendantsappear at the same (terminallevel from this definition it follows that the longest search path is no longer than twice the height of the tree since no sbb-tree with nodes can have height larger than log( )it follows immediately that *log(nis an upper bound on the search path length in order to visualize how these trees growwe refer to fig the lines represent snapshots taken during the insertion of the following sequences of keyswhere every semicolon marks snapshot
25,460
( ( ( ( ( ( ( ( fig insertion of keys to these pictures make the third property of -trees particularly obviousall terminal nodes appear on the same level one is therefore inclined to compare these structures with garden hedges that have been recently trimmed with hedge scissors the algorithm for the construction of sbb-trees is show below it is based on definition of the type node with the two components lh and rhindicating whether or not the left and right pointers are horizontal type node record keycountintegerleftrightpointer to nodelhrhboolean end the recursive procedure search again follows the pattern of the basic binary tree insertion algorithm third parameter is addedit indicates whether or not the subtree with root has changedand it corresponds directly to the parameter of the -tree search program we must notehoweverthe consequence of representing pages as linked listsa page is traversed by either one or two calls of the search procedure we must distinguish between the case of subtree (indicated by vertical pointerthat has grown and sibling node (indicated by horizontal pointerthat has obtained another sibling and hence requires page split the problem is easily solved by introducing three-valued with the following meanings
25,461
the subtree requires no changes of the tree structure node has obtained sibling the subtree has increased in height procedure search (var pnodexintegervar hinteger)var qrnode(adens _bbtrees *begin (* = *if nil then (*insert new node*new( ) key :xp :nilp :nilp lh :falsep rh :falseh : elsif key then search( lxh)if then (*left branch has grown or received sibling* : lif lh then : lh :falseif lh then (*ll* : rq lh :falseq :pp : else (* rhlr* : rq : lq rh :falser : lp : rr :pp : end else dec( )if then lh :true end end end elsif key then search( rxh)if then (*right branch has grown or received sibling* : rif rh then : rh :falseif rh then (*rr* : lq rh :falseq :pp : else (* lhrl* : lq : rq lh :falser : rp : lr :pp : end else dec( )if then rh :true end end end end end searchnote that the actions to be taken for node rearrangement very strongly resemble those developed in the avl-balanced tree search algorithm it is evident that all four cases can be implemented by simple pointer rotationssingle rotations in the ll and rr casesdouble rotations in the lr and rl cases in factprocedure search appears here slightly simpler than in the avl case clearlythe sbb-tree scheme
25,462
emerges as an alternative to the avl-balancing criterion performance comparison is therefore both possible and desirable we refrain from involved mathematical analysis and concentrate on some basic differences it can be proven that the avl-balanced trees are subset of the sbb-trees hencethe class of the latter is larger it follows that their path length is on the average larger than in the avl case note in this connection the worst-case tree ( in fig on the other handnode rearrangement is called for less frequently the balanced tree is therefore preferred in those applications in which key retrievals are much more frequent than insertions (or deletions)if this quotient is moderatethe sbb-tree scheme may be preferred it is very difficult to say where the borderline lies it strongly depends not only on the quotient between the frequencies of retrieval and structural changebut also on the characteristics of an implementation this is particularly the case if the node records have densely packed representationand if therefore access to fields involves part-word selection the sbb-tree has later found rebirth under the name of red-black tree the difference is that whereas in the case of the symmetricbinary -tree every node contains two -fields indicating whether the emanating pointers are horizontalevery node of the red-black tree contains single -fieldindicating whether the incoming pointer is horizontal the name stems from the idea to color nodes with incoming down-pointer blackand those with incoming horizontal pointer red no two red nodes can immedaitely follow each other on any path thereforelike in the cases of the bband sbb-treesevery search path is at most twice as long as the height of the tree there exists canonical mapping from binary -trees to red-black trees priority search trees treesand in particular binary treesconstitute very effective organisations for data that can be ordered on linear scale the preceding have exposed the most frequently used ingenious schemes for efficient searching and maintenance (insertiondeletiontreeshoweverdo not seem to be helpful in problems where the data are located not in one-dimensionalbut in multi-dimensional space in factefficient searching in multi-dimensional spaces is still one of the more elusive problems in computer sciencethe case of two dimensions being of particular importance to many practical applications upon closer inspection of the subjecttrees might still be applied usefully at least in the two-dimensional case after allwe draw trees on paper in two-dimensional space let us therefore briefly review the characteristics of the two major kinds of trees so far encountered search tree is governed by the invariants left nil implies right nil implies left xp right xholding for all nodes with key it is apparent that only the horizontal position of nodes is at all constrained by the invariantand that the vertical positions of nodes can be arbitrarily chosen such that access times in searching( path lengthsare minimized heapalso called priority treeis governed by the invariants left nil implies right nil implies < left yp < right yholding for all nodes with key here evidently only the vertical positions are constrained by the invariants it seems straightforward to combine these two conditions in definition of tree organization in twodimensional spacewith each node having two keys and which can be regarded as coordinates of the node such tree represents point set in planei in two-dimensional cartesian spaceit is therefore
25,463
called cartesian tree [ - we prefer the term priority search treebecause it exhibits that this structure emerged from combination of the priority tree and the search tree it is characterized by the following invariants holding for each node pp left nil implies ( left ( < left yp right nil implies ( right ( < right yit should come as no big surprisehoweverthat the search properties of such trees are not particularly wonderful after alla considerable degree of freedom in positioning nodes has been taken away and is no longer available for choosing arrangements yielding short path lengths indeedno logarithmic bounds on efforts involved in searchinginsertingor deleting elements can be assured although this had already been the case for the ordinaryunbalanced search treethe chances for good average behaviour are slim even worsemaintenance operations can become rather unwieldy considerfor examplethe tree of fig (ainsertion of new node whose coordinates force it to be inserted above and between and requires considerable effort transforming (ainto ( ( (bfig insertion into priority search tree mccreight discovered schemesimilar to balancingthatat the expense of more complicated insertion and deletion operationguarantees logarithmic time bounds for these operations he calls that structure priority search tree [ - ]in terms of our classificationhoweverit should be called balanced priority search tree we refrain from discussing that structurebecause the scheme is very intricate and in practice hardly used by considering somewhat more restrictedbut in practice no less relevant problemmccreight arrived at yet another tree structurewhich shall be presented here in detail instead of assuming that the search space be unboundedhe considered the data space to be delimited by rectangle with two sides open we denote the limiting values of the -coordinate by xmin and xmax in the scheme of the (unbalancedpriority search tree outlined aboveeach node divides the plane into two parts along the line all nodes of the left subtree lie to its leftall those in the right subtree to its right for the efficiency of searching this choice may be bad fortunatelywe may choose the dividing line differently let us associate with each node an interval [ )ranging over all values including up to but excluding this shall be the interval within which the -value of the node may lie then we postulate that the left descendant (if anymust lie within the left halfthe right descendant within the right half of this interval hencethe dividing line is not xbut ( + )/ for each descendant the interval is halvedthus limiting the height of the tree to log(xmax -xminthis result holds only if no two nodes have the same -valuea condition whichhoweveris guaranteed by the invariant if we deal with integer coordinatesthis limit is at most equal to the wordlength of the computer used effectivelythe search proceeds like bisection or radix searchand therefore these trees are called radix priority search trees [ they feature logarithmic bounds on the number of operations required for searchinginsertingand deleting an elementand are governed by the following invariants for each node
25,464
left nil implies ( < left ( < left yp right nil implies ( < right ( < right where ( rdiv left left right right for all node pand root xminroot xmax decisive advantage of the radix scheme is that maintenance operations (preserving the invariants under insertion and deletionare confined to single spine of the treebecause the dividing lines have fixed values of irrespective of the -values of the inserted nodes typical operations on priority search trees are insertiondeletionfinding an element with the least (largestvalue of (or ylarger (smallerthan given limitand enumerating the points lying within given rectangle given below are procedures for inserting and enumerating they are based on the following type declarationstype node pointer to record xyintegerleftrightnode end notice that the attributes xl and xr need not be recorded in the nodes themselves they are rather computed during each search thishoweverrequires two additional parameters of the recursive procedure insert their values for the first call (with rootare xmin and xmax respectively apart from thisa search proceeds similarly to that of regular search tree if an empty node is encounteredthe element is inserted if the node to be inserted has -value smaller than the one being inspectedthe new node is exchanged with the inspected node finallythe node is inserted in the left subtreeif its -value is less than the middle value of the intervalor the right subtree otherwise procedure insert (var pnodexyxlxrinteger)var xmtinteger(adens _prioritysearchtrees *begin if nil then (*not in treeinsert*new( ) :xp :yp left :nilp right :nil elsif then (*founddon' insert*else if then : xp :xx :tt : yp :yy : endxm :(xl xrdiv if xm then insert( leftxyxlxmelse insert( rightxyxmxrend end end insert the task of enumerating all points xy lying in given rectanglei satisfying < and < is accomplished by the following procedure enumerate it calls procedure report( ,yfor each point
25,465
found note that one side of the rectangle lies on the -axisi the lower bound for is this guarantees that enumeration requires at most (log(nsoperationswhere is the cardinality of the search space in and is the number of nodes enumerated procedure enumerate (pptrx xlxrinteger)var xminteger(adens _prioritysearchtrees *begin if nil then if ( < ( < ( then report( xp yendxm :(xl xrdiv if xm then enumerate( leftx xlxmendif xm then enumerate( rightx xmxrend end end enumerate exercises let us introduce the notion of recursive typeto be declared as rectype and denoting the set of values defined by the type enlarged by the single value none the definition of the type personfor examplecould then be simplified to rectype person record namenamefathermotherperson end which is the storage pattern of the recursive structure corresponding to fig presumablyan implementation of such feature would be based on dynamic storage allocation schemeand the fields named father and mother in the above example would contain pointers generated automatically but hidden from the programmer what are the difficulties encountered in the realization of such feature define the data structure described in the last paragraph of section in terms of records and pointers is it also possible to represent this family constellation in terms of recursive types as proposed in the preceding exercise assume that first-in-first-out (fifoqueue with elements of type is implemented as linked list define module with suitable data structureprocedures to insert and extract an element from qand function to test whether or not the queue is empty the procedures should contain their own mechanism for an economical reuse of storage assume that the records of linked list contain key field of type integer write program to sort the list in order of increasing value of the keys then construct procedure to invert the list circular lists (see fig are usually set up with so-called list header what is the reason for introducing such headerwrite procedures for the insertiondeletionand search of an element identified by given key do this once assuming the existence of headeronce without header
25,466
fig circular list bidirectional list is list of elements that are linked in both ways (see fig both links are originating from header analogous to the preceding exerciseconstruct module with procedures for searchinginsertingand deleting elements fig bidirectional list does the given program for topological sorting work correctly if certain pair occurs more than once in the input the message "this set is not partially orderedin the program for topological sorting is not very helpful in many cases extend the program so that it outputs sequence of elements that form loopif there exists one write program that reads program textidentifies all procedure definitions and callsand tries to establish topological ordering among the subroutines let mean that is called by draw the tree constructed by the program shown for constructing the perfectly balanced treeif the input consists of the natural numbers which are the sequences of nodes encountered when traversing the tree of fig in preorderinorderand postorder find composition rule for the sequence of numbers whichif applied to the program for straight search and insertionyields perfectly balanced tree consider the following two orders for traversing binary treesa traverse the right subtree visit the root traverse the left subtree visit the root traverse the right subtree traverse the left subtree are there any simple relationships between the sequences of nodes encountered following these orders and those generated by the three orders defined in the text define data structure to represent -ary trees then write procedure that traverses the -ary tree and generates binary tree containing the same elements assume that the key stored in an element
25,467
occupies words and that each pointer occupies one word of storage what is the gain in storage when using binary tree versus an -ary tree assume that tree is built upon the following definition of recursive data structure (see exercise formulate procedure to find an element with given key and to perform an operation on this element rectype tree record xintegerleftrighttree end in certain file system directory of all files is organized as an ordered binary tree each node denotes file and specifies the file name andamong other things the date of its last accessencoded as an integer write program that traverses the tree and deletes all files whose last access was before certain date in tree structure the frequency of access of each element is measured empirically by attributing to each node an access count at certain intervals of timethe tree organization is updated by traversing the tree and generating new tree by using the program of straight search and insertionand inserting the keys in the order of decreasing frequency count write program that performs this reorganization is the average path length of this tree equal toworseor much worse than that of an optimal tree the method of analyzing the tree insertion algorithm described in sect can also be used to compute the expected numbers cn of comparisons and mn of moves (exchangeswhich are performed by quicksortsorting elements of an arrayassuming that all npermutations of the keys are equally likely find the analogy and determine cn and mn draw the balanced tree with nodes which has the maximum height of all -node balanced trees in which sequence do the nodes have to be inserted so that the avl-insertion procedure generates this tree find sequence of insertion keys so that the procedure for insertion in an avl-tree performs each of the four rebalancing acts (lllrrrrlat least once what is the minimal length for such sequence find balanced tree with keys and permutation of these keys so thatwhen applied to the deletion procedure for avl-treesit performs each of the four rebalancing routines at least once what is the sequence with minimal length what is the average path length of the fibonacci-tree write program that generates nearly optimal tree according to the algorithm based on the selection of centroid as root assume that the keys are inserted into an empty -tree of order which keys cause page splits to occurwhich keys cause the height of the tree to increaseif the keys are deleted in the same orderwhich keys cause pages to be merged (and disposedand which keys cause the height to decreaseanswer the question for (aa deletion scheme using balancingand (ba scheme whithout balancing (upon underflowa single item only is fetched from neighboring page write program for the searchinsertionand deletion of keys in binary -tree use the node type and the insertion scheme shown above for the binary -tree find sequence of insertion keys whichstarting from the empty symmetric binary -treecauses
25,468
the shown procedure to perform all four rebalancing acts (lllrrrrlat least once what is the shortest such sequence write procedure for the deletion of elements in symmetric binary -tree then find tree and short sequence of deletions causing all four rebalancing situations to occur at least once formulate data structure and procedures for the insertion and deletion of an element in priority search tree the procedures must maintain the specified invariants compare their performance with that of the radix priority search tree design module with the following procedures operating on radix priority search trees-insert point with coordinates xy -enumerate all points within specified rectangle -find the point with the least -coordinate in specified rectangle -find the point with the largest -coordinate within specified rectangle -enumerate all points lying within two (intersectingrectangles references [ adelson-velskii and landis doklady akademia nauk sssr ( ) - english translation in soviet math - [ bayer and mccreight organization and maintenance of large ordered indexes acta informatica no ( ) - [ bayer and mccreight binary -trees for virtual memory proc acm sigfidet workshopsan diegonov pp - [ bayer and mccreight symmetric binary -treesdata structure and maintenance algorithms acta informatica no ( ) - [ hu and tucker siam applied math no ( - [ knuth optimum binary search trees acta informatica no ( ) - [ walker and gotlieb top-down algorithm for constructing nearly optimal lexicographic treesingraph theory and computing (new yorkacademic press )pp - [ comer the ubiquitous -tree acm comp surveys (june ) - [ vuillemin unifying look at data structures comm acm (april ) - [ mccreight priority search trees siam of comp (may
25,469
key transformations (hashing introduction the principal question discussed in chap at length is the followinggiven set of items characterized by key (upon which an ordering relation is defined)how is the set to be organized so that retrieval of an item with given key involves as little effort as possibleclearlyin computer store each item is ultimately accessed by specifying storage address hencethe stated problem is essentially one of finding an appropriate mapping of keys (kinto addresses ( )hk in chap this mapping was implemented in the form of various list and tree search algorithms based on different underlying data organizations here we present yet another approach that is basically simple and very efficient in many cases the fact that it also has some disadvantages is discussed subsequently the data organization used in this technique is the array structure is therefore mapping transforming keys into array indiceswhich is the reason for the term key transformation that is generally used for this technique it should be noted that we shall not need to rely on any dynamic allocation proceduresthe array is one of the fundamentalstatic structures the method of key transformations is often used in problem areas where tree structures are comparable competitors the fundamental difficulty in using key transformation is that the set of possible key values is much larger than the set of available store addresses (array indicestake for example names consisting of up to letters as keys identifying individuals in set of thousand persons hencethere are possible keys which are to be mapped onto possible indices the function is therefore obviously many-toone function given key kthe first step in retrieval (searchoperation is to compute its associated index ( )and the second evidently necessary step is to verify whether or not the item with the key is indeed identified by in the array (tablet to check whether [ ( )key we are immediately confronted with two questions what kind of function should be used how do we cope with the situation that does not yield the location of the desired itemthe answer to the second question is that some method must be used to yield an alternative locationsay index 'andif this is still not the location of the wanted itemyet third index "and so on the case in which key other than the desired one is at the identified location is called collisionthe task of generating alternative indices is termed collision handling in the following we shall discuss the choice of transformation function and methods of collision handling choice of hash function prerequisite of good transformation function is that it distributes the keys as evenly as possible over the range of index values apart from satisfying this requirementthe distribution is not bound to any patternand it is actually desirable that it give the impression of being entirely random this property has given this method the somewhat unscientific name hashingi chopping the argument upor making mess is called the hash function clearlyit should be efficiently computablei be composed of very few basic arithmetic operations assume that transfer function ord(kis avilable and denotes the ordinal number of the key in the set of all possible keys assumefurthermorethat the array indices range over the intergers - where is the size of the array then an obvious choice is
25,470
(kord(kmod it has the property that the key values are spread evenly over the index rangeand it is therefore the basis of most key transformations it is also very efficiently computableif is power of but it is exactly this case that must be avoidedif the keys are sequences of letters the assumption that all keys are equally likely is in this case mistaken in factwords that differ by only few characters then most likely map onto identical indicesthus effectively causing most uneven distribution it is therefore particularly recommended to let be prime number [ - this has the conseqeunce that full division operation is needed that cannot be replaced by mere masking of binary digitsbut this is no serious drawback on most modern computers that feature built-in division instruction oftenhash funtions are used which consist of applying logical operations such as the exclusive or to some parts of the key represented as sequence of binary digits these operations may be faster than division on some computersbut they sometimes fail spectacularly to distribute the keys evenly over the range of indices we therefore refrain from discussing such methods in further detail collision handling if an entry in the table corresponding to given key turns out not to be the desired itemthen collision is presenti two items have keys mapping onto the same index second probe is necessaryone based on an index obtained in deterministic manner from the given key there exist several methods of generating secondary indices an obvious one is to link all entries with identical primary index (ktogether in linked list this is called direct chaining the elements of this list may be in the primary table or notin the latter casestorage in which they are allocated is usually called an overflow area this method has the disadvantage that secondary lists must be maintainedand that each entry must provide space for pointer (or indexto its list of collided items an alternative solution for resolving collisions is to dispense with links entirely and instead simply look at other entries in the same table until the item is found or an open position is encounteredin which case one may assume that the specified key is not present in the table this method is called open addressing [ - naturallythe sequence of indices of secondary probes must always be the same for given key the algorithm for table lookup can then be sketched as followsh : ( ) : repeat if [hkey then item found elsif [hkey free then item is not in table else (*collision* : + : (kg(iend until found or not in table (or table fullvarious functions for resolving collisions have been proposed in the literature survey of the topic by morris in [ - stimulated considerable activities in this field the simplest method is to try for the next location considering the table to be circular until either the item with the specified key is found or an empty location is encountered henceg(iithe indices hi used for probing in this case are (khi (hi- imod ni - this method is called linear probing and has the disadvantage that entries have tendency to cluster around the primary keys (keys that had not collided upon insertionideallyof coursea function should be chosen that again spreads the keys uniformly over the remaining set of locations in practicehowever
25,471
this tends to be too costlyand methods that offer compromise by being simple to compute and still superior to the linear function are preferred one of them consists of using quadratic function such that the sequence of indices for probing is (khi ( mod ni > note that computation of the next index need not involve the operation of squaringif we use the following recurrence relations for hi and di hi+ di+ hi di di > with and this is called quadratic probingand it essentially avoids primary clusteringalthough practically no additional computations are required very slight disadvantage is that in probing not all table entries are searchedthat isupon insertion one may not encounter free slot although there are some left in factin quadratic probing at least half the table is visited if its size is prime number this assertion can be derived from the following deliberation if the -th and the -th probes coincide upon the same table entrywe can express this by the equation mod mod ( (modulo nsplitting the differences up into two factorswe obtain ( )( (modulo nand since jwe realize that either or have to be at least / in order to yield + * with being an integer in practicethe drawback is of no importancesince having to perform / secondary probes and collision evasions is extremely rare and occurs only if the table is already almost full as an application of the scatter storage techniquethe cross-reference generator procedure shown in sect is rewritten the principal differences lie in the procedure search and in the replacement of the pointer type node by the global hash table of words the hash function is the modulus of the table sizequadratic probing was chosen for collision handling note that it is essential for good performance that the table size be prime number although the method of key transformation is most effective in this case -actually more efficient than tree organizations -it also has disadvantage after having scanned the text and collected the wordswe presumably wish to tabulate these words in alphabetical order this is straightforward when using tree organizationbecause its very basis is the ordered search tree it is nothoweverwhen key transformations are used the full significance of the word hashing becomes apparent not only would the table printout have to be preceded by sort process (which is omitted here)but it even turns out to be advantageous to keep track of inserted keys by linking them together explicitly in list hencethe superior performance of the hashing method considering the process of retrieval only is partly offset by additional operations required to complete the full task of generating an ordered cross-reference index const (*primetable size*wordlen (*max length of keys*noc (*max no of items per word*type word array wordlen of chartable pointer to array of record keywordnintegerlnoarray noc of integer end(adens _crossref *
25,472
var lineintegerprocedure search (ttablevar aword)var idintegerhlongintfoundbooleanbegin (*compute hash index for auses global variable line* : : while [ do :( * ord( [ ])mod ninc(iendd : found :falserepeat if [hkey then (*match*found :truet[hlno[ [hn:lineif [hn noc then inc( [hnend elsif [hkey[ then (*new entry*found :truecopy(at[hkey) [hlno[ :linet[hn : else (*collision* : +dd : + if > then : - endif = then texts writestring( ,table overflow")halt( end end until found end searchprocedure tabulate (ttable)(*uses global writer *var ikintegerbegin for : to - do if [kkey[ then texts writestring(wt[kkey)texts write(wtab)for : to [kn - do texts writeint(wt[klno[ ] endtexts writeln(wend end end tabulateprocedure crossref (var rtexts reader)var iintegerchcharwwordhtablebegin new( )(*allocate and clear hash table*for : to - do [ikey[ :endline : texts writeint( )texts write(wtab)texts read(rch)while ~ eot do if ch dx then (*line end*texts writeln( )inc(line)texts writeint(wline )texts write( )texts read(rchelsif (" <ch(ch <" "or (" <ch(ch <" "then : repeat if wordlen- then [ :chinc(iendtexts write(wch)texts read(rchuntil ( wordlen- or ~((" <ch(ch <" ")~((" <ch(ch <" ")~((" <ch(ch <" "))
25,473
[ : (*string terminator*search(hwelse texts write(wch)texts read(rchendtexts writeln( )texts writeln( )tabulate(hend end crossref analysis of key transformation insertion and retrieval by key transformation has evidently miserable worst-case performance after allit is entirely possible that search argument may be such that the probes hit exactly all occupied locationsmissing consistently the desired (or freeones actuallyconsiderable confidence in the correctness of the laws of probability theory is needed by anyone using the hash technique what we wish to be assured of is that on the average the number of probes is small the following probabilistic argument reveals that it is even very small let us once again assume that all possible keys are equally likely and that the hash function distributes them uniformly over the range of table indices assumethenthat key has to be inserted in table of size which already contains items the probability of hitting free location the first time is then ( - )/ this is also the probability that single comparison only is needed the probability that excatly one second probe is needed is equal to the probability of collision in the first try times the probability of hitting free location the next time in generalwe obtain the probability pi of an insertion requiring exactly probes as ( - )/ ( /nx ( - )/( - ( /nx ( - )/( - ( - )/( - pi ( /nx ( - )/( - ( - )/( - ( - )/( -( - )the expected number of probes required upon insertion of the + st key is therefore ek+ si < < + pi ( - )/ ( /nx ( - )/( - ( + ( /nx ( - )/( - ( - )/( - /( -( - )( + ( -( - )since the number of probes required to insert an item is identical with the number of probes needed to retrieve itthe result can be used to compute the average number eof probes needed to access random key in table let the table size again be denoted by nand let be the number of keys actually in the table then (sk < < ekm ( + (sk < < /( - + ))/ ( + (hn+ hn- + where is the harmonic function can be approximated as hn ln(ngwhere is euler' constant ifmoreoverwe substitute for /( + )we obtain (ln( + ln( - + ))/ ln(( + )/( - + ))/ -ln( - )/ is approximately the quotient of occupied and available locationscalled the load factora implies
25,474
an empty tablea /( + full table the expected number of probes to retrieve or insert randomly chosen key is listed in table as function of the load factor table expected number of probes as function of the load factor the numerical results are indeed surprisingand they explain the exceptionally good performance of the key transformation method even if table is fullon the average only probes are necessary to either locate the key or to find an empty location note in particular that this figure does not depend on the absolute number of keys presentbut only on the load factor the above analysis was based on the use of collision handling method that spreads the keys uniformly over the remaining locations methods used in practice yield slightly worse performance detailed analysis for linear probing yields an expected number of probes as ( / ( asome numerical values for (aare listed in table [ table expected number of probes for linear probing the results obtained even for the poorest method of collision handling are so good that there is temptation to regard key transformation (hashingas the panacea for everything this is particularly so because its performance is superior even to the most sophisticated tree organization discussedat least on the basis of comparison steps needed for retrieval and insertion it is therefore important to point out explicitly some of the drawbacks of hashingeven if they are obvious upon unbiased consideration certainly the major disadvantage over techniques using dynamic allocation is that the size of the table is fixed and cannot be adjusted to actual demand fairly good priori estimate of the number of data items to be classified is therefore mandatory if either poor storage utilization or poor performance (or even table overflowis to be avoided even if the number of items is exactly known -an extremely rare case -the desire for good performance dictates to dimension the table slightly (say %too large the second major deficiency of scatter storage techniques becomes evident if keys are not only to be inserted and retrievedbut if they are also to be deleted deletion of entries in hash table is extremely cumbersome unless direct chaining in separate overflow area is used it is thus fair to say that tree organizations are still attractiveand actually to be preferredif the volume of data is largely unknownis strongly variableand at times even decreases
25,475
exercises if the amount of information associated with each key is relatively large (compared to the key itself)this information should not be stored in the hash table explain why and propose scheme for representing such set of data consider the proposal to solve the clustering problem by constructing overflow trees instead of overflow listsi of organizing those keys that collided as tree structures henceeach entry of the scatter (hashtable can be considered as the root of (possibly emptytree compare the expected performance of this tree hashing method with that of open addressing devise scheme that performs insertions and deletions in hash table using quadratic increments for collision resolution compare this scheme experimentally with the straight binary tree organization by applying random sequences of keys for insertion and deletion the primary drawback of the hash table technique is that the size of the table has to be fixed at time when the actual number of entries is not known assume that your computer system incorporates dynamic storage allocation mechanism that allows to obtain storage at any time hencewhen the hash table is full (or nearly full) larger table his generatedand all keys in are transferred to 'whereafter the store for can be returned to the storage administration this is called rehashing write program that performs rehash of table of size very often keys are not integers but sequences of letters these words may greatly vary in lengthand therefore they cannot conveniently and economically be stored in key fields of fixed size write program that operates with hash table and variable length keys references [ maurer an improved hash code for scatter storage comm acm no ( ) - [ morris scatter storage techniques comm acm no ( ) - [ peterson addressing for random-access storage ibm res dev ( ) - [ schay and spruth analysis of file addressing method comm acm no ( -
25,476
appendix the ascii character set nul dle soh dc stc etx dc dc eot dc enq nak ack syn bel etb bs can ht em lf sub vt esc ff fs cr gs so rs si us del
25,477
the syntax of the append(method issyntaxlistname append(elementl=[ , , , append( print("updated list=", #output:[ , , , , =[' ',' ',' ' append(' 'print("updated list=", #output:[' ',' ',' ',' ' insert():the insert(method insert one element at desired location syntaxlistname insert(index,elementl=[ , , insert( , print("updated list=", #output:[ , , , sort():sort elements in list in ascending order syntaxlistname sort(exl=[ , , , , sort(print(lo/ :[ , , , , count()this method returns the count of occurrence of an element in list syntaxlist count(xexl=[ , , , , , print( count( ) / : index():this method returns the index of the element syntaxlistname index(elementexl=[ , , , , , , , , print( index( ) / pop():this method removes and returns last object from the list synataxlist pop(elementexl=[ , , , print( pop()# is removed print(lo/ :[ , , print( pop( )# is removed print(lo/ :[ , bv prasanthi dept of cse page
25,478
remove():this method removes the first instance of element in list syntaxlist remove(elementexl=[ , , , , , remove( print(lo/ :[ , , , , reverse():this method reverses the list elements syntaxlist reverse(exl=[ , , , , , reverse(print(lo/ :[ , , , , , extend()the extend(extends the list by adding all items of list (passed as an argumentto the end syntax:list extend(list exl =[ , , =[' ',' ',' ' extend( print( print( copy():make copy of list with the copy(method syntaxlistname copy(exl =[ , , , , = copy(print( using lists to represent matrices in pythonwe can implement matrix as nested list (list inside listwe can treat each element as row of the matrix for example [[ ][ ][ ]would represent matrix first row can be selected as [ and the element in first rowfirst column can be selected as [ ][ )#write program to display given matrix [[ , , ][ , , ][ , , ]print(xbv prasanthi dept of cse page
25,479
iterate through rows for in range(len( ))iterate through columns for in range(len( [ ]))print( [ ][ ],end='\ 'for in resultprint )#write program to add two matrices [[ , , ][ , , ],[ , , ] [[ , , ],[ , , ],[ , , ]result [[ , , ],[ , , ][ , , ]iterate through rows for in range(len( ))iterate through columns for in range(len( [ ]))result[ ][jx[ ][jy[ ][jprint(result[ ][ ],end='\ 'print(program to find norm of matrix =[[ , , ],[ , , ],[ , , ]sum= for in range(len( ))for in range(len( [ ])if( == )sum=sum+ [ ][ ]* [ ][jprint(sumtuplestuple is an ordered collection of elements tuples are similar to listbut it is sequence of immutable objects tuples are fixed in lengthheterogeneousand can be nested individual elements can be accessed through offset (indexthey are represented by (ex =(print(type( )ex =( , , , , print( bv prasanthi dept of cse page
25,480
ex =( , ,'abc'print( basic tuple operations concatenation:we can use operator to combine the two tuples this is also called concatenation syntaxtuplename +tuplename ext =( , , =( , , print( + / :( , , , , , repitition:we can also repeat elements in tuple for given number of times using operator syntaxtuple*int-value =( , , print( * / :( , , , , , , , , tuple length:it is used to find the length of the tuple syntaxlen(tupleext=( , , print(len( ) / : index:we can use the index operator [to access an item in tuple index starts from syntaxtuplename[index ext=( , , , , print( [ ]#output: print( [ ]#output: membership operator:we can find element exists in tuple or not it returns boolean values exa=( , , print( in aprint( not in iterationwe can iterate each element in tuple using for loop syntaxfor in tupleexfor in ( , , )print( slicingslicing is used to extract part of tuple we can access range of elements in list by using the slicing operator (colont (' ',' ',' ',' ',' ',' ',' 'print(tprint( [ ]bv prasanthi dept of cse page
25,481
print( [ : ]print( [ :- ]print( [: ]print( [ :]print( [:- ]print( [ :: ]print( [::- ]methodstuple does not support remove(),pop(),append(),sort(),reverse(),insert(,extend( index():this method returns the index of the element syntaxextuplename index(elementt=( , , , , , , , , print( index( ) / count()this method returns the count of occurrence of an element in list syntaxtuplename count(elementext=( , , , , , print( count( ) / : )copy:copying one tuple to another tuple is done by using assignment operator =( , , = print( )zip()it takes two or more sequence(list,tupleand zip them into list of tuples or tuple of tuples =( , , =( , , , , =tuple(zip( , )print( =[ , , =[ , , , , =list(zip( , )print( #output#outputcompare list and tuple no list lists are mutable bv prasanthi dept of cse tuple tuple are immutable page
25,482
no list tuple implication of iterations is comparatively faster tuple data type is appropriate for accessing the elements tuple consume less memory as compared to the list tuple does no have must built-in methods implication of iterations is time-consuming the list is better for performing operationssuch as insertion and deletion lists consume more memory lists have several built-in methods the unexpected changes and errors are more in tupleit is hard to take place likely to occur setsset: set is unordered collection of elements and it is mutable every element is unique and must be immutable sets are represented by or by built in function set(exs={ , , print(ss ={"python",( , , )print( ={[ , , ], ,'hai'print( #output:error because list is mutable,but set should have immutable elements ={ , , , print(ss=set([ , , ]print(sset operations )union(|):it contains all the elements of set and set ={ , , , , ={ , , , , print( | )intersection(&):it contains common elements in both sets ={ , , , , ={ , , , , bv prasanthi dept of cse page
25,483
print( & )difference(-):difference of contain only elements that are in ,but not in ={ , , , , ={ , , , , print( - )set symmetric difference(^):symmetric difference of and is set of elements in both and except that are common in both ={ , , , , ={ , , , , print( ^ #output )membership operators:it return boolean values ={' ', , , print(' 'in aprint( not in aset methods )add():this method is used to add elements in set syntaxexsetname add(elements={' ','java','cpp' add('python'print( )clear():this method is used to remove the elements from set syntaxsetname clear(exv={ , , , clear(print( )copy():this method is used to copy the elements from one to another set syntaxsetname copy(exs={ , , = copy(print( )difference():difference of contain only elements that are in ,but not in syntaxset difference(set exa={ , , , , ={ , , , , print( difference( ) )intersection()it contains common elements in both sets bv prasanthi dept of cse page
25,484
syntaxset intersection(set exa={ , , , , ={ , , , , print( intersection( ) )union():it contains all the elements of set and set syntaxset union(set exa={ , , , , ={ , , , , print( union( ) )symmetric_difference():symmetric difference of and is set of elements in both and except that are common in both syntaxset symmetric_difference(set exa={ , , , , ={ , , , , print( symmetric_difference ( ) )discard():it takes single element and removes it from set syntaxsetname discard(elementexn={ , , , discard( print( )remove():this method searches for given element in the set and removes it syntaxsetname remove(elementexn={ , , , remove( print(nn={ , remove( #keyerror note:if we try to remove the element in the set which is not present ,it gives keyerror )pop():it removes random element in the set syntaxsetname pop(exs={' ',' ',' ' pop(print( )isdisjoint()two sets are said to be disjoint,if they have no common elements(true/falsesyntaxset isdisjoint(set ={ , , ={ , , bv prasanthi dept of cse page
25,485
print( isdisjoint( ) )issubset()this method returns true if all elements of one set is present in second set syntaxset issubset(set ={ , , ={ , , , print( issubset( )dictionariespython dictionary is an unordered collection of elements and it is mutable we can store values as pair of keys and values represented by dict(or {keys in dictionary are unique and they are immutable(strings,numbers,tuplescreating dictionary ={print(dd ={ :'ay', :'aa', :' 'print( ={' ': ,' ': ,' ': print( ={ : , :' ', :[ , , ], :( , , )#mixed dictoinary print( ={[ , , ]: ,' ': print( #error-keys are of immutable nature =dict([(' ', ),(' ', ),(' ', )]print(ddictionary operations )index:it is used to find the value at particular index syntaxdictname[index/keyexd={' ': ,' ': ,' ': print( [' ']#output: )len:it is used to find length of dictionary syntaxlen(dictnameexd={' ': ,' ': ,' ': print(len( )#output: )iteration:iteration is used to access the elements syntaxfor in dictnameexs={ : , : , : , : for in sbv prasanthi dept of cse page
25,486
print( [ ]output: )membership operatorthis operator returns boolean valuesto check whether the keys are present in dictionary or not exs={ : , : , : , : print( in sprint( not in sdictionary methods )keys():it returns keys from the dictionary syntaxdictname keys(exd ={' ': ,' ': ,' ': print( keys() )values():it returns values from the dictionary syntaxdictname values(exd ={' ': ,' ': ,' ': print( values() )get():this method is used to read the value at particular index exd ={' ': ,' ': ,' ': print( get(' ') )update():this method is used to change the values in dictionary syntaxolddict update(newdictexd={ :' ', :' ', :'th' ={ :'tw' update( print( )copy():this method is used to copy dictionary syntaxdictname copy(exd ={' ': ,' ': ,' ': = copy(print( )clear():it remove all the elements from dictionary syntaxdictname clear(bv prasanthi dept of cse page
25,487
exd={ :'one', :'two' clear(print( )pop():this method is used to remove the keys from dictionary syntaxdictname pop(keyexf={ :'app', :'man', :'stra' pop( print( #output{ :'man', :'stra'iterators and generators note:for clear explanation refer to iterators are containers for objects so that you can loop over the objects in other wordsyou can run the "forloop over the object there are many iterators in the python standard library for examplelist is an iterator and you can run for loop over list python generator gives us an easier way to create python iterators this is done by defining function but instead of the return statement returning from the functionuse the "yieldkeyword for examplesee how you can get simple vowel generator below comprehensions comprehensions in python provide us with short and concise way to construct new sequences (such as listssetdictionary etc using sequences which have been already defined comprehensions are of three typeslist comprehensions set comprehensions dict comprehensions list comprehensions were introduced in python while set and dict comprehensions have been introduced in python list comprehensions bv prasanthi dept of cse page
25,488
list comprehension is the most popular python comprehension it allows us to create new list of elements that satisfy condition from an iterable an iterable is any python construct that can be looped over like listsstringstuplessets in list comprehensions we use square brackets general syntax of list comprehension is as follows[expression for ele in iterable if cond for ele in iterable if cond for elen in iterablen if condnfollowing is an example of list comprehension for creating list of squares of numbers in range =[ * for in range( , )print(sin the previous examplewe can also use if condition to generate only squares of even numberss=[ * for in range( , if % == result of above comprehension will be[ set comprehensions set comprehensions were added to python in version in set comprehensionswe use the braces rather than square brackets for exampleto create the set of the squares of all numbers between and the following set comprehension can be usedx { ** for in range( )print(xoutputdict comprehensions just like set comprehensionsdict comprehensions were added to python in version below we create mapping of number to its square using dict comprehensionx { : ** for in range( )print( { bv prasanthi dept of cse page
25,489
introduction to functions function is block of organized and reusable program code that performs specificsingleand well-defined task function provides an interface for communication in terms of how information is transferred to it and how results are generated need for functions simplifies program development by making it easy to test separate functions understanding programs becomes easier libraries contain several functions which can be used in our programs to increase the productivity by dividing large program into smaller functionsdifferent programmers can work on different functions users can create their own functions and use them in various locations in the main program there are two types of functionsbuilt-in-functions user defined functions built-in functionspython interpreter has number of functions that are available for use they are called as bulit-in functions eginput(),print(),range(),abs(),len(),type(),sum(),sorted(),etc user defined functions defining functions function definition consists of function header that identifies the functionfollowed by the body of the function the body of function contains the code that is to be executed when function is called to define functionwe have to remember following pointsfunction definition starts with the keyword def the keyword def is followed by the function name and parentheses after parenthesesa colon (:should be placed parameters or arguments that the function accepts should be placed inside the parentheses function might have return statement bv prasanthi dept of cse page
25,490
the function code should indented properly function definition contains two partsfunction header function body the syntax of function definition is as followsdef function_name(arg arg /no arg)"""documentation string""statement block function header ,formal parameters body of function example for defining function without arguments is as followsdef sample()""this is sample program created by prashanthi""print("hello"print("python"example for defining function with arguments is as followsdef add( , )""this is sample program for addition""print( +bcalling function before calling functionit should be defined we call function to execute the code inside the function syntax for function call is as followsfunction_namefunction_name[arg arg function call,actual parameters egsample(add( ,bthe arguments or parameters passed in function call are called actual parameters the arguments used in the function header of function definition are called formal parameters when function is calledcontrol moves to the first line inside the function definition after the body of function definition is executedcontrol returns back to the next statement after the function call points to remember while calling functionbv prasanthi dept of cse page
25,491
the function name and number of parameters must be same in the function call and function definition when the number parameters passed doesn' match with the parameters in the function definitionerror is generated names of arguments in the function call and function definition can be different arguments can be passed as expressions the expression will get executed first and then the value is passed to the formal parameter the parameter list must be separated by commas if the function returns value it must be assigned to some variable in the calling function let' consider the following example which demonstrates function definition and function call#program without parameters def sample()""this is sample program created by prashanthi""print("hello"print("python"sample(#program with parameters def add( , )""this is sample program for addition""print( +ba= = add( , #different parameters in function header and function call def add( , )""this is sample program for addition""print( +ya= = add( ,bfunctions returning value(fruitful functionsa function may or may not return value to return valuewe must use return statement in the function definition every function by default contains an implicit return statement as the last line which returns none object to the calling function the functions which returns value is called fruitful functions return statement is used for two reasonsreturn value to the caller to end the execution of function and give control to caller the syntax of return statement is as followsreturn(bv prasanthi dept of cse page
25,492
return (expressionexample of function returning value is as followsdef cube( )return * * =int(input("enter the value of ") =cube(aprint("cube=",bdef sq( )return * =int(input("enter the value of ") =sq(xprint("square=",bpassing arguments if function definition contains argumentsthen in function call there is need to pass arguments for examplein the previous function definition of cubethere is single argument sowhile calling this function we need to pass single parameter the cube function can be called as followscube( in the above function call is the actual parameter positional arguments positional arguments are arguments that can be called by their position in the function definition first positional argument always needed to be listed first when the function is called second positional argument always needed to be listed second when the function is called and so on egdef ( , , )print( , , #output: ( , , def ( , , )print( * + #output: ( , , def ( , , )print( + /cf( , , def add( , )print( +ba= bv prasanthi dept of cse #output: page
25,493
= add( ,bdefault arguments the formal parameters in function definition can be assigned default value such parameters to which default values are assigned are called default arguments default value can be assigned to parameter by using the assignment operator function definition can have one or more default arguments default arguments allow function call to pass less parameters than the number of parameters in the function definition (no of parameters in function call and function header need not be samefollowing example demonstrates function with default arguments and its usagedef ( , = , = )print( , ,cf( #output: def ( , = , = )print( , ,cf( = #output: def ( , = , = )print( , ,cf( , #output: def ( , = , = )print( , ,cf( , = #output: def ( , = , = )print( , ,cf( , , #output: keyword arguments in generalwhen parameters are passed in function callthey are assigned to formal parameters based on their position such parameters are called positional parameters we can also pass the parameters based on the name (keywordof the parameter in the function definition such parameters are called keyword arguments points to remember when using keyword argumentsall keyword parameters must match one of the parameters in the function definition order of keyword arguments is not important value should not be passed more than once to keyword parameter bv prasanthi dept of cse page
25,494
following example demonstrates keyword arguments and their usedef ( , , )print( , , #output: ( , , def ( , , )print( , ,cf( = , = , = #output: def ( , , )print( , ,cf( = , = , = #output: def ( , , )print( , ,cf( , = , = #output: def ( , , )print( , ,cf( , , = #output: def ( , , )print( , ,cf( , = #output:error def ( , , )print( , ,cf( = , = , = #output:error variable-length arguments in some cases we cannot exactly tell how many parameters are needed in function definition in such cases we can use variable length arguments variable length arguments allows to pass random number of arguments in function call while creating variable-length argumentthe argument name must be preceded with symbol points to remember when working with variable-length argumentsthe random arguments passed to the function forms tuple for loop can be used to iterate over and access the elements in the variable-length argument variable-length argument should be at the end of the parameters list in the function definition other formal parameters written after variable-length argument must be keyword arguments only bv prasanthi dept of cse page
25,495
following example demonstrates variable-length argumentdef fun(name*friendslist)print("friends of",name,"are"for in friendslistprint(xend 'fun("shaa""ayaan""avi","velan"output of the above example is as followsfriends of shaa areayaan avi velan scope of variables variables in program has two thingsscopeparts of the program in which it is accessible lifetimehow long variable stays in the memory based on scope of variablethere are two types of variables global variables local variables following are the differences between global variable and local variableglobal variable local variable variable which is defined in the main body of the program file variable which is defined inside function accessible throughout the program file accessible from the point it is defined to the end of the block it is defined in accessible to all functions in the program they are not related in any way to other variables outside the function following example demonstrates local and global variablesx def fun() print("local =",xfun(print("global =",xbv prasanthi dept of cse page
25,496
output of above code is as followslocal global global statement local variable inside function can be made global by using the global keyword if local variable which is made global using the global statement have the same name as another global variablethen changes on the variable will be reflected everywhere in the program syntax of global statement is as followsglobal variable-name following example demonstrates global keywordx def fun()global print("local =",xfun(print("global =",xoutput of the above program islocal global in case of nested functionsinner function can access variables both outer and inner functions outer function can access variables defined only in the outer function anonymous functions or lambda functions functions that don' have any name are known as lambda or anonymous functions lambda functions are created using the keyword lambda lambda functions are one line functions that can be created and used anywhere function is required lambda is simply the name of letter 'lin the greek alphabet lambda function returns function object lambda function can be created as followslambda arguments-list expression bv prasanthi dept of cse page
25,497
the arguments-list contains comma separated list of arguments expression is an arithmetic expression that uses the arguments in the arguments-list lambda function can be assigned to variable to give it name following is an example for creating lambda function and using itpower lambda * * print(power( )#output: lambda print( ( )#output: lambda ab print( ( )#output: lambda abc print( ( )#output: in the above example the lambda function is assigned to power variable we can call the lambda function by writing power( )where is the argument that goes in to formal parameter points to remember when creating lambda functionslambda functions doesn' have any name lambda functions can take multiple arguments lambda functions can returns only one valuethe value of expression lambda function does not have any return statement lambda functions are one line functions lambda functions are not equivalent to inline functions in and +they cannot access variables other than those in the arguments lambda functions cannot even access global variables lambda functions can be passed as arguments in other functions lambda functions can be used in the body of regular functions lambda functions can be used without assigning it to variable we can pass lambda arguments to function we can create lambda function without any arguments we can nest lambda functions time taken by lambda function to execute is almost similar to regular functions recursive functions recursion is another way to repeat code in our programs recursive functions is function which calls itself recursive functions should contain two major partsbase condition parta condition which terminates recursion and returns the result recursive partcode which calls the function itself with reduced data or information bv prasanthi dept of cse page
25,498
recursion uses divide and conquer strategy to solve problems if > fact( )= *fact( - if = fact( )= !=fact( )= *fact( * *fact( * * *fact( * * * *fact( * * * * *fact( * * * * * = advantages recursive functions make the code look clean and easy complex task can be broken into sub problem using recursion sequence generation is easy disadvantages sometimes logic behind recursion is hard to follow recursive calls are expensive ,as they take lot of memory and time recursive functions are hard to debug following is an example for recursive function which calculates factorial of numberdef fact( )"""returns the factorial of number using recursion ""if == or == return elsereturn *fact( - =int(input("enter value")print("factorial=",fact( )in the above example test inside triple quotes is called docstring or documentation string the docstring of function can be printed by writing function_name __doc__ following is an example for recursive function which calculates gcd of two numbersdef gcd( , )rem % if rem = return elsereturn gcd(yrembv prasanthi dept of cse page
25,499
=int(input("enter the value of ") =int(input("enter the value of ")print("gcd of two numbers =",gcd( , )modulescreating modulesimport statementfrom import statementname spacing modules function allows to reuse piece of code module on the other hand contains multiple functionsvariablesand other elements which can be reused module is python file with py extension each py file can be treated as module creation of modulemymodule py def greeting(name)print("hellonameuse of moduleimport mymodule mymodule greeting("ayaan"output:hello,ayaan variables in module mymodule py person "name""python""age" "country""indiaimport statementimport keyword allows to use functions or variables available in module import mymodule mymodule person ["age"print(arenaming modulebv prasanthi dept of cse page