id
int64
0
25.6k
text
stringlengths
0
4.59k
24,900
/end class link in addition to the datathere' constructor and methoddisplaylink()that displays the link' data in the format { object purists would probably object to naming this method displaylink()arguing that it should be simply display(this would be in the spirit of polymorphismbut it makes the listing somewhat harder to understand when you see statement like current display()and you've forgotten whether current is link objecta linklist objector something else the constructor initializes the data there' no need to initialize the next fieldbecause it' automatically set to null when it' created (although it could be set to null explicitlyfor clarity the null value means it doesn' refer to anythingwhich is the situation until the link is connected to other links we've made the storage type of the link fields (idata and so onpublic if they were private we would need to provide public methods to access themwhich would require extra codethus making the listing longer and harder to read ideallyfor security we would probably want to restrict link-object access to methods of the linklist class howeverwithout an inheritance relationship between these classesthat' not very convenient we could use the default access specifier (no keywordto give the data package access (access restricted to classes in the same directorybut that has no effect in these demo programswhich only occupy one directory anyway the public specifier at least makes it clear that this data isn' private the linklist class the linklist class contains only one data itema reference to the first link on the list this reference is called first it' the only permanent information the list maintains about the location of any of the links it finds the other links by following the chain of references from firstusing each link' next field class linklist private link first/ref to first link on list /public void linklist(/constructor first null/no items on list yet /public boolean isempty(/true if list is empty return (first==null)
24,901
/other methods go here the constructor for linklist sets first to null this isn' really necessary because as we notedreferences are set to null automatically when they're created howeverthe explicit constructor makes it clear that this is how first begins when first has the value nullwe know there are no items on the list if there were any itemsfirst would contain reference to the first one the isempty(method uses this fact to determine whether the list is empty the insertfirst(method the insertfirst(method of linklist inserts new link at the beginning of the list this is the easiest place to insert linkbecause first already points to the first link to insert the new linkwe need only set the next field in the newly created link to point to the old first linkand then change first so it points to the newly created link this is shown in figure in insertfirst(we begin by creating the new link using the data passed as arguments then we change the link references as we just noted /insert at start of list public void insertfirst(int iddouble dd/make new link link newlink new link(iddd)newlink next first/newlink --old first first newlink/first --newlink the arrows --in the comments in the last two statements mean that link (or the first fieldconnects to the next (downstreamlink (in doubly linked lists we'll see upstream connections as wellsymbolized by <-arrows compare these two statements with figure make sure you understand how the statements cause the links to be changedas shown in the figure this kind of reference-manipulation is the heart of linked list algorithms the deletefirst(method the deletefirst(method is the reverse of insertfirst(it disconnects the first link by rerouting first to point to the second link this second link is found by looking at the next field in the first link public link deletefirst(link temp firstfirst first nextreturn temp/delete first item /(assumes list not empty/save reference to link /delete itfirst-->old next /return deleted link
24,902
the second statement is all you need to remove the first link from the list we choose to also return the linkfor the convenience of the user of the linked listso we save it in temp before deleting itand return the value of temp figure shows how first is rerouted to delete the object in +and similar languagesyou would need to worry about deleting the link itself after it was disconnected from the list it' in memory somewherebut now nothing refers to it what will become of itin javathe garbage collection process will destroy it at some point in the futureit' not your responsibility figure deleting link notice that the deletefirst(method assumes the list is not empty before calling ityour program should verify this with the isempty(method the displaylist(method to display the listyou start at first and follow the chain of references from link to link variable current points to (or technically refers toeach link in turn it starts off pointing to firstwhich holds reference to the first link the statement current current next
24,903
each link here' the entire displaylist(methodpublic void displaylist(system out print("list (first-->last)")link current first/start at beginning of list while(current !null/until end of listcurrent displaylink()/print data current current next/move to next link system out println("")the end of the list is indicated by the next field in the last link pointing to null rather than another link how did this field get to be nullit started that way when the link was created and was never given any other value because it was always at the end of the list the while loop uses this condition to terminate itself when it reaches the end of the list figure shows how current steps along the list at each linkthe displaylist(method calls the displaylink(method to display the data in the link the linklist java program listing shows the complete linklist java program you've already seen all the components except the main(routine figure stepping along the list listing the linklist java program /linklist java /demonstrates linked list /to run this programc>java linklistapp ///////////////////////////////////////////////////////////////class link
24,904
public int idatapublic double ddatapublic link next/data item (key/data item /next link in list /public link(int iddouble dd/constructor idata id/initialize data ddata dd/('nextis automatically /set to null/public void displaylink(/display ourself system out print("{idata "ddata "")/end class link ///////////////////////////////////////////////////////////////class linklist private link first/ref to first link on list /public linklist(/constructor first null/no items on list yet /public boolean isempty(/true if list is empty return (first==null)//insert at start of list public void insertfirst(int iddouble dd/make new link link newlink new link(iddd)newlink next first/newlink --old first first newlink/first --newlink /
24,905
link temp firstfirst first nextnext return temp/delete first item /(assumes list not empty/save reference to link /delete itfirst-->old /return deleted link /public void displaylist(system out print("list (first-->last)")link current first/start at beginning of list while(current !null/until end of listcurrent displaylink()/print data current current next/move to next link system out println("")//end class linklist ///////////////////////////////////////////////////////////////class linklistapp public static void main(string[argslinklist thelist new linklist()/make new list thelist insertfirst( )thelist insertfirst( )thelist insertfirst( )thelist insertfirst( )/insert four items thelist displaylist()/display list while!thelist isempty(/until it' emptylink alink thelist deletefirst()/delete link system out print("deleted ")/display it alink displaylink()system out println("")thelist displaylist()/display list /end main(/end class linklistapp
24,906
display it thenin the while loopwe remove the items one by one with deletefirst(until the list is empty the empty list is then displayed here' the output from linklist javalist (first-->last){ { { { deleted { deleted { deleted { deleted { list (first-->last)finding and deleting specified links our next example program adds methods to search linked list for data item with specified key valueand to delete an item with specified key value thesealong with insertion at the start of the listare the same operations carried out by the linklist workshop applet the complete linklist java program is shown in listing listing the linklist java program /linklist java /demonstrates linked list /to run this programc>java linklist app ///////////////////////////////////////////////////////////////class link public int idata/data item (keypublic double ddata/data item public link next/next link in list /public link(int iddouble dd/constructor idata idddata dd/public void displaylink(/display ourself system out print("{idata "ddata "")/end class link ///////////////////////////////////////////////////////////////class linklist private link first/ref to first link on list
24,907
/constructor first null/no links on list yet /public void insertfirst(int iddouble dd/make new link link newlink new link(iddd)newlink next first/it points to old first link first newlink/now first points to this /public link find(int key/find link with given key /(assumes non-empty listlink current first/start at 'firstwhile(current idata !key/while no matchif(current next =null/if end of listreturn null/didn' find it else /not end of listcurrent current next/go to next link return current/found it /public link delete(int key/delete link with given key /(assumes non-empty listlink current first/search for link link previous firstwhile(current idata !keyif(current next =nullreturn null/didn' find it else previous current/go to next link current current next/found it if(current =first/if first linkfirst first next/change first else /otherwiseprevious next current next/bypass it return current
24,908
/public void displaylist(/display the list system out print("list (first-->last)")link current first/start at beginning of list while(current !null/until end of listcurrent displaylink()/print data current current next/move to next link system out println("")//end class linklist ///////////////////////////////////////////////////////////////class linklist app public static void main(string[argslinklist thelist new linklist()/make list thelist insertfirst( )thelist insertfirst( )thelist insertfirst( )thelist insertfirst( )/insert items thelist displaylist()/display list link thelist find( )/find item iff !nullsystem out println("found link with key idata)else system out println("can' find link")link thelist delete( )/delete item ifd !null system out println("deleted link with key idata)else system out println("can' delete link")thelist displaylist()/display list /end main(/end class linklist app the main(routine makes listinserts four itemsand displays the resulting list it then searches for the item with key deletes the item with key and displays the list
24,909
list (first-->last){ { { { found link with key deleted link with key list (first-->last){ { { the find(method the find(method works much like the displaylist(method seen in the last program the reference current initially points to firstand then steps its way along the links by setting itself repeatedly to current next at each linkfind(checks if that link' key is the one it' looking for if it isit returns with reference to that link if it reaches the end of the list without finding the desired linkit returns null the delete(method the delete(method is similar to find(in the way it searches for the link to be deleted howeverit needs to maintain reference not only to the current link (current)but to the link preceding the current link (previousthis is becauseif it deletes the current linkit must connect the preceding link to the following linkas shown in figure the only way to tell where the preceding link isis to maintain reference to it at each cycle through the while loopjust before current is set to current nextprevious is set to current this keeps it pointing at the link preceding current to delete the current link once it' foundthe next field of the previous link is set to the next link special case arises if the current link is the first link because the first link is pointed to by the linklist' first field and not by another link in this case the link is deleted by changing first to point to first nextas we saw in the last program with the deletefirst(method here' the code that covers these two possibilities/found it if(current =firstfirst first next/if first link/change first else /otherwiseprevious next current next/bypass link other methods we've seen methods to insert and delete items at the start of list and to find specified item and delete specified item you can imagine other useful list methods for examplean insertafter(method could find link with specified key value and insert new link following it we'll see such method when we talk about list iterators at the end of this
24,910
double-ended lists double-ended list is similar to an ordinary linked listbut it has one additional featurea reference to the last link as well as to the first figure shows what this looks like figure double-ended list the reference to the last link permits you to insert new link directly at the end of the list as well as at the beginning of course you can insert new link at the end of an ordinary single-ended list by iterating through the entire list until you reach the endbut this is inefficient access to the end of the list as well as the beginning makes the double-ended list suitable for certain situations that single-ended list can' handle efficiently one such situation is implementing queuewe'll see how this works in the next section listing contains the firstlastlist java programwhich demonstrates doubleended list (incidentallydon' confuse the double-ended list with the doubly linked listwhich we'll explore later in this listing the firstlastlist java program /firstlastlist java /demonstrates list with first and last references /to run this programc>java firstlastapp ///////////////////////////////////////////////////////////////class link public double ddata/data item public link next/next link in list /
24,911
ddata /constructor /public void displaylink(/display this link system out print(ddata ")//end class link ///////////////////////////////////////////////////////////////class firstlastlist private link firstprivate link last/ref to first link /ref to last link /public firstlastlist(/constructor first null/no links on list yet last null/public boolean isempty(/true if no links return first==null/public void insertfirst(double dd/insert at front of list link newlink new link(dd)/make new link ifisempty(last newlinknewlink next firstfirst newlink/if empty list/newlink <-last /newlink --old first /first --newlink /public void insertlast(double dd/insert at end of list link newlink new link(dd)/make new link ifisempty(first newlinkelse last next newlink/if empty list/first --newlink /old last --newlink
24,912
/newlink <-last /public double deletefirst(/delete first link /(assumes non-empty listdouble temp first ddata/save the data if(first next =null/if only one item last null/null <-last first first next/first --old next return temp/public void displaylist(system out print("list (first-->last)")link current first/start at beginning while(current !null/until end of listcurrent displaylink()/print data current current next/move to next link system out println("")//end class firstlastlist ///////////////////////////////////////////////////////////////class firstlastapp public static void main(string[args/make new list firstlastlist thelist new firstlastlist()thelist insertfirst( )thelist insertfirst( )thelist insertfirst( )/insert at front thelist insertlast( )thelist insertlast( )thelist insertlast( )/insert at rear thelist displaylist()/display the list thelist deletefirst()thelist deletefirst()/delete first two items
24,913
/end main(/display again /end class firstlastapp for simplicityin this program we've reduced the number of data items in each link from two to one this makes it easier to display the link contents (remember that in serious program there would be many more data itemsor reference to another object containing many data items this program inserts three items at the front of the listinserts three more at the endand displays the resulting list it then deletes the first two items and displays the list again here' the outputlist (first-->last) list (first-->last) notice how repeated insertions at the front of the list reverse the order of the itemswhile repeated insertions at the end preserve the order the double-ended list class is called the firstlastlist as discussedit has two data itemsfirst and lastwhich point to the first item and the last item in the list if there is only one item in the listthen both first and last point to itand if there are no itemsthey are both null the class has new methodinsertlast()that inserts new item at the end of the list this involves modifying last next to point to the new linkand then changing last to point to the new linkas shown in figure figure insertion at the end of list the insertion and deletion routines are similar to those in single-ended list howeverboth insertion routines must watch out for the special case when the list is empty prior to the insertion that isif isempty(is truethen insertfirst(must set last to the new linkand insertlast(must set first to the new link if inserting at the beginning with insertfirst()first is set to point to the new linkalthough when inserting at the end with insertlast()last is set to point to the new link deleting from the start of the list is also special case if it' the last item on the listlast must be set to point to null in this case
24,914
there is still no reference to the next-to-last linkwhose next field would need to be changed to null if the last link were deleted to conveniently delete the last linkyou would need doubly linked listwhich we'll look at soon (of courseyou could also traverse the entire list to find the last linkbut that' not very efficient linked-list efficiency insertion and deletion at the beginning of linked list are very fast they involve changing only one or two referenceswhich takes ( time findingdeletingor insertion next to specific item requires searching throughon the averagehalf the items in the list this requires (ncomparisons an array is also (nfor these operationsbut the linked list is nevertheless faster because nothing needs to be moved when an item is inserted or deleted the increased efficiency can be significantespecially if copy takes much longer than comparison of courseanother important advantage of linked lists over arrays is that the linked list uses exactly as much memory as it needsand can expand to fill all of the available memory the size of an array is fixed when it' createdthis usually leads to inefficiency because the array is too largeor to running out of room because the array is too small vectorswhich are expandable arraysmay solve this problem to some extentbut they usually expand in fixed-sized increments (such as doubling the size of the array whenever it' about to overflowthis is still not as efficient use of memory as linked list abstract data types in this section we'll shift gears and discuss topic that' more general than linked listsabstract data types (adtswhat is an adtroughly speakingit' way of looking at data structurefocusing on what it doesand ignoring how it does it stacks and queues are examples of adts we've already seen that both stacks and queues can be implemented using arrays before we return to discussion of adtslet' see how stacks and queues can be implemented using linked lists this will demonstrate the "abstractnature of stacks and queueshow they can be considered separately from their implementation stack implemented by linked list when we created stack in the last we used an ordinary java array to hold the stack' data the stack' push(and pop(operations were actually carried out by array operations such as arr[++topdataand data arr[top--]which insert data intoand take it out ofan array we can also use linked list to hold stack' data in this case the push(and pop(operations would be carried out by operations like thelist insertfirst(data
24,915
data thelist deletefirst(the user of the stack class calls push(and pop(to insert and delete itemswithout knowingor needing to knowwhether the stack is implemented as an array or as linked list listing shows how stack class called linkstack can be implemented using the linklist class instead of an array (object purists would argue that the name linkstack should be simply stackbecause users of this class shouldn' need to know that it' implemented as list listing the linkstack(program /linkstack java /demonstrates stack implemented as list /to run this programc>java linkstackapp import java io */for / ///////////////////////////////////////////////////////////////class link public double ddata/data item public link next/next link in list /public link(double dd/constructor ddata dd/public void displaylink(/display ourself system out print(ddata ")/end class link ///////////////////////////////////////////////////////////////class linklist private link first/ref to first item on list /public linklist(/constructor first null/no items on list yet /public boolean isempty(/true if list is empty return (first==null)/public void insertfirst(double dd/insert at start of list
24,916
/make new link link newlink new link(dd)newlink next first/newlink --old first first newlink/first --newlink /public double deletefirst(/delete first item /(assumes list not emptylink temp first/save reference to link first first next/delete itfirst-->old next return temp ddata/return deleted link /public void displaylist(link current first/start at beginning of list while(current !null/until end of listcurrent displaylink()/print data current current next/move to next link system out println("")//end class linklist ///////////////////////////////////////////////////////////////class linkstack private linklist thelist//public linkstack(/constructor thelist new linklist()//public void push(double /put item on top of stack thelist insertfirst( )/
24,917
/take item from top of stack return thelist deletefirst()//public boolean isempty(/true if stack is empty return thelist isempty()//public void displaystack(system out print("stack (top-->bottom)")thelist displaylist()///end class linkstack ///////////////////////////////////////////////////////////////class linkstackapp public static void main(string[argsthrows ioexception linkstack thestack new linkstack()/make stack thestack push( )thestack push( )/push items thestack displaystack()/display stack thestack push( )thestack push( )/push items thestack displaystack()/display stack thestack pop()thestack pop()/pop items thestack displaystack()/end main(/display stack /end class linkstackapp the main(routine creates stack objectpushes two items on itdisplays the stackpushes two more itemsand displays it again finally it pops two items and displays the stack again here' the output
24,918
stack (top-->bottom) stack (top-->bottom) notice the overall organization of this program the main(routine in the linkstackapp class relates only to the linkstack class the linkstack class relates only to the linklist class there' no communication between main(and the linklist class more specificallywhen statement in main(calls the push(operation in the linkstack classthis method in turn calls insertfirst(in the linklist class to sactually insert data similarlypop(calls deletefirst(to delete an itemand displaystack(calls displaylist(to display the stack to the class userwriting code in main()there is no difference between using the list-based linkstack class and using the array-based stack class from the stack java program in queue implemented by linked list here' similar example of an adt implemented with linked list listing shows queue implemented as double-ended linked list listing the linkqueue(program /linkqueue java /demonstrates queue implemented as double-ended list /to run this programc>java linkqueueapp import java io */for / ///////////////////////////////////////////////////////////////class link public double ddata/data item public link next/next link in list /public link(double /constructor ddata /public void displaylink(/display this link system out print(ddata ")//end class link ///////////////////////////////////////////////////////////////class firstlastlist private link firstprivate link last/ref to first item /ref to last item
24,919
/constructor first null/no items on list yet last null/public boolean isempty(/true if no links return first==null/public void insertlast(double dd/insert at end of list link newlink new link(dd)/make new link ifisempty(/if empty listfirst newlink/first --newlink else last next newlink/old last --newlink last newlink/newlink <-last /public double deletefirst(/delete first link /(assumes non-empty listdouble temp first ddataif(first next =null/if only one item last null/null <-last first first next/first --old next return temp/public void displaylist(link current first/start at beginning while(current !null/until end of listcurrent displaylink()/print data current current next/move to next link system out println("")//end class firstlastlist ///////////////////////////////////////////////////////////////
24,920
private firstlastlist thelist//public linkqueue(/constructor thelist new firstlastlist()/make -ended list //public boolean isempty(/true if queue is empty return thelist isempty()//public void insert(double /insertrear of queue thelist insertlast( )//public double remove(/removefront of queue return thelist deletefirst()//public void displayqueue(system out print("queue (front-->rear)")thelist displaylist()///end class linkqueue ///////////////////////////////////////////////////////////////class linkqueueapp public static void main(string[argsthrows ioexception linkqueue thequeue new linkqueue()thequeue insert( )/insert items thequeue insert( )
24,921
thequeue displayqueue()/display queue thequeue insert( )thequeue insert( )/insert items thequeue displayqueue()/display queue thequeue remove()thequeue remove()/remove items thequeue displayqueue()/end main(/display queue /end class linkqueueapp the program creates queueinserts two itemsinserts two more itemsand removes two itemsfollowing each of these operations the queue is displayed here' the outputqueue (front-->rear) queue (front-->rear) queue (front-->rear) here the methods insert(and remove(in the linkqueue class are implemented by the insertlast(and deletefirst(methods of the firstlastlist class we've substituted linked list for the array used to implement the queue in the queue program of the linkstack and linkqueue programs emphasize that stacks and queues are conceptual entitiesseparate from their implementations stack can be implemented equally well by an array or by linked list what' important about stack is the push(and pop(operations and how they're usedit' not the underlying mechanism used to implement these operations when would you use linked list as opposed to an array as the implementation of stack or queueone consideration is how accurately you can predict the amount of data the stack or queue will need to hold if this isn' clearthe linked list gives you more flexibility than an array both are fastso that' probably not major consideration data types and abstraction where does the term abstract data type come fromlet' look at the "data typepart of it firstand then return to "abstract data types the phrase "data typecovers lot of ground it was first applied to built-in types such as int and double this is probably what you first think of when you hear the term when you talk about primitive typeyou're actually referring to two thingsa data item with certain characteristicsand permissible operations on that data for exampletype int variables in java can have whole-number values between - , , , and + , , , and the operators +-*/and so on can be applied to them the data type' permissible operations are an inseparable part of its identityunderstanding the type means understanding what operations can be performed on it with the advent of object-oriented programmingit became possible to create your own
24,922
are used in ways similar to primitive types you canfor exampledefine class for time (with fields for hoursminutesseconds) class for fractions (with numerator and denominator fields)and class for extra-long numbers (characters in string represent the digitsall these can be added and subtracted like int and doubleexcept that in java you must use methods with functional notation like add(and sub(rather than operators like and the phrase "data typeseems to fit naturally with such quantity-oriented classes howeverit is also applied to classes that don' have this quantitative aspect in factany class represents data typein the sense that class comprises data (fieldsand permissible operations on that data (methodsby extensionwhen data storage structure like stack or queue is represented by classit too can be referred to as data type stack is different in many ways from an intbut they are both defined as certain arrangement of data and set of operations on that data abstraction the word abstract means "considered apart from detailed specifications or implementation an abstraction is the essence or important characteristics of something the office of presidentfor exampleis an abstractionconsidered apart from the individual who happens to occupy that office the powers and responsibilities of the office remain the samewhile individual office-holders come and go in object-oriented programmingthenan abstract data type is class considered without regard to its implementation it' description of the data in the class (fields) list of operations (methodsthat can be carried out on that dataand instructions on how to use these operations specifically excluded are the details of how the methods carry out their tasks as class useryou're told what methods to callhow to call themand the results you can expectbut not how they work the meaning of abstract data type is further extended when it' applied to data structures like stacks and queues as with any classit means the data and the operations that can be performed on itbut in this context even the fundamentals of how the data is stored become invisible to the user users not only don' know how the methods workthey also don' know what structure is used to store the data for the stackthe user knows that push(and pop((and perhaps few other methodsexist and how they work the user doesn' (at least not usuallyneed to know how push(and pop(workor whether data is stored in an arraya linked listor some other data structure like tree the interface an adt specification is often called an interface it' what the class user seesusually its public methods in stack classpush(and pop(and similar methods form the interface adt lists now that we know what an abstract data type iswe can mention another onethe list list (sometimes called linear listis group of items arranged in linear order that isthey're lined up in certain waylike beads on string or houses on street lists support certain fundamental operations you can insert an itemdelete an itemand usually read an item from specified location (the third itemsaydon' confuse the adt list with the linked list we've been discussing in this list
24,923
be implemented by various structuresincluding arrays and linked lists the list is an abstraction of such data structures adts as design tool the adt concept is useful aid in the software design process if you need to store datastart by considering the operations that need to be performed on that data do you need access to the last item insertedthe first onean item with specified keyan item in certain positionanswering such questions leads to the definition of an adt only after the adt is completely defined should you worry about the details of how to represent the data and how to code the methods that access the data by decoupling the specification of the adt from the implementation detailsyou can simplify the design process you also make it easier to change the implementation at some future time if the users relate only to the adt interfaceyou should be able to change the implementation without "breakingthe user' code of courseonce the adt has been designedthe underlying data structure must be carefully chosen to make the specified operations as efficient as possible if you need random access to element nfor examplethen the linked-list representation isn' so good because random access isn' an efficient operation for linked list you' be better off with an array it' all relative remember that the adt concept is only conceptual tool data storage structures are not divided cleanly into some that are adts and some that are used to implement adts linked listfor exampledoesn' need to be wrapped in list interface to be usefulit can act as an adt on its ownor it can be used to implement another data type such as queue linked list can be implemented using an arrayand an array-type structure can be implemented using linked list what' an adt and what' more basic structure must be determined in given context sorted lists in linked lists we've seen thus farthere was no requirement that data be stored in order howeverfor certain applications it' useful to maintain the data in sorted order within the list list with this characteristic is called sorted list in sorted listthe items are arranged in sorted order by key value deletion is often limited to the smallest (or the largestitem in the listwhich is at the start of the listalthough sometimes find(and delete(methodswhich search through the list for specified linksare used as well in general you can use sorted list in most situations where you use sorted array the advantages of sorted list over sorted array are speed of insertion (because elements don' need to be movedand the fact that list can expand to fill available memorywhile an array is limited to fixed size howevera sorted list is somewhat more difficult to implement than sorted array later we'll look at one application for sorted listssorting data sorted list can also be used to implement priority queuealthough heap (see is more common implementation the linklist workshop applet the linklist workshop applet introduced at the beginning of this demonstrates sorted as well as unsorted lists use the new button to create new list with about
24,924
sorted orderas shown in figure figure the linklist workshop applet with sorted list figure newly inserted link use the ins button to insert new item type in value that will fall somewhere in the middle of the list watch as the algorithm traverses the linkslooking for the appropriate insertion place when it finds itit inserts the new linkas shown in figure with the next press of insthe list will be redrawn to regularize its appearance you can also find specified link using the find buttonand delete specified link using the del button java code to insert an item in sorted list to insert an item in sorted listthe algorithm must first search through the list until it finds the appropriate place to put the itemthis is just before the first item that' largeras shown in figure once the algorithm finds where to put itthe item can be inserted in the usual way by changing next in the new link to point to the next linkand changing next in the previous link to point to the new link howeverthere are some special cases to considerthe link might need to be inserted at the beginning of the listor it might need to go at the end let' look at the codepublic void insert(double key/insert in order link newlink new link(key)/make new link
24,925
link current first/start at first /until end of listwhile(current !null &key current ddata/or key currentprevious currentcurrent current next/go to next item if(previous==null/at beginning of list first newlink/first --newlink else /not at beginning previous next newlink/old prev --newlink newlink next current/newlink --old currnt /end insert(we need to maintain previous reference as we move alongso we can modify the previous link' next field to point to the new link after creating the new linkwe prepare to search for the insertion point by setting current to first in the usual way we also set previous to nullthis is important because later we'll use this null value to determine whether we're still at the beginning of the list the while loop is similar to those we've used before to search for the insertion pointbut there' an added condition the loop terminates when the key of the link currently being examined (current ddatais no longer smaller than the key of the link being inserted (key)this is the most usual casewhere key is inserted somewhere in the middle of the list howeverthe while loop also terminates if current is null this happens at the end of the list (the next field of the last element is null)or if the list is empty to begin with (first is nullonce the while loop terminateswe may be at the beginningthe middleor the end of the listor the list may be empty if we're at the beginning or the list is emptyprevious will be nullso we set first to the new link otherwisewe're in the middle of the list or at the endand we set previous next to the new link in any case we set the new link' next field to current if we're at the end of the listcurrent is nullso the new link' next field is appropriately set to this value the sortedlist java program the sortedlist java example shown in listing presents sortedlist class with insert()remove()and displaylist(methods only the insert(routine is different from its counterpart in nonsorted lists listing the sortedlist java program /sortedlist java /demonstrates sorted list /to run this programc>java sortedlistapp
24,926
/for / ///////////////////////////////////////////////////////////////class link public double ddata/data item public link next/next link in list /public link(double dd/constructor ddata dd/public void displaylink(/display this link system out print(ddata ")/end class link ///////////////////////////////////////////////////////////////class sortedlist private link firstlist /ref to first item on /public sortedlist(/constructor first null/public boolean isempty(/true if no links return (first==null)/public void insert(double key/insert in order link newlink new link(key)/make new link link previous null/start at first link current first/until end of listwhile(current !null &key current ddata/or key currentprevious currentcurrent current next/go to next item if(previous==null/at beginning of list first newlink/first --newlink else /not at beginning previous next newlink/old prev --newlink newlink next current/newlink --old currnt /end insert(
24,927
/return delete first link /(assumes non-empty listlink temp first/save first first first next/delete first return temp/return value /public void displaylist(system out print("list (first-->last)")link current first/start at beginning of list while(current !null/until end of listcurrent displaylink()/print data current current next/move to next link system out println("")/end class sortedlist ///////////////////////////////////////////////////////////////class sortedlistapp public static void main(string[args/create new list sortedlist thesortedlist new sortedlist()thesortedlist insert( )/insert items thesortedlist insert( )thesortedlist displaylist()/display list thesortedlist insert( )thesortedlist insert( )thesortedlist insert( )/insert more items thesortedlist displaylist()/display list thesortedlist remove()/remove an item thesortedlist displaylist()/display list /end main(/end class sortedlistapp in main(we insert two items with key values and then we insert three more itemswith values and these are inserted at the beginning of the listin the middleand at the endshowing that the insert(routine correctly handles these special cases finallywe remove one item to show removal is always from the front of
24,928
sortedlist javalist (first-->last) list (first-->last) list (first-->last) efficiency of sorted linked lists insertion and deletion of arbitrary items in the sorted linked list require (ncomparisons ( / on the averagebecause the appropriate location must be found by stepping through the list howeverthe minimum value can be foundor deletedin ( time because it' at the beginning of the list if an application frequently accesses the minimum item and fast insertion isn' criticalthen sorted linked list is an effective choice list insertion sort sorted list can be used as fairly efficient sorting mechanism suppose you have an array of unsorted data items if you take the items from the array and insert them one by one into the sorted listthey'll be placed in sorted order automatically if you then remove them from the list and put them back in the arraythey array will be sorted it turns out this is substantially more efficient than the more usual insertion sort within an arraydescribed in this is because fewer copies are necessary it' still an ( processbecause inserting each item into the sorted list involves comparing new item with an average of half the items already in the listand there are items to insert resulting in about / comparisons howevereach item is only copied twiceonce from the array to the listand once from the list to the array copies compare favorably with the insertion sort within an arraywhere there are about copies listing shows the listinsertionsort java programwhich starts with an array of unsorted items of type linkinserts them into sorted list (using constructor)and then removes them and places them back into the array listing the listinsertionsort java program /listinsertionsort java /demonstrates sorted list used for sorting /to run this programc>java listinsertionsortapp import java io */for / ///////////////////////////////////////////////////////////////class link public double ddata/data item public link next/next link in list /public link(double dd/constructor ddata dd//end class link
24,929
class sortedlist private link first/ref to first item on list /public sortedlist(/constructor (no argsfirst null/public sortedlist(link[linkarr/constructor (array as /argumentfirst null;/initialize list for(int = <linkarr lengthj++/copy array insertlinkarr[ )/to list /public void insert(link /insertin order link previous null/start at first link current first/until end of listwhile(current !null & ddata current ddata/or key currentprevious currentcurrent current next/go to next item if(previous==null/at beginning of list first /first -- else /not at beginning previous next /old prev -- next current/ --old current /end insert(/public link remove(/return delete first link /(assumes non-empty listlink temp first/save first first first next/delete first return temp/return value //end class sortedlist ///////////////////////////////////////////////////////////////
24,930
public static void main(string[argsint size /create array of links link[linkarray new link[size]for(int = <sizej++/fill array with links /random number int (int)(java lang math random()* )link newlink new link( )/make link linkarray[jnewlink/put in array /display array contents system out print("unsorted array")for(int = <sizej++system out printlinkarray[jddata )system out println("")/create new list/initialized with array sortedlist thesortedlist new sortedlist(linkarray)for(int = <sizej++/links from list to array linkarray[jthesortedlist remove()/display array contents system out print("sorted array")for(int = <sizej++system out print(linkarray[jddata ")system out println("")/end main(/end class listinsertionsortapp this program displays the values in the array before the sorting operationand again afterward here' some sample outputunsorted array sorted array the output will be different each time because the initial values are generated randomly new constructor for sortedlist takes an array of link objects as an argument and inserts the entire contents of this array into the newly created list this helps make things easier for the client (the main(routinewe've also made change to the insert(routine in this program it now accepts link object as an argumentrather than double we do this so we can store link objects in the array and insert them directly into the list in the sortedlist java programit was more convenient to have the insert(routine create each link objectusing the double value passed as an argument
24,931
it takes somewhat more than twice as much memorythe array and linked list must be in memory at the same time howeverif you have sorted linked list class handythe list insertion sort is convenient way to sort arrays that aren' too large doubly linked lists let' examine another variation on the linked listthe doubly linked list (not to be confused with the double-ended listwhat' the advantage of doubly linked lista potential problem with ordinary linked lists is that it' difficult to traverse backward along the list statement like current=current next steps conveniently to the next linkbut there' no corresponding way to go to the previous link depending on the applicationthis could pose problems for exampleimagine text editor in which linked list is used to store the text each text line on the screen is stored as string object embedded in link when the editor' user moves the cursor downward on the screenthe program steps to the next link to manipulate or display the new line but what happens if the user moves the cursor upwardin an ordinary linked listyou' need to return current (or its equivalentto the start of the list and then step all the way down again to the new current link this isn' very efficient you want to make single step upward the doubly linked list provides this capability it allows you to traverse backward as well as forward through the list the secret is that each link has two references to other links instead of one the first is to the next linkas in ordinary lists the second is to the previous link this is shown in figure the beginning of the specification for the link class in doubly linked list looks like thisclass link public double ddatapublic link nextpublic link previous/data item /next link in list /previous link in list figure doubly linked list the downside of doubly linked lists is that every time you insert or delete link you must deal with four links instead of twotwo attachments to the previous link and two attachments to the following one alsoof courseeach link is little bigger because of the extra reference doubly linked list doesn' necessarily need to be double-ended list (keeping
24,932
example we'll show the complete listing for the doublylinked java program soonbut first let' examine some of the methods in its doublylinkedlist class traversal two display methods demonstrate traversal of doubly linked list the displayforward(method is the same as the displaylist(method we've seen in ordinary linked lists the displaybackward(method is similarbut starts at the last element in the list and proceeds toward the start of the listgoing to each element' previous field this code fragment shows how this workslink current lastwhile(current !nullcurrent current previous/start at end /until start of list/move to previous link incidentallysome people take the view thatbecause you can go either way equally easily on doubly linked listthere is no preferred direction and therefore terms like previous and next are inappropriate if you preferyou can substitute direction-neutral terms such as left and right figure insertion at the beginning insertion we've included several insertion routines in the doublylinkedlist class the insertfirst(method inserts at the beginning of the listinsertlast(inserts at the endand insertafter(inserts following an element with specified key unless the list is emptythe insertfirst(routine changes the previous field in the old first link to point to the new linkand changes the next field in the new link to point to the old first link finally it sets first to point to the new link this is shown in figure if the list is emptythen the last field must be changed instead of the first previous field here' the codeifisempty(/if empty list
24,933
else first previous newlinknewlink next firstfirst newlink/newlink <-last /newlink <-old first /newlink --old first /first --newlink the insertlast(method is the same process applied to the end of the listit' mirror image of insertfirst(the insertafter(method inserts new link following the link with specified key value it' bit more complicated because four connections must be made first the link with the specified key value must be found this is handled the same way as the find(routine in the linklist program earlier in this thenassuming we're not at the end of the listtwo connections must be made between the new link and the next linkand two more between current and the new link this is shown in figure figure insertion at an arbitrary location if the new link will be inserted at the end of the listthen its next field must point to nulland last must point to the new link here' the insertafter(code that deals with the linksif(current==last/if last linknewlink next null/newlink --null last newlink/newlink <-last else /not last linknewlink next current next/newlink --old next /newlink <-old next current next previous newlinknewlink previous current/old current <-newlink current next newlink/old current --newlink perhaps you're unfamiliar with the use of two dot operators in the same expression it' natural extension of single dot operator the expression
24,934
means the previous field of the link referred to by the next field in the link current deletion there are three deletion routinesdeletefirst()deletelast()and deletekey(the first two are fairly straightforward in deletekey()the key being deleted is current assuming the link to be deleted is neither the first nor the last one in the listthen the next field of current previous (the link before the one being deletedis set to point to current next (the link following the one being deleted)and the previous field of current next is set to point to current previous this disconnects the current link from the list figure shows how this disconnection looksand the following two statements carry it outfigure deleting an arbitrary link current previous next current nextcurrent next previous current previousspecial cases arise if the link to be deleted is either the first or last in the listbecause first or last must be set to point to the next or the previous link here' the code from deletekey(for dealing with link connectionsif(current==firstfirst current nextelse /first item/first --old next /not first /old previous --old next current previous next current nextif(current==lastlast current previouselse /last item/old previous <-last /not last /old previous <-old next current next previous current previousthe doublylinked java program listing shows the complete doublylinked java programwhich includes all the routines just discussed listing the doublylinked java program
24,935
/demonstrates doubly-linked list /to run this programc>java doublylinkedapp ///////////////////////////////////////////////////////////////class link public double ddata/data item public link next/next link in list public link previous/previous link in list /public link(double /constructor ddata /public void displaylink(/display this link system out print(ddata ")//end class link ///////////////////////////////////////////////////////////////class doublylinkedlist private link firstprivate link last/ref to first item /ref to last item /public doublylinkedlist(/constructor first null/no items on list yet last null/public boolean isempty(/true if no links return first==null/public void insertfirst(double dd/insert at front of list link newlink new link(dd)/make new link ifisempty(/if empty listlast newlink/newlink <-last else first previous newlink/newlink <-old first newlink next first/newlink --old first
24,936
/first --newlink /public void insertlast(double dd/insert at end of list link newlink new link(dd)/make new link ifisempty(/if empty listfirst newlink/first --newlink else last next newlink/old last --newlink newlink previous last/old last <-newlink last newlink/newlink <-last /public link deletefirst(/delete first link /(assumes non-empty listlink temp firstif(first next =null/if only one item last null/null <-last else first next previous null/null <-old next first first next/first --old next return temp/public link deletelast(/delete last link /(assumes non-empty listlink temp lastif(first next =null/if only one item first null/first --null else last previous next null/old previous --null last last previous/old previous <-last return temp//insert dd just after key public boolean insertafter(double keydouble dd/(assumes non-empty listlink current first/start at beginning while(current ddata !key/until match is found
24,937
current current nextif(current =nullreturn falselink newlink new link(dd)/move to next link /didn' find it /make new link if(current==last/if last linknewlink next null/newlink --null last newlink/newlink <-last else /not last linknewlink next current next/newlink --old next /newlink <-old next current next previous newlinknewlink previous current/old current <-newlink current next newlink/old current --newlink return true/found itdid insertion /public link deletekey(double key/delete item wgiven key /(assumes non-empty listlink current first/start at beginning while(current ddata !key/until match is foundcurrent current next/move to next link if(current =nullreturn null/didn' find it if(current==first/found itfirst itemfirst current next/first --old next else /not first /old previous --old next current previous next current nextif(current==lastlast current previouselse next /last item/old previous <-last /not last /old previous <-old current next previous current previousreturn current/return value /
24,938
system out print("list (first-->last)")link current first/start at beginning while(current !null/until end of listcurrent displaylink()/display data current current next/move to next link system out println("")/public void displaybackward(system out print("list (last-->first)")link current last/start at end while(current !null/until start of listcurrent displaylink()/display data current current previous/move to previous link system out println("")//end class doublylinkedlist ///////////////////////////////////////////////////////////////class doublylinkedapp public static void main(string[args/make new list doublylinkedlist thelist new doublylinkedlist()thelist insertfirst( )thelist insertfirst( )thelist insertfirst( )/insert at front thelist insertlast( )thelist insertlast( )thelist insertlast( )/insert at rear thelist displayforward()thelist displaybackward()/display list forward /display list backward thelist deletefirst()thelist deletelast()thelist deletekey( )/delete first item /delete last item /delete item with key
24,939
thelist displayforward()/display list forward thelist insertafter( )thelist insertafter( )/insert after /insert after thelist displayforward()/end main(/display list forward /end class doublylinkedapp in main(we insert some items at the beginning of the list and at the enddisplay the items going both forward and backwarddelete the first and last items and the item with key display the list again (forward only)insert two items using the insertafter(methodand display the list again here' the outputlist (first-->last) list (last-->first) list (first-->last) list (first-->last) the deletion methods and the insertafter(method assume that the list isn' empty although for simplicity we don' show it in main()isempty(should be used to verify that there' something in the list before attempting such insertions and deletions doubly linked list as basis for deques doubly linked list can be used as the basis for dequementioned in the last in deque you can insert and delete at either endand the doubly linked list provides this capability iterators we've seen how it' possible for the user of list to find link with given key using find(method the method starts at the beginning of the list and examines each link until it finds one matching the search key other operations we've looked atsuch as deleting specified link or inserting before or after specified linkalso involve searching through the list to find the specified link howeverthese methods don' give the user any control over the traversal to the specified item suppose you wanted to traverse listperforming some operation on certain links for exampleimagine personnel file stored as linked list you might want to increase the wages of all employees who were being paid minimum wagewithout affecting employees already above the minimum or suppose that in list of mail-order customersyou decided to delete all customers who had not ordered anything in six months in an arraysuch operations are easy because you can use an array index to keep track of your position you can operate on one itemthen increment the index to point to the next itemand see if that item is suitable candidate for the operation howeverin linked listthe links don' have fixed index numbers how can we provide list' user with something analogous to an array indexyou could repeatedly use find(to look for appropriate items in listbut this requires many comparisons to find each link it' far more efficient to step from link to linkchecking if each one meets certain criteria and performing the appropriate operation if it does reference in the list itself
24,940
arbitrary link this allows us to examine or modify the link we should be able to increment the reference so we can traverse along the listlooking at each link in turnand we should be able to access the link pointed to by the reference assuming we create such referencewhere will it be installedone possibility is to use field in the list itselfcalled current or something similar you could access link using currentand increment current to move to the next link one trouble with this approach is that you might need more than one such referencejust as you often use several array indices at the same time how many would be appropriatethere' no way to know how many the user might need thus it seems easier to allow the user to create as many such references as necessary to make this possible in an object-oriented languageit' natural to embed each reference in class object (this can' be the same as the list classbecause there' only one list object an iterator class objects containing references to items in data structuresused to traverse data structuresare commonly called iterators (or sometimesas in certain java classesenumeratorshere' preliminary idea of how they lookclass listiterator(private link currentthe current field contains reference to the link the iterator currently points to (the term "pointsas used here doesn' refer to pointers in ++we're using it in its generic sense to use such an iteratorthe user might create list and then create an iterator object associated with the list actuallyas it turns outit' easier to let the list create the iteratorso it can pass the iterator certain informationsuch as reference to its first field thus we add getiterator(method to the list classthis method returns suitable iterator object to the user here' some abbreviated code in main(that shows how the class user would invoke an iteratorpublic static void mainlinklist thelist new linklist()listiterator iter thelist getiterator()link alink iter getcurrent()iterator iter nextlink()/make list /make iter /access link at /move iter to next link once we've made the iterator objectwe can use it to access the link it points toor increment it so it points to the next linkas shown in the second two statements we call the iterator object iter to emphasize that you could make more iterators (iter and so onthe same way the iterator always points to some link in the list it' associated with the listbut it' not the same as the list figure shows two iterators pointing to links in list
24,941
additional iterator features we've seen several programs where the use of previous field made it simpler to perform certain operationssuch as deleting link from an arbitrary location such field is also useful in an iterator alsoit may be that the iterator will need to change the value of the list' first fieldfor exampleif an item is inserted or deleted at the beginning of the list if the iterator is an object of separate classhow can it access private fieldsuch as firstin the listone solution is for the list to pass reference to itself to the iterator when it creates it this reference is stored in field in the iterator the list must then provide public methods that allow the iterator to change first these are linklist methods getfirst(and setfirst((the weakness of this approach is that these methods allow anyone to change firstwhich introduces an element of risk here' revised (although still incompleteiterator class that incorporates these additional fieldsalong with reset(and nextlink(methodsclass listiterator(private link currentprivate link previousprivate linklist ourlist/reference to current link /reference to previous link /reference to "parentlist public void reset(/set to start of list current ourlist getfirst()/current --first previous null/previous --null public void nextlink(/go to next link previous current/set previous to this current current next/set this to next
24,942
we might notefor you old-time +programmersthat in +the connection between the iterator and the list is typically provided by making the iterator class friend of the list class howeverjava has no friend classeswhich are controversial in any case because they are chink in the armor of data hiding iterator methods additional methods can make the iterator flexible and powerful class all operations previously performed by the class that involve iterating through the listlike insertafter()are more naturally performed by the iterator in our example the iterator includes the following methodsreset(sets iterator to the start of the list nextlink(moves iterator to next link getcurrent(returns the link at iterator tend(returns true if iterator is at end of list insertafter(inserts new link after iterator insertbefore(inserts new link before iterator deletecurrent(deletes the link at the iterator the user can position the iterator using reset(and nextlink()check if it' at the end of the list with atend()and perform the other operations shown deciding which tasks should be carried out by an iterator and which by the list itself is not always easy an insertbefore(method works best in the iteratorbut an insertfirst(routine that always inserts at the beginning of the list might be more appropriate in the list class we've kept displaylist(routine in the listbut this operation could also be handled with getcurrent(and nextlink(calls to the iterator the interiterator java program the interiterator java program includes an interactive interface that permits the user to control the iterator directly once you've started the programyou can perform the following actions by typing the appropriate letters show the list contents reset the iterator to the start of the list go to the next link get the contents of the current link insert before the current link
24,943
delete the current link listing shows the complete interiterator java program listing the interiterator java program /interiterator java /demonstrates iterators on linked list /to run this programc>java interiterapp import java io */for / ///////////////////////////////////////////////////////////////class link public double ddata/data item public link next/next link in list /public link(double dd/constructor ddata dd/public void displaylink(/display ourself system out print(ddata ")/end class link ///////////////////////////////////////////////////////////////class linklist private link first/ref to first item on list /public linklist(/constructor first null/no items on list yet /public link getfirst(/get value of first return first/public void setfirst(link /set first to new link first /
24,944
return first==null/true if list is empty /public listiterator getiterator(/return iterator return new listiterator(this)/initialized with /this list /public void displaylist(link current first/start at beginning of list while(current !null/until end of listcurrent displaylink()/print data current current next/move to next link system out println("")//end class linklist ///////////////////////////////////////////////////////////////class listiterator private link currentprivate link previousprivate linklist ourlist/current link /previous link /our linked list //public listiterator(linklist list/constructor ourlist listreset()//public void reset(/start at 'firstcurrent ourlist getfirst()previous null//public boolean atend(/true if last link
24,945
//public void nextlink(/go to next link previous currentcurrent current next//public link getcurrent(/get current link return current//public void insertafter(double dd/insert after /current link link newlink new link(dd)ifourlist isempty(/empty list ourlist setfirst(newlink)current newlinkelse /not empty newlink next current nextcurrent next newlinknextlink()/point to new link //public void insertbefore(double dd/insert before /current link link newlink new link(dd)if(previous =null/beginning of list /(or empty listnewlink next ourlist getfirst()ourlist setfirst(newlink)reset()else /not beginning newlink next previous nextprevious next newlinkcurrent newlink
24,946
double value current ddataif(previous =null/beginning of list ourlist setfirst(current next)reset()else /not beginning previous next current nextifatend(reset()else current current nextreturn value///end class listiterator ///////////////////////////////////////////////////////////////class interiterapp public static void main(string[argsthrows ioexception linklist thelist new linklist()/new list listiterator iter thelist getiterator()/new iter double valueiter insertafter( )iter insertafter( )iter insertafter( )iter insertbefore( )")")/insert items while(truesystem out print("enter first letter of showresetsystem out print("nextgetbeforeafterdeletesystem out flush()int choice getchar()/get user' option switch(choicecase ' '/show list if!thelist isempty(thelist displaylist()
24,947
system out println("list is empty")breakcase ' '/reset (to firstiter reset()breakcase ' '/advance to next item current current if!thelist isempty(&!iter atend(iter nextlink()else system out println("can' go to next link")breakcase ' '/get current item if!thelist isempty(value iter getcurrent(ddatasystem out println("returned value)else system out println("list is empty")breakcase ' '/insert before system out print("enter value to insert")system out flush()value getint()iter insertbefore(value)breakcase ' '/insert after system out print("enter value to insert")system out flush()value getint()iter insertafter(value)breakcase ' '/delete current item if!thelist isempty(value iter deletecurrent()system out println("deleted value)else system out println("can' delete")breakdefaultsystem out println("invalid entry")/end switch /end while /end main(//public static string getstring(throws ioexception
24,948
inputstreamreader isr new inputstreamreader(system in)bufferedreader br new bufferedreader(isr)string br readline()return //public static int getchar(throws ioexception string getstring()return charat( )//public static int getint(throws ioexception string getstring()return integer parseint( )/end getint(///end class interiterapp the main(routine inserts four items into the listusing an iterator and its insertafter(method then it waits for the user to interact with it in the following sample interactionthe user displays the listresets the iterator to the beginninggoes forward two linksgets the current link' key value (which is )inserts before thisinserts after the and displays the list again enter first letter of showresetnextgetbeforeafterdeletes enter first letter of showresetnextgetbeforeafterdeleter enter first letter of showresetnextgetbeforeafterdeleten enter first letter of showresetnextgetbeforeafterdeleten enter first letter of showresetnextgetbeforeafterdeleteg returned enter first letter of showresetnextgetbeforeafterdeleteb enter value to insert enter first letter of showresetnextgetbeforeafterdeletea enter value to insert enter first letter of showresetnextgetbeforeafterdeletes
24,949
experimenting with the interiterator java program will give you feeling for how the iterator moves along the links and how it can insert and delete links anywhere in the list where does it pointone of the design issues in an iterator class is deciding where the iterator should point following various operations when you delete an item with deletecurrent()should the iterator end up pointing to the next itemto the previous itemor back at the beginning of the listit' convenient to keep it in the vicinity of the deleted itembecause the chances are the class user will be carrying out other operations there howeveryou can' move it to the previous item because there' no way to reset the list' previous field to the previous item (you' need doubly linked list for that our solution is to move the iterator to the link following the deleted link if we've just deleted the item at the end of the listthe iterator is set to the beginning of the list following calls to insertbefore(and insertafter()we return with current pointing to the newly inserted item the atend(method there' another question about the atend(method it could return true when the iterator points to the last valid link in the listor it could return true when the iterator points past the last link (and is thus not pointing to valid linkwith the first approacha loop condition used to iterate through the list becomes awkward because you need to perform an operation on the last link before checking whether it is the last link (and terminating the loop if it ishoweverthe second approach doesn' allow you to find out you're at the end of the list until it' too late to do anything with the last link (you couldn' look for the last link and then delete itfor example this is because when atend(became truethe iterator would no longer point to the last link (or indeed any valid link)and you can' "back upthe iterator in singly linked list we take the first approach this way the iterator always points to valid linkalthough you must be careful when writing loop that iterates through the listas we'll see next iterative operations as we notedan iterator allows you to traverse the listperforming operations on certain data items here' code fragment that displays the list contentsusing an iterator instead of the list' displaylist(methoditer reset()double value iter getcurrent(ddatasystem out println(value ")while!iter atend(iter nextlink()linkdouble value iter getcurrent(ddatasystem out println(value ") /start at first /display link /until end/go to next /display it
24,950
although not shown hereyou should check with isempty(to be sure the list is not empty before calling getcurrent(the following code shows how you could delete all items with keys that are multiples of we show only the revised main(routineeverything else is the same as in interiterator java class interiterapp public static void main(string[argsthrows ioexception linklist thelist new linklist()/new list listiterator iter thelist getiterator()/new iter iter insertafter( )iter insertafter( )iter insertafter( )iter insertafter( )iter insertafter( )/insert links thelist displaylist()/display list iter reset()link alink iter getcurrent()if(alink ddata = iter deletecurrent()while!iter atend(iter nextlink()/start at first link /get it /if divisible by /delete it /until end of listalink iter getcurrent()if(alink ddata = iter deletecurrent()thelist displaylist()/end main(/get link /if divisible by /delete it /go to next link /display list /end class interiterapp we insert five links and display the list then we iterate through the listdeleting those links with keys divisible by and display the list again here' the output againalthough this code doesn' show itit' important to check whether the list is empty before calling deletecurrent(other methods
24,951
find(method would return an item with specified key valueas we've seen when find(is list method replace(method could replace items that had certain key values with other items because it' singly linked listyou can only iterate along it in the forward direction if doubly linked list were usedyou could go either wayallowing operations such as deletion from the end of the listjust as with noniterator this would probably be convenience in some applications summary linked list consists of one linkedlist object and number of link objects the linkedlist object contains referenceoften called firstto the first link in the list each link object contains data and referenceoften called nextto the next link in the list next value of null signals the end of the list inserting an item at the beginning of linked list involves changing the new link' next field to point to the old first linkand changing first to point to the new item deleting an item at the beginning of list involves setting first to point to first next to traverse linked listyou start at firstthen go from link to linkusing each link' next field to find the next link link with specified key value can be found by traversing the list once foundan item can be displayeddeletedor operated on in other ways new link can be inserted before or after link with specified key valuefollowing traversal to find this link double-ended list maintains pointer to the last link in the listoften called lastas well as to the first double-ended list allows insertion at the end of the list an abstract data type (adtis data-storage class considered without reference to its implementation stacks and queues are adts they can be implemented using either arrays or linked lists in sorted linked listthe links are arranged in order of ascending (or sometimes descendingkey value insertion in sorted list takes (ntime because the correct insertion point must be found deletion of the smallest link takes ( time in doubly linked listeach link contains reference to the previous link as well as the next link
24,952
an iterator is referenceencapsulated in class objectthat points to link in an associated list iterator methods allow the user to move the iterator along the list and access the link currently pointed to an iterator can be used to traverse through listperforming some operation on selected links (or all linkssummary linked list consists of one linkedlist object and number of link objects the linkedlist object contains referenceoften called firstto the first link in the list each link object contains data and referenceoften called nextto the next link in the list next value of null signals the end of the list inserting an item at the beginning of linked list involves changing the new link' next field to point to the old first linkand changing first to point to the new item deleting an item at the beginning of list involves setting first to point to first next to traverse linked listyou start at firstthen go from link to linkusing each link' next field to find the next link link with specified key value can be found by traversing the list once foundan item can be displayeddeletedor operated on in other ways new link can be inserted before or after link with specified key valuefollowing traversal to find this link double-ended list maintains pointer to the last link in the listoften called lastas well as to the first double-ended list allows insertion at the end of the list an abstract data type (adtis data-storage class considered without reference to its implementation stacks and queues are adts they can be implemented using either arrays or linked lists in sorted linked listthe links are arranged in order of ascending (or sometimes descendingkey value insertion in sorted list takes (ntime because the correct insertion point must be found deletion of the smallest link takes ( time in doubly linked listeach link contains reference to the previous link as well as the next link
24,953
an iterator is referenceencapsulated in class objectthat points to link in an associated list iterator methods allow the user to move the iterator along the list and access the link currently pointed to an iterator can be used to traverse through listperforming some operation on selected links (or all linkstriangular numbers it' said that the pythagoriansa band of mathematicians in ancient greece who worked under pythagoras (of pythagorian theorem fame)felt mystical connection with the series of numbers (where the means the series continues indefinitelycan you find the next member of this seriesthe nth term in the series is obtained by adding to the previous term thus the second term is found by adding to the first term (which is )giving the third term is added to the second term (which is )giving and so on the numbers in this series are called triangular numbers because they can be visualized as triangular arrangements of objectsshown as little squares in figure finding the nth term using loop suppose you wanted to find the value of some arbitrary nth term in the seriessay the fourth term (whose value is how would you calculate itlooking at figure you might decide that the value of any term can be obtained by adding up all the vertical columns of squares in the fourth termthe first column has four little squaresthe second column has threeand so on adding + + + gives figure the triangular numbers
24,954
the following triangle(method uses this column-based technique to find triangular number it sums all the columnsfrom height of to height of int triangle(int nint total while( total total --nreturn total/until is /add (column heightto total /decrement column height the method cycles around the loop timesadding to total the first timen- the second timeand so on down to quitting the loop when becomes finding the nth term using recursion the loop approach may seem straightforwardbut there' another way to look at this problem the value of the nth term can be thought of as the sum of only two thingsinstead of whole series these are the first (tallestcolumnwhich has the value the sum of all the remaining columns this is shown in figure figure triangular number as column plus triangle
24,955
if we knew about method that found the sum of all the remaining columnsthen we could write our triangle(methodwhich returns the value of the nth triangular numberlike thisint triangle(int nreturnn sumremainingcolumns( )version/(incomplete but what have we gained hereit looks like it' just as hard to write the sumremainingcolumns(method as to write the triangle(method in the first place notice in figure howeverthat the sum of all the remaining columns for term is the same as the sum of all the columns for term - thusif we knew about method that summed all the columns for term nwe could call it with an argument of - to find the sum of all the remaining columns for term nint triangle(int nreturnn sumallcolumns( - )/(incomplete versionbut when you think about itthe sumallcolumns(method is doing exactly the same thing the triangle(method is doingsumming all the columns for some number passed as an argument so why not use the triangle(method itselfinstead of some other methodthat would look like thisint triangle(int nreturnn triangle( - )/(incomplete versionit may seem amazing that method can call itselfbut why shouldn' it be able toa method call is (among other thingsa transfer of control to the start of the method this transfer of control can take place from within the method as well as from outside passing the buck all this may seem like passing the buck someone tells me to find the th triangular number know this is plus the th triangular numberso call harry and ask him to find the th triangular number when hear back from himi'll add to whatever he tells meand that will be the answer harry knows the th triangular number is plus the th triangular numberso he calls sally and asks her to find the th triangular number this process continues with each person passing the buck to another one
24,956
an answer that doesn' involve asking another person to help them if this didn' happenthere would be an infinite chain of people asking other people questionsa sort of arithmetic ponzi scheme that would never end in the case of triangle()this would mean the method calling itself over and over in an infinite series that would paralyze the program the buck stops here to prevent an infinite regressthe person who is asked to find the first triangular number of the serieswhen is must knowwithout asking anyone elsethat the answer is there are no smaller numbers to ask anyone aboutthere' nothing left to add to anything elseso the buck stops there we can express this by adding condition to the triangle(methodint triangle(int nif( == return else returnn triangle( - )the condition that leads to recursive method returning without making another recursive call is referred to as the base case it' critical that every recursive method have base case to prevent infinite recursion and the consequent demise of the program the triangle java program does recursion actually workif you run the triangle java programyou'll see that it does enter value for the term numbernand the program will display the value of the corresponding triangular number listing shows the triangle java program listing the triangle java program /triangle java /evaluates triangular numbers /to run this programc>java triangleapp import java io */for / ///////////////////////////////////////////////////////////////class triangleapp static int thenumberpublic static void main(string[argsthrows ioexception system out print("enter number")system out flush()thenumber getint()int theanswer triangle(thenumber)system out println("triangle="+theanswer)/end main(/
24,957
if( == return else returnn triangle( - )//public static string getstring(throws ioexception inputstreamreader isr new inputstreamreader(system in)bufferedreader br new bufferedreader(isr)string br readline()return //public static int getint(throws ioexception string getstring()return integer parseint( )///end class triangleapp the main(routine prompts the user for value for ncalls triangle()and displays the return value the triangle(method calls itself repeatedly to do all the work here' some sample outputenter number triangle incidentallyif you're skeptical of the results returned from triangle()you can check them by using the following formulanth triangular number ( + )/ what' really happeninglet' modify the triangle(method to provide an insight into what' happening when it executes we'll insert some output statements to keep track of the arguments and return valuespublic static int triangle(int nsystem out println("enteringn= )if( ==
24,958
return else int temp triangle( - )system out println("returning temp)return temphere' the interaction when this method is substituted for the earlier triangle(method and the user enters enter number enteringn= enteringn= enteringn= enteringn= enteringn= returning returning returning returning returning triangle each time the triangle(method calls itselfits argumentwhich starts at is reduced by the method plunges down into itself again and again until its argument is reduced to then it returns this triggers an entire series of returns the method rises back upphoenixlikeout of the discarded versions of itself each time it returnsit adds the value of it was called with to the return value from the method it called the return values recapitulate the series of triangular numbersuntil the answer is returned to main(figure shows how each invocation of the triangle(method can be imagined as being "insidethe previous one notice thatjust before the innermost version returns there are actually five different incarnations of triangle(in existence at the same time the outer one was passed the argument the inner one was passed the argument
24,959
characteristics of recursive methods although it' shortthe triangle(method possesses the key features common to all recursive routinesit calls itself when it calls itselfit does so to solve smaller problem there' some version of the problem that is simple enough that the routine can solve itand returnwithout calling itself in each successive call of recursive method to itselfthe argument becomes smaller (or perhaps range described by multiple arguments becomes smaller)reflecting the fact that the problem has become "smalleror easier when the argument or range reaches certain minimum sizea condition is triggered and the method returns without calling itself is recursion efficientcalling method involves certain overhead control must be transferred from the location of the call to the beginning of the method in additionthe arguments to the methodand the address to which the method should returnmust be pushed onto an internal stack so that the method can access the argument values and know where to return in the case of the triangle(methodit' probable thatas result of this overheadthe while loop approach executes more quickly than the recursive approach the penalty may not be significantbut if there are large number of method calls as result of recursive methodit might be desirable to eliminate the recursion we'll talk about this more at the end of this another inefficiency is that memory is used to store all the intermediate arguments and
24,960
amount of dataleading to stack overflow recursion is usually used because it simplifies problem conceptuallynot because it' inherently more efficient mathematical induction recursion is the programming equivalent of mathematical induction mathematical induction is way of defining something in terms of itself (the term is also used to describe related approach to proving theorems using inductionwe could define the triangular numbers mathematically by saying if tri(nn tri( - if defining something in terms of itself may seem circularbut in fact it' perfectly valid (provided there' base casefactorials factorials are similar in concept to triangular numbersexcept that multiplication is used instead of addition the triangular number corresponding to is found by adding to the triangular number of - while the factorial of is found by multiplying by the factorial of - that isthe fifth triangular number is + + + + while the factorial of is * * * * which equals table shows the factorials of the first numbers table factorials number calculation factorial by definition * * * * , , ,
24,961
, , the factorial of is defined to be factorial numbers grow large very rapidlyas you can see recursive method similar to triangle(can be used to calculate factorials it looks like thisint factorial(int nif( == return else return ( factorial( - )there are only two differences between factorial(and triangle(firstfactorial(uses an instead of in the expression factorial( - secondthe base condition occurs when is not here' some sample interaction when this method is used in program similar to triangle javaenter number factorial = figure shows how the various incarnations of factorial(call themselves when initially entered with = calculating factorials is the classic demonstration of recursionalthough factorials aren' as easy to visualize as triangular numbers various other numerological entities lend themselves to calculation using recursion in similar waysuch as finding the greatest common denominator of two numbers (which is used to reduce fraction to lowest terms)raising number to powerand so on againwhile these calculations are interesting for demonstrating recursionthey probably wouldn' be used in practice because loop-based approach is more efficient
24,962
anagrams here' different kind of situation in which recursion provides neat solution to problem suppose you want to list all the anagrams of specified wordthat isall possible letter combinations (whether they make real english word or notthat can be made from the letters of the original word we'll call this anagramming word anagramming catfor examplewould produce cat cta atc act tca tac try anagramming some words yourself you'll find that the number of possibilities is the factorial of the number of letters for letters there are possible wordsfor letters there are wordsfor letters wordsand so on (this assumes that all letters are distinctif there are multiple instances of the same letterthere will be fewer possible words how would you write program to anagram wordhere' one approach assume the word has letters anagram the rightmost - letters rotate all letters repeat these steps times to rotate the word means to shift all the letters one position leftexcept for the leftmost letterwhich "rotatesback to the rightas shown in figure
24,963
selected letter occupies this first positionall the other letters are then anagrammed (arranged in every possible positionfor catwhich has only lettersrotating the remaining letters simply switches them the sequence is shown in table figure rotating word table anagramming the word cat word display wordfirst letter remaining letters action cat yes at rotate at cta yes ta rotate ta cat no at rotate cat atc yes tc rotate tc act yes ct rotate ct atc no tc rotate atc tca yes ca rotate ca tac yes ac rotate ac tca no ca rotate tca cat no at done notice that we must rotate back to the starting point with two letters before performing -letter rotation this leads to sequences like catctacat the redundant combinations aren' displayed
24,964
doanagram(method takes the size of the word to be anagrammed as its only parameter this word is understood to be the rightmost letters of the complete word each time doanagram(calls itselfit does so with word one letter smaller than beforeas shown in figure the base case occurs when the size of the word to be anagrammed is only one letter there' no way to rearrange one letterso the method returns immediately otherwiseit anagrams all but the first letter of the word it was given and then rotates the entire word these two actions are performed timeswhere is the size of the word here' the recursive routine doanagram()public static void doanagram(int newsizeif(newsize = /if too smallreturn/go no further for(int = <newsizej++/for each positiondoanagram(newsize- )/anagram remaining if(newsize== /if innermostdisplayword()/display it rotate(newsize)/rotate word each time the doanagram(method calls itselfthe size of the word is one letter smallerand the starting position is one cell further to the rightas shown in figure figure the recursive doanagram(method
24,965
listing shows the complete anagram java program the main(routine gets word from the userinserts it into character array so it can be dealt with convenientlyand then calls doanagram(listing the anagram java program /anagram java /creates anagrams /to run this programc>java anagramapp import java io */for / ///////////////////////////////////////////////////////////////class anagramapp static int sizestatic int countstatic char[arrchar new char[ ]public static void main(string[argsthrows ioexception system out print("enter word")/get word system out flush()string input getstring()size input length()/find its size count for(int = <sizej++/put it in array arrchar[jinput charat( )doanagram(size)/anagram it /end main(/public static void doanagram(int newsizeif(newsize = /if too smallreturn/go no further for(int = <newsizej++/for each positiondoanagram(newsize- )/anagram remaining if(newsize== /if innermostdisplayword()/display it rotate(newsize)/rotate word ///rotate left all chars from position to end public static void rotate(int newsize
24,966
int jint position size newsizechar temp arrchar[position]for( =position+ <sizej++arrchar[ - arrchar[ ]arrchar[ - temp/save first letter /shift others left /put first on //public static void displayword(if(count system out print(")if(count system out print(")system out print(++count ")for(int = <sizej++system out printarrchar[ )system out print(")system out flush()if(count% = system out println("")//public static string getstring(throws ioexception inputstreamreader isr new inputstreamreader(system in)bufferedreader br new bufferedreader(isr)string br readline()return ///end class anagramapp the rotate(method rotates the word one position left as described earlier the displayword(method displays the entire word and adds count to make it easy to see how many words have been displayed here' some sample interaction with the programenter wordcats cats cast atsc atcs tsca tsac scat scta ctsa asct tcas satc ctas astc tcsa sact csat acts tasc stca csta acst tacs stac (is it only coincidence that scat is an anagram of cats?you can use the program to anagram -letter or even -letter words howeverbecause the factorial of is this may generate more words than you want to know about
24,967
here' different kind of situation in which recursion provides neat solution to problem suppose you want to list all the anagrams of specified wordthat isall possible letter combinations (whether they make real english word or notthat can be made from the letters of the original word we'll call this anagramming word anagramming catfor examplewould produce cat cta atc act tca tac try anagramming some words yourself you'll find that the number of possibilities is the factorial of the number of letters for letters there are possible wordsfor letters there are wordsfor letters wordsand so on (this assumes that all letters are distinctif there are multiple instances of the same letterthere will be fewer possible words how would you write program to anagram wordhere' one approach assume the word has letters anagram the rightmost - letters rotate all letters repeat these steps times to rotate the word means to shift all the letters one position leftexcept for the leftmost letterwhich "rotatesback to the rightas shown in figure rotating the word times gives each letter chance to begin the word while the selected letter occupies this first positionall the other letters are then anagrammed (arranged in every possible positionfor catwhich has only lettersrotating the remaining letters simply switches them the sequence is shown in table figure rotating word
24,968
word display wordfirst letter remaining letters action cat yes at rotate at cta yes ta rotate ta cat no at rotate cat atc yes tc rotate tc act yes ct rotate ct atc no tc rotate atc tca yes ca rotate ca tac yes ac rotate ac tca no ca rotate tca cat no at done notice that we must rotate back to the starting point with two letters before performing -letter rotation this leads to sequences like catctacat the redundant combinations aren' displayed how do we anagram the rightmost - lettersby calling ourselves the recursive doanagram(method takes the size of the word to be anagrammed as its only parameter this word is understood to be the rightmost letters of the complete word each time doanagram(calls itselfit does so with word one letter smaller than beforeas shown in figure the base case occurs when the size of the word to be anagrammed is only one letter there' no way to rearrange one letterso the method returns immediately otherwiseit anagrams all but the first letter of the word it was given and then rotates the entire word these two actions are performed timeswhere is the size of the word here' the recursive routine doanagram()public static void doanagram(int newsizeif(newsize = /if too smallreturn/go no further for(int = <newsizej++/for each positiondoanagram(newsize- )/anagram remaining
24,969
displayword()rotate(newsize)/if innermost/display it /rotate word each time the doanagram(method calls itselfthe size of the word is one letter smallerand the starting position is one cell further to the rightas shown in figure figure the recursive doanagram(method figure smaller and smaller words listing shows the complete anagram java program the main(routine gets word from the userinserts it into character array so it can be dealt with convenientlyand then calls doanagram(listing the anagram java program /anagram java /creates anagrams /to run this programc>java anagramapp import java io */for / ///////////////////////////////////////////////////////////////class anagramapp static int size
24,970
static char[arrchar new char[ ]public static void main(string[argsthrows ioexception system out print("enter word")/get word system out flush()string input getstring()size input length()/find its size count for(int = <sizej++/put it in array arrchar[jinput charat( )doanagram(size)/anagram it /end main(/public static void doanagram(int newsizeif(newsize = /if too smallreturn/go no further for(int = <newsizej++/for each positiondoanagram(newsize- )/anagram remaining if(newsize== /if innermostdisplayword()/display it rotate(newsize)/rotate word //rotate left all chars from position to end public static void rotate(int newsizeint jint position size newsizechar temp arrchar[position]/save first letter for( =position+ <sizej++/shift others left arrchar[ - arrchar[ ]arrchar[ - temp/put first on right //public static void displayword(if(count system out print(")if(count system out print(")system out print(++count ")
24,971
system out printarrchar[ )system out print(")system out flush()if(count% = system out println("")//public static string getstring(throws ioexception inputstreamreader isr new inputstreamreader(system in)bufferedreader br new bufferedreader(isr)string br readline()return ///end class anagramapp the rotate(method rotates the word one position left as described earlier the displayword(method displays the entire word and adds count to make it easy to see how many words have been displayed here' some sample interaction with the programenter wordcats cats cast atsc atcs tsca tsac scat scta ctsa asct tcas satc ctas astc tcsa sact csat acts tasc stca csta acst tacs stac (is it only coincidence that scat is an anagram of cats?you can use the program to anagram -letter or even -letter words howeverbecause the factorial of is this may generate more words than you want to know about the towers of hanoi the towers of hanoi is an ancient puzzle consisting of number of disks placed on three columnsas shown in figure the disks all have different diameters and holes in the middle so they will fit over the columns all the disks start out on column the object of the puzzle is to transfer all the disks from column to column only one disk can be moved at timeand no disk can be placed on disk that' smaller than itself there' an ancient myth that somewhere in indiain remote templemonks labor day and night to transfer golden disks from one of three diamond-studded towers to another when they are finishedthe world will end any alarm you may feelhoweverwill be dispelled when you see how long it takes to solve the puzzle for far fewer than disks the towers workshop applet
24,972
using the mouse to drag the topmost disk to another tower figure shows how this looks after several moves have been made there are three ways to use the workshop applet you can attempt to solve the puzzle manuallyby dragging the disks from tower to tower you can repeatedly press the step button to watch the algorithm solve the puzzle at each step in the solutiona message is displayedtelling you what the algorithm is doing you can press the run button and watch the algorithm solve the puzzle with no intervention on your partthe disks zip back and forth between the posts figure the towers of hanoi figure the towers workshop applet to restart the puzzletype in the number of disks you want to usefrom to and press new twice (after the first timeyou're asked to verify that restarting is what you want to do the specified number of disks will be arranged on tower once you drag disk with the mouseyou can' use step or runyou must start over with new howeveryou can switch to manual in the middle of stepping or runningand you can switch to step when you're runningand run when you're stepping try solving the puzzle manually with small number of diskssay or work up to higher numbers the applet gives you the opportunity to learn intuitively how the problem is solved
24,973
let' call the initial tree-shaped (or pyramid-shapedarrangement of disks on tower tree as you experiment with the appletyou'll begin to notice that smaller tree-shaped stacks of disks are generated as part of the solution process let' call these smaller treescontaining fewer than the total number of diskssubtrees for exampleif you're trying to transfer disksyou'll find that one of the intermediate steps involves subtree of disks on tower bas shown in figure these subtrees form many times in the solution of the puzzle this is because the creation of subtree is the only way to transfer larger disk from one tower to anotherall the smaller disks must be placed on an intermediate towerwhere they naturally form subtree figure subtree on tower here' rule of thumb that may help when you try to solve the puzzle manually if the subtree you're trying to move has an odd number of disksstart by moving the topmost disk directly to the tower where you want the subtree to go if you're trying to move subtree with an even number of disksstart by moving the topmost disk to the intermediate tower the recursive algorithm the solution to the towers of hanoi puzzle can be expressed recursively using the notion of subtrees suppose you want to move all the disks from source tower (call it sto destination tower (call it dyou have an intermediate tower available (call it iassume there are disks on tower here' the algorithm move the subtree consisting of the top - disks from to move the remaining (largestdisk from to move the subtree from to when you beginthe source tower is athe intermediate tower is band the destination tower is figure shows the three steps for this situation firstthe subtree consisting of disks and is moved to the intermediate tower then the largest disk is moved to tower then the subtree is moved from to of coursethis doesn' solve the problem of how to move the subtree consisting of disks and to tower bbecause you can' move subtree all at onceyou must move it one disk at time moving the -disk subtree is not so easy howeverit' easier than moving disks as it turns outmoving disks from to the destination tower can be done with the same steps as moving disks that ismove the subtree consisting of the top disks from tower to intermediate tower cthen move disk from to then move the subtree back from to
24,974
only one disk ( from to this is the base casewhen you're moving only one diskyou just move itthere' nothing else to do then move the larger disk ( from to cand replace the subtree (disk on it figure recursive solution to towers puzzle the towers java program the towers java program solves the towers of hanoi puzzle using this recursive approach it communicates the moves by displaying themthis requires much less code than displaying the towers it' up to the human reading the list to actually carry out the moves the code is simplicity itself the main(routine makes single call to the recursive method dotowers(this method then calls itself recursively until the puzzle is solved in this versionshown in listing there are initially only disksbut you can recompile the program with any number listing the towers java program /towers java /evaluates triangular numbers /to run this programc>java towersapp import java io */for / ///////////////////////////////////////////////////////////////class towersapp static int ndisks public static void main(string[argsdotowers(ndisks' '' '' ')//public static void dotowers(int topnchar fromchar interchar to
24,975
if(topn== system out println("disk from from to "else dotowers(topn- fromtointer)/from-->inter system out println("disk topn from from to "to)dotowers(topn- interfromto)/inter-->to ///end class towersapp remember that disks are moved from to here' the output from the programdisk from to disk from to disk from to disk from to disk from to disk from to disk from to the arguments to dotowers(are the number of disks to be movedand the source (from)intermediate (inter)and destination (totowers to be used the number of disks decreases by each time the method calls itself the sourceintermediateand destination towers also change here is the output with additional notations that show when the method is entered and when it returnsits argumentsand whether disk is moved because it' the base case ( subtree consisting of only one diskor because it' the remaining bottom disk after subtree has been moved enter ( disks) =ai=bd= enter ( disks) =ai=cd= enter ( disk) =ai=bd= base casemove disk from to return ( diskmove bottom disk from to enter ( disk) =ci=ad= base casemove disk from to return ( diskreturn ( disksmove bottom disk from to enter ( disks) =bi=ad= enter ( disk) =bi=cd= base casemove disk from to return ( disk
24,976
enter ( disk) =ai=bd= base casemove disk from to return ( diskreturn ( disksreturn ( disksif you study this output along with the source code for dotower()it should become clear exactly how the method works it' amazing that such small amount of code can solve such seemingly complicated problem mergesort our final example of recursion is the mergesort this is much more efficient sorting technique than those we saw in "simple sorting,at least in terms of speed while the bubbleinsertionand selection sorts take ( timethe mergesort is ( *lognthe graph in figure (in shows how much faster this is for exampleif (the number of items to be sortedis , then is , , while *logn is only , if sorting this many items required seconds with the mergesortit would take almost hours for the insertion sort the mergesort is also fairly easy to implement it' conceptually easier than quicksort and the shell shortwhich we'll encounter in the next the downside of the mergesort is that it requires an additional array in memoryequal in size to the one being sorted if your original array barely fits in memorythe mergesort won' work howeverif you have enough spaceit' good choice merging two sorted arrays the heart of the mergesort algorithm is the merging of two already sorted arrays merging two sorted arrays and creates third arraycthat contains all the elements of and balso arranged in sorted order we'll examine the merging process firstlater we'll see how it' used in sorting imagine two sorted arrays they don' need to be the same size let' say array has elements and array has they will be merged into an array that starts with empty cells figure shows how this looks in the figurethe circled numbers indicate the order in which elements are transferred from and to table shows the comparisons necessary to determine which element will be copied the steps in the table correspond to the steps in the figure following each comparisonthe smaller element is copied to
24,977
table merging operations step comparison (if anycopy compare and copy from to compare and copy from to compare and copy from to compare and copy from to compare and copy from to compare and copy from to compare and copy from to compare and copy from to copy from to copy from to notice thatbecause is empty following step no more comparisons are necessaryall the remaining elements are simply copied from into listing shows java program that carries out the merge shown in figure and table
24,978
/merge java /demonstrates merging two arrays into third /to run this programc>java mergeapp ///////////////////////////////////////////////////////////////class mergeapp public static void main(string[argsint[arraya { }int[arrayb { }int[arrayc new int[ ]merge(arraya arrayb arrayc)display(arrayc )/end main(///merge and into public static void mergeint[arrayaint sizeaint[arraybint sizebint[arrayc int adex= bdex= cdex= empty while(adex sizea &bdex sizeb/neither array ifarraya[adexarrayb[bdexarrayc[cdex++arraya[adex++]else arrayc[cdex++arrayb[bdex++]while(adex sizeaarrayc[cdex++arraya[adex++]/arrayb is empty/but arraya isn' while(bdex sizebarrayc[cdex++arrayb[bdex++]/end merge(/arraya is empty/but arrayb isn' ///display array public static void display(int[thearrayint sizefor(int = <sizej++system out print(thearray[ ")system out println("")/
24,979
/end class mergeapp in main(the arrays arrayaarrayband arrayc are createdthen the merge(method is called to merge arraya and arrayb into arraycand the resulting contents of arrayc are displayed here' the output the merge(method has three while loops the first steps along both arraya and arraybcomparing elements and copying the smaller of the two into arrayc the second while loop deals with the situation when all the elements have been transferred out of arraybbut arraya still has remaining elements (this is what happens in the examplewhere and remain in arraya the loop simply copies the remaining elements from arraya into arrayc the third loop handles the similar situation when all the elements have been transferred out of arraya but arrayb still has remaining elementsthey are copied to arrayc sorting by merging the idea in the mergesort is to divide an array in halfsort each halfand then use the merge(method to merge the two halves into single sorted array how do you sort each halfthis is about recursionso you probably already know the answeryou divide the half into two quarterssort each of the quartersand merge them to make sorted half similarlyeach pair of ths is merged to make sorted quartereach pair of ths is merged to make sorted thand so on you divide the array again and again until you reach subarray with only one element this is the base caseit' assumed an array with one element is already sorted we've seen that generally something is reduced in size each time recursive method calls itselfand built back up again each time the method returns in mergesort(the range is divided in half each time this method calls itselfand each time it returns it merges two smaller ranges into larger one as mergesort(returns from finding arrays of element eachit merges them into sorted array of elements each pair of resulting -element arrays is then merged into -element array this process continues with larger and larger arrays until the entire array is sorted this is easiest to see when the original array size is power of as shown in figure
24,980
firstin the bottom half of the arrayrange - and range - are merged into range - of course - and - aren' really rangesthey're only one elementso they are base cases similarly - and - are merged into - then ranges - and - are merged - in the top half of the array - and - are merged into - - and - are merged into - and - and - are merged into - finally the top half - and the bottom half are merged into the complete array - which is now sorted when the array size is not power of arrays of different sizes must be merged for examplefigure shows the situation in which the array size is here an array of size must be merged with an array of size to form an array of size figure array size not power of first the -element ranges - and - are merged into the -element range - then range - is merged with the -element range - this creates -element range - it' merged with the -element range - the process continues until the array is sorted notice that in mergesort we don' merge two separate arrays into third oneas we
24,981
into itself you may wonder where all these subarrays are located in memory in the algorithma workspace array of the same size as the original array is created the subarrays are stored in sections of the workspace array this means that subarrays in the original array are copied to appropriate places in the workspace array after each mergethe workspace array is copied back into the original array the mergesort workshop applet all this is easier to appreciate when you see it happening before your very eyes start up the mergesort workshop applet repeatedly pressing the step button will execute mergesort step by step figure shows what it looks like after the first three presses figure the mergesort workshop applet the lower and upper arrows show the range currently being considered by the algorithmand the mid arrow shows the middle part of the range the range starts as the entire array and then is halved each time the mergesort(method calls itself when the range is one elementmergesort(returns immediatelythat' the base case otherwisethe two subarrays are merged the applet provides messagessuch as entering mergesort - to tell you what it' doing and the range it' operating on many steps involve the mergesort(method calling itself or returning comparisons and copies are performed only during the merge processwhen you'll see messages such as merged - and - into workspace you can' see the merge happeningbecause the workspace isn' shown howeveryou can see the result when the appropriate section of the workspace is copied back into the original (visiblearraythe bars in the specified range will appear in sorted order firstthe first bars will be sortedthen the first barsthen the bars in the range - then the bars in the range - then the bars in the range - and so oncorresponding to the sequence shown in figure eventually all the bars will be sorted you can cause the algorithm to run continuously by pressing the run button you can stop this process at any time by pressing stepsingle-step as many times as you wantand resume running by pressing run again as in the other sorting workshop appletspressing new resets the array with new group of unsorted bars and toggles between random and inverse arrangements the size button toggles between bars and bars it' especially instructive to watch the algorithm run with inversely sorted bars the
24,982
other halfand how the ranges grow larger and larger the mergesort java program in moment we'll look at the entire mergesort java program firstlet' focus on the method that carries out the mergesort here it isprivate void recmergesort(double[workspaceint lowerboundint upperboundif(lowerbound =upperbound/if range is return/no use sorting else /find midpoint int mid (lowerbound+upperbound /sort low half recmergesort(workspacelowerboundmid)/sort high half recmergesort(workspacemid+ upperbound)/merge them merge(workspacelowerboundmid+ upperbound)/end else /end recmergesort as you can seebeside the base casethere are only four statements in this method one computes the midpointthere are two recursive calls to recmergesort((one for each half of the array)and finally call to merge(to merge the two sorted halves the base case occurs when the range contains only one element (lowerbound==upperboundand results in an immediate return in the mergesort java programthe mergesort(method is the one actually seen by the class user it creates the array workspace[]and then calls the recursive routine recmergesort(to carry out the sort the creation of the workspace array is handled in mergesort(because doing it in recmergesort(would cause the array to be created anew with each recursive callan inefficiency the merge(method in the previous merge java program operated on three separate arraystwo source arrays and destination array the merge(routine in the mergesort java program operates on single arraythe thearray member of the darray class the arguments to this merge(method are the starting point of the lowhalf subarraythe starting point of the high-half subarrayand the upper bound of the high-half subarray the method calculates the sizes of the subarrays based on this information listing shows the complete mergesort java program this program uses variant of the array classes from adding the mergesort(and recmergesort(methods to the darray class the main(routine creates an arrayinserts itemsdisplays the arraysorts the items with mergesort()and displays the array again listing the mergesort java program /mergesort java /demonstrates recursive mergesort
24,983
import java io */for / ///////////////////////////////////////////////////////////////class darray private double[thearray/ref to array thearray private int nelems/number of data items //public darray(int maxthearray new double[max]nelems /constructor /create array //public void insert(double valuethearray[nelemsvaluenelems++/put element into array /insert it /increment size //public void display(/displays array contents for(int = <nelemsj++/for each elementsystem out print(thearray[ ")/display it system out println("")//public void mergesort(/called by main(/provides workspace double[workspace new double[nelems]recmergesort(workspace nelems- )/private void recmergesort(double[workspaceint lowerboundint upperboundif(lowerbound =upperbound/if range is return/no use sorting else /find midpoint int mid (lowerbound+upperbound /sort low half recmergesort(workspacelowerboundmid)
24,984
/sort high half recmergesort(workspacemid+ upperbound)/merge them merge(workspacelowerboundmid+ upperbound)/end else /end recmergesort //private void merge(double[workspaceint lowptrint highptrint upperboundint /workspace index int lowerbound lowptrint mid highptr- int upperbound-lowerbound+ /of items while(lowptr <mid &highptr <upperboundifthearray[lowptrthearray[highptrworkspace[ ++thearray[lowptr++]else workspace[ ++thearray[highptr++]while(lowptr <midworkspace[ ++thearray[lowptr++]while(highptr <upperboundworkspace[ ++thearray[highptr++]for( = <nj++thearray[lowerbound+jworkspace[ ]/end merge(///end class darray ///////////////////////////////////////////////////////////////class mergesortapp public static void main(string[argsint maxsize /array size darray arr/reference to array arr new darray(maxsize)/create the array arr insert( )arr insert( )arr insert( )arr insert( )arr insert( )arr insert( )/insert items
24,985
arr insert( )arr insert( )arr insert( )arr insert( )arr insert( )arr display()/display items arr mergesort()/mergesort the array arr display()/end main(/display items again /end class mergesortapp the output from the program is simply the display of the unsorted and sorted arrays if we put additional statements in the recmergesort(methodwe could generate running commentary on what the program does during sort the following output shows how this might look for the -item array { (you can think of this as the lower half of the array in figure entering - will sort low half of - entering - will sort low half of - entering - base-case return - will sort high half of - entering - base-case return - will merge halves into - return - will sort high half of - entering - will sort low half of - entering - base-case return - will sort high half of - entering - base-case return - will merge halves into - return - will merge halves into - return - thearray= thearray= thearray= this is roughly the same content as would be generated by the mergesort workshop applet if it could sort items study of this outputand comparison with the code for
24,986
efficiency of the mergesort as we notedthe mergesort runs in ( *logntime how do we know thislet' see how we can figure out the number of times data item must be copiedand the number of times it must be compared with another data itemduring the course of the algorithm we assume that copying and comparing are the most time-consuming operationsthat the recursive calls and returns don' add much overhead number of copies consider figure each cell below the top line represents an element copied from the array into the workspace adding up all the cells in figure (the numbered stepsshows there are copies necessary to sort items log is so *log equals this shows thatfor the case of itemsthe number of copies is proportional to *log another way to look at this is thatto sort items requires levelseach of which involves copies level means all copies into the same size subarray in the first levelthere are -element subarraysin the second levelthere are -element subarraysand in the third levelthere is -element subarray each level has elementsso again there are * or copies in figure by considering only half the graphyou can see that copies are necessary for an array of items (steps and )and copies are necessary for items similar calculations provide the number of copies necessary for larger arrays table summarizes this information table number of operations when is power of log number of copies into workspace ( *log ntotal copies comparisons max (min ( ( ( ( ( ( ( actuallythe items are not only copied into the workspacethey're also copied back into
24,987
column the final column of table shows comparisonswhich we'll return to in moment it' harder to calculate the number of copies and comparisons when is not multiple of but these numbers fall between those that are power of for itemsthere are total copiesand for items total copies number of comparisons in the mergesort algorithmthe number of comparisons is always somewhat less than the number of copies how much lessassuming the number of items is power of for each individual merging operationthe maximum number of comparisons is always one less than the number of items being mergedand the minimum is half the number of items being merged you can see why this is true in figure which shows two possibilities when trying to merge arrays of items each figure maximum and minimum comparisons in the first casethe items interleaveand comparisons must be made to merge them in the second caseall the items in one array are smaller than all the items in the otherso only comparisons must be made there are many merges for each sortso we must add the comparisons for each one referring to figure you can see that merge operations are required to sort items the number of items being merged and the resulting number of comparisons is shown in table table comparisons involved in sorting items step number totals number of items being merged( maximum comparisons( - minimum
24,988
for each mergethe maximum number of comparisons is one less than the number of items adding these figures for all the merges gives us total of the minimum number of comparisons is always half the number of items being mergedand adding these figures for all the merges results in comparisons similar arithmetic results in the comparisons columns for table the actual number of comparisons to sort specific array depends on how the data is arrangedbut it will be somewhere between the maximum and minimum values eliminating recursion some algorithms lend themselves to recursive approachsome don' as we've seenthe recursive triangle(and factorial(methods can be implemented more efficiently using simple loop howevervarious divide-and-conquer algorithmssuch as mergesortwork very well as recursive routine often an algorithm is easy to conceptualize as recursive methodbut in practice the recursive approach proves to be inefficient in such casesit' useful to transform the recursive approach into nonrecursive approach such transformation can often make use of stack recursion and stacks there is close relationship between recursion and stacks in factmost compilers implement recursion by using stacks as we notedwhen method is calledthey push the arguments to the method and the return address (where control will go when the method returnson the stackand then transfer control to the method when the method returnsthey pop these values off the stack the arguments disappearand control returns to the return address simulating recursive method in this section we'll demonstrate how any recursive solution can be transformed into stack-based solution remember the recursive triangle(method from the first section in this here it is againint triangle(int nif( == return else returnn triangle( - )we're going to break this algorithm down into its individual operationsmaking each operation one case in switch statement (you can perform similar decomposition using goto statements in +and some other languagesbut java doesn' support goto the switch statement is enclosed in method called step(each call to step(causes one case section within the switch to be executed calling step(repeatedly will eventually execute all the code in the algorithm
24,989
out the arithmetic necessary to compute triangular numbers this involves checking if is and adding to the results of previous recursive calls howevertriangle(also performs the operations necessary to manage the method itself these involve transfer of controlargument accessand the return address these operations are not visible by looking at the codethey're built into all methods hereroughly speakingis what happens during call to methodwhen method is calledits arguments and the return address are pushed onto stack method can access its arguments by peeking at the top of the stack when method is about to returnit peeks at the stack to obtain the return addressand then pops both this address and its arguments off the stack and discards them the stacktriangle java program contains three classesparamsstackxand stacktriangleapp the params class encapsulates the return address and the method' argumentnobjects of this class are pushed onto the stack the stackx class is similar to those in other except that it holds objects of class params the stacktriangleapp class contains four methodsmain()rectriangle()step()and the usual getint(method for numerical input the main(routine asks the user for numbercalls the rectriangle(method to calculate the triangular number corresponding to nand displays the result the rectriangle(method creates stackx object and initializes codepart to it then settles into while loop where it repeatedly calls step(it won' exit from the loop until step(returns true by reaching case its exit point the step(method is basically large switch statement in which each case corresponds to section of code in the original triangle(method listing shows the stacktriangle java program listing the stacktriangle java program /stacktriangle java /evaluates triangular numbersstack replaces recursion /to run this programc>java stacktriangleapp import java io */for / ///////////////////////////////////////////////////////////////class params /parameters to save on stack public int npublic int codepartpublic params(int nnint ran=nnreturnaddress ra/end class params ///////////////////////////////////////////////////////////////
24,990
private int maxsize/size of stack array private params[stackarrayprivate int top/top of stack //public stackx(int /constructor maxsize /set array size stackarray new params[maxsize]/create array top - /no items yet //public void push(params /put item on top of stack stackarray[++topp/increment topinsert item //public params pop(/take item from top of stack return stackarray[top--]/access itemdecrement top //public params peek(/peek at top of stack return stackarray[top]///end class stackx ///////////////////////////////////////////////////////////////class stacktriangleapp static int thenumberstatic int theanswerstatic stackx thestackstatic int codepartstatic params theseparamspublic static void main(string[argsthrows ioexception system out print("enter number")system out flush()
24,991
triangle()system out println("triangle="+theanswer)/end main(//public static void rectriangle(thestack new stackx( )codepart whilestep(=false/call step(until it' true /null statement //public static boolean step(switch(codepartcase /initial call theseparams new params(thenumber )thestack push(theseparams)codepart breakcase /method entry theseparams thestack peek()if(theseparams = /test theanswer codepart /exit else codepart /recursive call breakcase /method call params newparams new params(theseparams )thestack push(newparams)codepart /go enter method breakcase /calculation theseparams thestack peek()theanswer theanswer theseparams ncodepart breakcase /method exit theseparams thestack peek()codepart theseparams returnaddress/( or thestack pop()breakcase /return point return true/end switch
24,992
/end triangle /all but //public static string getstring(throws ioexception inputstreamreader isr new inputstreamreader(system in)bufferedreader br new bufferedreader(isr)string br readline()return //public static int getint(throws ioexception string getstring()return integer parseint( )///end class stacktriangleapp this program calculates triangular numbersjust as the triangle java program at the beginning of the did here' some sample outputenter number triangle= figure shows how the sections of code in each case relate to the various parts of the algorithm figure the cases and the step(method the program simulates methodbut it has no name in the listing because it isn' real
24,993
(at case pushes the value entered by the user and return value of onto the stack and moves to the entry point of simmeth((case at its entry (case )simmeth(tests whether its argument is it accesses the argument by peeking at the top of the stack if the argument is this is the base case and control goes to simmeth()' exit (case if notit calls itself recursively (case this recursive call consists of pushing - and return address of onto the stackand going to the method entry at case on the return from the recursive callsimmeth(adds its argument to the value returned from the call finally it exits (case when it exitsit pops the last params object off the stackthis information is no longer needed the return address given in the initial call was so case is where control goes when the method returns this code returns true to let the while loop in rectriangle(know that the loop is over note that in this description of simmeth()' operation we use terms like argumentrecursive calland return address to mean simulations of these featuresnot the normal java versions if you inserted some output statements in each case to see what simmeth(was doingyou could arrange for output like thisenter number case theanswer= stackcase theanswer= stack( case theanswer= stack( case theanswer= stack( ( case theanswer= stack( ( case theanswer= stack( ( ( case theanswer= stack( ( ( case theanswer= stack( ( ( ( case theanswer= stack( ( ( ( case theanswer= stack( ( ( case theanswer= stack( ( ( case theanswer= stack( ( case theanswer= stack( ( case theanswer= stack( case theanswer= stack( case theanswer= stacktriangle= the case number shows what section of code is being executed the contents of the stack (consisting of params objects containing followed by return addressare also shown the simmeth(method is entered times (case and returns times (case it' only when it starts returning that theanswer begins to accumulate the results of the calculations what does this provein stacktriangle java we have program that more or less systematically transforms program that uses recursion into program that uses stack this suggests that such transformation is possible for any program that uses recursionand in fact this is the case
24,994
simplifying it and even eliminating the switch statement entirely to make the code more efficient in practicehoweverit' usually more practical to rethink the algorithm from the beginningusing stack-based approach instead of recursive approach listing shows what happens when we do that with the triangle(method listing the stacktriangle java program /stacktriangle java /evaluates triangular numbersstack replaces recursion /to run this programc>java stacktriangle app import java io */for / ///////////////////////////////////////////////////////////////class stackx private int maxsize/size of stack array private int[stackarrayprivate int top/top of stack //public stackx(int /constructor maxsize sstackarray new int[maxsize]top - //public void push(int /put item on top of stack stackarray[++topp//public int pop(/take item from top of stack return stackarray[top--]//public int peek(/peek at top of stack return stackarray[top]//public boolean isempty(/true if stack is empty return (top =- )///end class stackx
24,995
class stacktriangle app static int thenumberstatic int theanswerstatic stackx thestackpublic static void main(string[argsthrows ioexception system out print("enter number")system out flush()thenumber getint()stacktriangle()system out println("triangle="+theanswer)/end main(//public static void stacktriangle(thestack new stackx( )/make stack theanswer /initialize answer while(thenumber thestack push(thenumber)--thenumberwhile!thestack isempty(int newn thestack pop()theanswer +newn/until is /push value /decrement value /until stack empty/pop value/add to answer //public static string getstring(throws ioexception inputstreamreader isr new inputstreamreader(system in)bufferedreader br new bufferedreader(isr)string br readline()return //public static int getint(throws ioexception string getstring()return integer parseint( )
24,996
/end class stacktriangle app here two short while loops in the stacktriangle(method substitute for the entire step(method of the stacktriangle java program of coursein this program you can see by inspection that you can eliminate the stack entirely and use simple loop howeverin more complicated algorithms the stack must remain often you'll need to experiment to see whether recursive methoda stack-based approachor simple loop is the most efficient (or practicalway to handle particular situation part iii list advanced sorting binary trees red-black trees advanced sorting overview we discussed simple sorting in the sorts described there--the bubbleselectionand insertion sorts--are easy to implement but are rather slow in we described the mergesort it runs much faster than the simple sortsbut requires twice as much space as the original arraythis is often serious drawback this covers two advanced approaches to sortingshellsort and quicksort these sorts both operate much faster than the simple sortsthe shellsort in about ( *(logntimeand quicksort in ( *logntimewhich is the fastest time for general-purpose sorts neither of these sorts requires large amount of extra spaceas mergesort does the shellsort is almost as easy to implement as mergesortwhile quicksort is the fastest of all the general-purpose sorts we'll examine the shellsort first quicksort is based on the idea of partitioningso we'll then examine partitioning separatelybefore examining quicksort itself shellsort the shellsort is named for donald shellthe computer scientist who discovered it in it' based on the insertion sort but adds new feature that dramatically improves the insertion sort' performance the shellsort is good for medium-sized arraysperhaps up to few thousand itemsdepending on the particular implementation (howeversee the cautionary notes in about how much data can be handled by particular algorithm it' not quite
24,997
howeverit' much faster than the ( sorts like the selection sort and the insertion sortand it' very easy to implementthe code is short and simple the worst-case performance is not significantly worse than the average performance (we'll see later in this that the worst-case performance for quicksort can be much worse unless precautions are taken some experts (see sedgewick in the bibliographyrecommend starting with shellsort for almost any sorting projectand only changing to more advanced sortlike quicksortif shellsort proves too slow in practice insertion sorttoo many copies because shellsort is based on the insertion sortyou might want to review the relevant section of recall that partway through the insertion sort the items to the left of marker are internally sorted (sorted among themselvesand items to the right are not the algorithm removes the item at the marker and stores it in temporary variable thenbeginning with the item to the left of the newly vacated cellit shifts the sorted items right one cell at timeuntil the item in the temporary variable can be reinserted in sorted order here' the problem with the insertion sort suppose small item is on the far rightwhere the large items should be to move this small item to its proper place on the leftall the intervening items (between where it is and where it should bemust be shifted one space right this is close to copiesjust for one item not all the items must be moved full spacesbut the average item must be moved / spaceswhich takes times / shifts for total of / copies thus the performance of insertion sort is ( this performance could be improved if we could somehow move smaller item many spaces to the left without shifting all the intermediate items individually -sorting the shellsort achieves these large shifts by insertion-sorting widely spaced elements once these are sortedit sorts somewhat less widely spaced elementsand so on the spacing between elements for these sorts is called the increment and is traditionally represented by the letter figure shows the first step in the process of sorting element array with an increment of here the elements and are sorted figure -sorting and once and are sortedthe algorithm shifts over one cell and sorts and this process continues until all the elements have been -sortedwhich means that all items spaced cells apart are sorted among themselves the process is shown (using more
24,998
figure complete -sort after the complete -sortthe array can be thought of as comprising four subarrays( , , )( , , )( , )and ( , )each of which is completely sorted these subarrays are interleavedbut otherwise independent notice thatin this particular exampleat the end of the -sort no item is more than cells from where it would be if the array were completely sorted this is what is meant by an array being "almostsorted and is the secret of the shellsort by creating interleavedinternally sorted sets of itemswe minimize the amount of work that must be done to complete the sort nowas we noted in the insertion sort is very efficient when operating on an array that' almost sorted if it only needs to move items one or two cells to sort the fileit can operate in almost (ntime thus after the array has been -sortedwe can -sort it using the ordinary insertion sort the combination of the -sort and the -sort is much faster than simply applying the ordinary insertion sort without the preliminary -sort diminishing gaps we've shown an initial interval--or gap--of cells for sorting -cell array for larger arrays the gap should start out much larger the interval is then repeatedly reduced until it becomes for instancean array of , items might be -sortedthen -sortedthen sortedthen -sortedthen -sortedand finally -sorted the sequence of numbers used to generate the intervals (in this example is called the interval sequence or gap sequence the particular interval sequence shown hereattributed to knuth (see the bibliography)is popular one in reversed formstarting from it' generated by the recursive expression * where the initial value of is the first two columns of table show how this formula generates the sequence table knuth' interval sequence
24,999
* ( - there are other approaches to generating the interval sequencewe'll return to this issue later firstwe'll explore how the shellsort works using knuth' sequence in the sorting algorithmthe sequence-generating formula is first used in short loop to figure out the initial gap value of is used for the first value of hand the = * + formula is applied to generate the sequence and so on this process ends when the gap is larger than the array for , -element arraythe th number in the sequence is too large thus we begin the sorting process with the th-largest numbercreating -sort theneach time through the outer loop of the sorting routinewe reduce the interval using the inverse of the formula previously givenh ( - this is shown in the third column of table this inverse formula generates the reverse sequence starting with each of these numbers is used to -sort the array when the array has been -sortedthe algorithm is done the shellsort workshop applet you can use the shellsort workshop applet to see how this sort works figure shows the applet after all the bars have been -sortedjust as the -sort begins