id
int64
0
25.6k
text
stringlengths
0
4.59k
22,600
simple sorting figure the bubblesort applet with bars figure the partly sorted bars if you started sort with run and the arrows are whizzing aroundyou can freeze the process at any point by pressing the step button you can then single-step to watch the details of the operation or press run again to return to high-speed mode the draw button sometimes while running the sorting algorithm at full speedthe computer takes time off to perform some other task this can result in some bars not being drawn if this happensyou can press the draw button to redraw all the bars doing so pauses the runso you'll need to press the run button again to continue
22,601
you can press draw at any time there seems to be glitch in the display java code for bubble sort in the bubblesort java programshown in listing class called arraybub encapsulates an array []which holds variables of type long in more serious programthe data would probably consist of objectsbut we use primitive type for simplicity (we'll see how objects are sorted in the objectsort java program in listing alsoto reduce the size of the listingwe don' show find(and delete(methods with the arraybub classalthough they would normally be part of such class listing the bubblesort java program /bubblesort java /demonstrates bubble sort /to run this programc>java bubblesortapp ///////////////////////////////////////////////////////////////class arraybub private long[ /ref to array private int nelems/number of data items //public arraybub(int max/constructor new long[max]/create the array nelems /no items yet //public void insert(long value/put element into array [nelemsvalue/insert it nelems++/increment size //public void display(/displays array contents for(int = <nelemsj++/for each elementsystem out print( [ ")/display it system out println("")//public void bubblesort(
22,602
simple sorting listing continued int outinfor(out=nelems- out> out--/outer loop (backwardfor(in= in<outin++/inner loop (forwardifa[ina[in+ /out of orderswap(inin+ )/swap them /end bubblesort(//private void swap(int oneint twolong temp [one] [onea[two] [twotemp///end class arraybub ///////////////////////////////////////////////////////////////class bubblesortapp public static void main(string[argsint maxsize /array size arraybub arr/reference to array arr new arraybub(maxsize)/create the array arr insert( )arr insert( )arr insert( )arr insert( )arr insert( )arr insert( )arr insert( )arr insert( )arr insert( )arr insert( )/insert items arr display()/display items arr bubblesort()/bubble sort them
22,603
listing continued arr display()/display them again /end main(/end class bubblesortapp ///////////////////////////////////////////////////////////////the constructor and the insert(and display(methods of this class are similar to those we've seen before howeverthere' new methodbubblesort(when this method is invoked from main()the contents of the array are rearranged into sorted order the main(routine inserts items into the array in random orderdisplays the arraycalls bubblesort(to sort itand then displays it again here' the output the bubblesort(method is only four lines long here it isextracted from the listingpublic void bubblesort(int outinfor(out=nelems- out> out--for(in= in<outin++ifa[ina[in+ swap(inin+ )/end bubblesort(/outer loop (backward/inner loop (forward/out of order/swap them the idea is to put the smallest item at the beginning of the array (index and the largest item at the end (index nelems- the loop counter out in the outer for loop starts at the end of the arrayat nelems- and decrements itself each time through the loop the items at indices greater than out are always completely sorted the out variable moves left after each pass by in so that items that are already sorted are no longer involved in the algorithm the inner loop counter in starts at the beginning of the array and increments itself each cycle of the inner loopexiting when it reaches out within the inner loopthe two array cells pointed to by in and in+ are comparedand swapped if the one in in is larger than the one in in+ for claritywe use separate swap(method to carry out the swap it simply exchanges the two values in the two array cellsusing temporary variable to hold the value of the first cell while the first cell takes on the value in the second and
22,604
simple sorting then setting the second cell to the temporary value actuallyusing separate swap(method may not be good idea in practice because the function call adds small amount of overhead if you're writing your own sorting routineyou may prefer to put the swap instructions in line to gain slight increase in speed invariants in many algorithms there are conditions that remain unchanged as the algorithm proceeds these conditions are called invariants recognizing invariants can be useful in understanding the algorithm in certain situations they may also be helpful in debuggingyou can repeatedly check that the invariant is trueand signal an error if it isn' in the bubblesort java programthe invariant is that the data items to the right of out are sorted this remains true throughout the running of the algorithm (on the first passnothing has been sorted yetand there are no items to the right of out because it starts on the rightmost element efficiency of the bubble sort as you can see by watching the bubblesort workshop applet with barsthe inner and inner+ arrows make nine comparisons on the first passeight on the secondand so ondown to one comparison on the last pass for itemsthis is in generalwhere is the number of items in the arraythere are - comparisons on the first passn- on the secondand so on the formula for the sum of such series is ( - ( - ( - *( - )/ *( - )/ is ( * / when is thusthe algorithm makes about / comparisons (ignoring the - which doesn' make much differenceespecially if is large there are fewer swaps than there are comparisons because two bars are swapped only if they need to be if the data is randoma swap is necessary about half the timeso there will be about / swaps (although in the worst casewith the initial data inversely sorteda swap is necessary with every comparison both swaps and comparisons are proportional to because constants don' count in big notationwe can ignore the and the and say that the bubble sort runs in ( time this is slowas you can verify by running the bubblesort workshop applet with bars
22,605
whenever you see one loop nested within anothersuch as those in the bubble sort and the other sorting algorithms in this you can suspect that an algorithm runs in ( time the outer loop executes timesand the inner loop executes (or perhaps divided by some constanttimes for each cycle of the outer loop this means you're doing something approximately * or times selection sort the selection sort improves on the bubble sort by reducing the number of swaps necessary from ( to (nunfortunatelythe number of comparisons remains ( howeverthe selection sort can still offer significant improvement for large records that must be physically moved around in memorycausing the swap time to be much more important than the comparison time (typicallythis isn' the case in javawhere references are moved aroundnot entire objects selection sort on the baseball players let' consider the baseball players again in the selection sortyou can no longer compare only players standing next to each other thusyou'll need to remember certain player' heightyou can use notebook to write it down magenta-colored towel will also come in handy brief description what' involved in the selection sort is making pass through all the players and picking (or selectinghence the name of the sortthe shortest one this shortest player is then swapped with the player on the left end of the lineat position now the leftmost player is sorted and won' need to be moved again notice that in this algorithm the sorted players accumulate on the left (lower indices)whereas in the bubble sort they accumulated on the right the next time you pass down the row of playersyou start at position andfinding the minimumswap with position this process continues until all the players are sorted more detailed description in more detailstart at the left end of the line of players record the leftmost player' height in your notebook and throw the magenta towel on the ground in front of this person then compare the height of the next player to the right with the height in your notebook if this player is shortercross out the height of the first player and record the second player' height instead also move the towelplacing it in front of this new "shortest(for the time beingplayer continue down the rowcomparing each player with the minimum change the minimum value in your notebook and move the towel whenever you find shorter player when you're donethe magenta towel will be in front of the shortest player
22,606
simple sorting swap this shortest player with the player on the left end of the line you've now sorted one player you've made - comparisonsbut only one swap on the next passyou do exactly the same thingexcept that you can completely ignore the player on the left because this player has already been sorted thusthe algorithm starts the second pass at position instead of with each succeeding passone more player is sorted and placed on the leftand one less player needs to be considered when finding the new minimum figure shows how this sort looks for the first three passes the selectsort workshop applet to see how the selection sort looks in actiontry out the selectsort workshop applet the buttons operate the same way as those in the bubblesort applet use new to create new array of randomly arranged bars the red arrow called outer starts on the leftit points to the leftmost unsorted bar graduallyit will move right as more bars are added to the sorted group on its left the magenta min arrow also starts out pointing to the leftmost barit will move to record the shortest bar found so far (the magenta min arrow corresponds to the towel in the baseball analogy the blue inner arrow marks the bar currently being compared with the minimum as you repeatedly press stepinner moves from left to rightexamining each bar in turn and comparing it with the bar pointed to by min if the inner bar is shortermin jumps over to this newshorter bar when inner reaches the right end of the graphmin points to the shortest of the unsorted bars this bar is then swapped with outerthe leftmost unsorted bar figure shows the situation midway through sort the bars to the left of outer are sortedand inner has scanned from outer to the right endlooking for the shortest bar the min arrow has recorded the position of this barwhich will be swapped with outer use the size button to switch to barsand sort random arrangement you'll see how the magenta min arrow hangs out with perspective minimum value for while and then jumps to new one when the blue inner arrow finds smaller candidate the red outer arrow moves slowly but inexorably to the rightas the sorted bars accumulate to its left
22,607
swap minimum minimum (no swapsorted swap minimum sorted swap minimum sorted figure selection sort on baseball players
22,608
figure simple sorting the selectsort workshop applet java code for selection sort the listing for the selectsort java program is similar to that for bubblesort javaexcept that the container class is called arraysel instead of arraybuband the bubblesort(method has been replaced by selectsort(here' how this method lookspublic void selectionsort(int outinminfor(out= out<nelems- out++/outer loop min out/minimum for(in=out+ in<nelemsin++/inner loop if( [ina[min/if min greatermin in/we have new min swap(outmin)/swap them /end for(out/end selectionsort(the outer loopwith loop variable outstarts at the beginning of the array (index and proceeds toward higher indices the inner loopwith loop variable inbegins at out and likewise proceeds to the right at each new position of inthe elements [inand [minare compared if [inis smallerthen min is given the value of in at the end of the inner loopmin points to
22,609
the minimum valueand the array elements pointed to by out and min are swapped listing shows the complete selectsort java program listing the selectsort java program /selectsort java /demonstrates selection sort /to run this programc>java selectsortapp ///////////////////////////////////////////////////////////////class arraysel private long[ /ref to array private int nelems/number of data items //public arraysel(int max/constructor new long[max]/create the array nelems /no items yet //public void insert(long value/put element into array [nelemsvalue/insert it nelems++/increment size //public void display(/displays array contents for(int = <nelemsj++/for each elementsystem out print( [ ")/display it system out println("")//public void selectionsort(int outinminfor(out= out<nelems- out++/outer loop min out/minimum for(in=out+ in<nelemsin++/inner loop if( [ina[min/if min greatermin in/we have new min
22,610
simple sorting listing continued swap(outmin)/swap them /end for(out/end selectionsort(//private void swap(int oneint twolong temp [one] [onea[two] [twotemp///end class arraysel ///////////////////////////////////////////////////////////////class selectsortapp public static void main(string[argsint maxsize /array size arraysel arr/reference to array arr new arraysel(maxsize)/create the array arr insert( )arr insert( )arr insert( )arr insert( )arr insert( )arr insert( )arr insert( )arr insert( )arr insert( )arr insert( )/insert items arr display()/display items arr selectionsort()/selection-sort them arr display()/end main(/end class selectsortapp /display them again ///////////////////////////////////////////////////////////////
22,611
the output from selectsort java is identical to that from bubblesort java invariant in the selectsort java programthe data items with indices less than or equal to out are always sorted efficiency of the selection sort the selection sort performs the same number of comparisons as the bubble sortn*( - )/ for data itemsthis is comparisons however items require fewer than swaps with items , comparisons are requiredbut fewer than swaps for large values of nthe comparison times will dominateso we would have to say that the selection sort runs in ( timejust as the bubble sort did howeverit is unquestionably faster because there are so few swaps for smaller values of nthe selection sort may in fact be considerably fasterespecially if the swap times are much larger than the comparison times insertion sort in most cases the insertion sort is the best of the elementary sorts described in this it still executes in ( timebut it' about twice as fast as the bubble sort and somewhat faster than the selection sort in normal situations it' also not too complexalthough it' slightly more involved than the bubble and selection sorts it' often used as the final stage of more sophisticated sortssuch as quicksort insertion sort on the baseball players to begin the insertion sortstart with your baseball players lined up in random order (they wanted to play gamebut clearly there' no time for that it' easier to think about the insertion sort if we begin in the middle of the processwhen the team is half sorted partial sorting at this point there' an imaginary marker somewhere in the middle of the line (maybe you threw red -shirt on the ground in front of player the players to the left of this marker are partially sorted this means that they are sorted among themselveseach one is taller than the person to his or her left howeverthe players aren' necessarily in their final positions because they may still need to be moved when previously unsorted players are inserted between them
22,612
simple sorting note that partial sorting did not take place in the bubble sort and selection sort in these algorithms group of data items was completely sorted at any given timein the insertion sort group of items is only partially sorted the marked player the player where the marker iswhom we'll call the "markedplayerand all the players on her rightare as yet unsorted this is shown in figure "markedplayer partially sorted bto be shifted (taller than marked playerempty space cinserted shifted internally sorted figure the insertion sort on baseball players "markedplayer
22,613
what we're going to do is insert the marked player in the appropriate place in the (partiallysorted group howeverto do thiswe'll need to shift some of the sorted players to the right to make room to provide space for this shiftwe take the marked player out of line (in the program this data item is stored in temporary variable this step is shown in figure now we shift the sorted players to make room the tallest sorted player moves into the marked player' spotthe next-tallest player into the tallest player' spotand so on when does this shifting process stopimagine that you and the marked player are walking down the line to the left at each position you shift another player to the rightbut you also compare the marked player with the player about to be shifted the shifting process stops when you've shifted the last player that' taller than the marked player the last shift opens up the space where the marked playerwhen insertedwill be in sorted order this step is shown in figure now the partially sorted group is one player biggerand the unsorted group is one player smaller the marker -shirt is moved one space to the rightso it' again in front of the leftmost unsorted player this process is repeated until all the unsorted players have been inserted (hence the name insertion sortinto the appropriate place in the partially sorted group the insertsort workshop applet use the insertsort workshop applet to demonstrate the insertion sort unlike the other sorting appletsit' probably more instructive to begin with random bars rather than sorting bars change to bars with the size buttonand click run to watch the bars sort themselves before your very eyes you'll see that the short red outer arrow marks the dividing line between the partially sorted bars to the left and the unsorted bars to the right the blue inner arrow keeps starting from outer and zipping to the leftlooking for the proper place to insert the marked bar figure shows how this process looks when about half the bars are partially sorted the marked bar is stored in the temporary variable pointed to by the magenta arrow at the right end of the graphbut the contents of this variable are replaced so often that it' hard to see what' there (unless you slow down to single-step modesorting bars to get down to the detailsuse size to switch to bars (if necessaryuse new to make sure they're in random order
22,614
figure simple sorting the insertsort workshop applet with bars at the beginninginner and outer point to the second bar from the left (array index )and the first message is will copy outer to temp this will make room for the shift (there' no arrow for inner- but of course it' always one bar to the left of inner click the step button the bar at outer will be copied to temp we say that items are copied from source to destination when performing copythe applet removes the bar from the source locationleaving blank this is slightly misleading because in real java program the reference in the source would remain there howeverblanking the source makes it easier to see what' happening what happens next depends on whether the first two bars are already in order (smaller on the leftif they areyou'll see the message have compared inner- and tempno copy necessary if the first two bars are not in orderthe message is have compared inner- and tempwill copy inner- to inner this is the shift that' necessary to make room for the value in temp to be reinserted there' only one such shift on this first passmore shifts will be necessary on subsequent passes the situation is shown in figure on the next clickyou'll see the copy take place from inner- to inner alsothe inner arrow moves one space left the new message is now inner is so no copy necessary the shifting process is complete no matter which of the first two bars was shorterthe next click will show you will copy temp to inner this will happenbut if the first two bars were initially in orderyou won' be able to tell copy was performed because temp and inner hold the same bar copying data over the top of the same data may seem inefficientbut the algorithm runs faster if it doesn' check for this possibilitywhich happens comparatively infrequently
22,615
figure the insertsort workshop applet with bars now the first two bars are partially sorted (sorted with respect to each other)and the outer arrow moves one space rightto the third bar (index the process repeatswith the will copy outer to temp message on this pass through the sorted datathere may be no shiftsone shiftor two shiftsdepending on where the third bar fits among the first two continue to single-step the sorting process againyou can see what' happening more easily after the process has run long enough to provide some sorted bars on the left then you can see how just enough shifts take place to make room for the reinsertion of the bar from temp into its proper place java code for insertion sort here' the method that carries out the insertion sortextracted from the insertsort java programpublic void insertionsort(int inoutfor(out= out<nelemsout++/out is dividing line long temp [out]/remove marked item in out/start shifts at out while(in> & [in- >temp/until one is smallera[ina[in- ]/shift item right
22,616
simple sorting --ina[intemp/end for /end insertionsort(/go left one position /insert marked item in the outer for loopout starts at and moves right it marks the leftmost unsorted data in the inner while loopin starts at out and moves leftuntil either temp is smaller than the array element thereor it can' go left any further each pass through the while loop shifts another sorted element one space right it may be hard to see the relation between the steps in the insertsort workshop applet and the codeso figure is an activity diagram of the insertionsort(methodwith the corresponding messages from the insertsort workshop applet listing shows the complete insertsort java program outer= [outer==nelems"will copy outer to temp[elsetemp= [outerinner=outer "will copy temp to inner[else[inner> [inner]=temp outer+"have compared inner- and temp no copy necessary[elsea[inner- >=temp [inner]= [inner- --inner figure activity diagram for insertsort("have compared inner- and temp will copy inner- to inner
22,617
listing the insertsort java program /insertsort java /demonstrates insertion sort /to run this programc>java insertsortapp //class arrayins private long[ /ref to array private int nelems/number of data items //public arrayins(int max/constructor new long[max]/create the array nelems /no items yet //public void insert(long value/put element into array [nelemsvalue/insert it nelems++/increment size //public void display(/displays array contents for(int = <nelemsj++/for each elementsystem out print( [ ")/display it system out println("")//public void insertionsort(int inoutfor(out= out<nelemsout++/out is dividing line long temp [out]/remove marked item in out/start shifts at out while(in> & [in- >temp/until one is smallera[ina[in- ]/shift item to right --in/go left one position
22,618
simple sorting listing continued [intemp/insert marked item /end for /end insertionsort(///end class arrayins ///////////////////////////////////////////////////////////////class insertsortapp public static void main(string[argsint maxsize /array size arrayins arr/reference to array arr new arrayins(maxsize)/create the array arr insert( )arr insert( )arr insert( )arr insert( )arr insert( )arr insert( )arr insert( )arr insert( )arr insert( )arr insert( )/insert items arr display()/display items arr insertionsort()/insertion-sort them arr display()/display them again /end main(/end class insertsortapp ///////////////////////////////////////////////////////////////here' the output from the insertsort java programit' the same as that from the other programs in this
22,619
invariants in the insertion sort at the end of each passfollowing the insertion of the item from tempthe data items with smaller indices than outer are partially sorted efficiency of the insertion sort how many comparisons and copies does this algorithm requireon the first passit compares maximum of one item on the second passit' maximum of two itemsand so onup to maximum of - comparisons on the last pass this is - *( - )/ howeverbecause on each pass an average of only half of the maximum number of items are actually compared before the insertion point is foundwe can divide by which gives *( - )/ the number of copies is approximately the same as the number of comparisons howevera copy isn' as time-consuming as swapso for random data this algorithm runs twice as fast as the bubble sort and faster than the selection sort in any caselike the other sort routines in this the insertion sort runs in ( time for random data for data that is already sorted or almost sortedthe insertion sort does much better when data is in orderthe condition in the while loop is never trueso it becomes simple statement in the outer loopwhich executes - times in this case the algorithm runs in (ntime if the data is almost sortedinsertion sort runs in almost (ntimewhich makes it simple and efficient way to order file that is only slightly out of order howeverfor data arranged in inverse sorted orderevery possible comparison and shift is carried outso the insertion sort runs no faster than the bubble sort you can check this using the reverse-sorted data option (toggled with newin the insertsort workshop applet sorting objects for simplicity we've applied the sorting algorithms we've looked at thus far to primitive data typelong howeversorting routines will more likely be applied to objects than primitive types accordinglywe show java program in listing objectsort javathat sorts an array of person objects (last seen in the classdataarray java program in
22,620
simple sorting java code for sorting objects the algorithm used in our java program is the insertion sort from the preceding section the person objects are sorted on lastnamethis is the key field the objectsort java program is shown in listing listing the objectsort java program /objectsort java /demonstrates sorting objects (uses insertion sort/to run this programc>java objectsortapp ///////////////////////////////////////////////////////////////class person private string lastnameprivate string firstnameprivate int age//public person(string laststring firstint /constructor lastname lastfirstname firstage //public void displayperson(system out print(last namelastname)system out print("first namefirstname)system out println("ageage)//public string getlast(/get last name return lastname/end class person ///////////////////////////////////////////////////////////////class arrayinob private person[ /ref to array private int nelems/number of data items //public arrayinob(int max/constructor
22,621
listing continued new person[max]/create the array nelems /no items yet ///put person into array public void insert(string laststring firstint agea[nelemsnew person(lastfirstage)nelems++/increment size //public void display(/displays array contents for(int = <nelemsj++/for each elementa[jdisplayperson()/display it system out println("")//public void insertionsort(int inoutfor(out= out<nelemsout++person temp [out]in out/out is dividing line /remove marked person /start shifting at out while(in> &/until smaller one founda[in- getlast(compareto(temp getlast())> [ina[in- ]/shift item to the right --in/go left one position [intemp/insert marked item /end for /end insertionsort(///end class arrayinob ///////////////////////////////////////////////////////////////class objectsortapp
22,622
simple sorting listing continued public static void main(string[argsint maxsize /array size arrayinob arr/reference to array arr new arrayinob(maxsize)/create the array arr insert("evans""patty" )arr insert("smith""doc" )arr insert("smith""lorraine" )arr insert("smith""paul" )arr insert("yee""tom" )arr insert("hashimoto""sato" )arr insert("stimson""henry" )arr insert("velasquez""jose" )arr insert("vang""minh" )arr insert("creswell""lucinda" )system out println("before sorting:")arr display()/display items arr insertionsort()/insertion-sort them system out println("after sorting:")arr display()/display them again /end main(/end class objectsortapp ///////////////////////////////////////////////////////////////here' the output of this programbefore sortinglast nameevansfirst namepattyage last namesmithfirst namedocage last namesmithfirst namelorraineage last namesmithfirst namepaulage last nameyeefirst nametomage last namehashimotofirst namesatoage last namestimsonfirst namehenryage last namevelasquezfirst namejoseage last namevangfirst nameminhage last namecreswellfirst namelucindaage
22,623
after sortinglast namecreswellfirst namelucindaage last nameevansfirst namepattyage last namehashimotofirst namesatoage last namesmithfirst namedocage last namesmithfirst namelorraineage last namesmithfirst namepaulage last namestimsonfirst namehenryage last namevangfirst nameminhage last namevelasquezfirst namejoseage last nameyeefirst nametomage lexicographical comparisons the insertsort(method in objectsort java is similar to that in insertsort javabut it has been adapted to compare the lastname key values of records rather than the value of primitive type we use the compareto(method of the string class to perform the comparisons in the insertsort(method here' the expression that uses ita[in- getlast(compareto(temp getlast() the compareto(method returns different integer values depending on the lexicographical (that isalphabeticalordering of the string for which it' invoked and the string passed to it as an argumentas shown in table table operation of the compareto(method compareto( return value < > equals for exampleif is "catand is "dog"the function will return number less than in the objectsort java programthis method is used to compare the last name of [in- with the last name of temp stability sometimes it matters what happens to data items that have equal keys for exampleyou may have employee data arranged alphabetically by last names (that isthe last names were used as key values in the sort now you want to sort the data by zip codebut you want all the items with the same zip code to continue to be sorted by
22,624
simple sorting last names you want the algorithm to sort only what needs to be sortedand leave everything else in its original order some sorting algorithms retain this secondary orderingthey're said to be stable all the algorithms in this are stable for examplenotice the output of the objectsort java program (listing three persons have the last name of smith initiallythe order is doc smithlorraine smithand paul smith after the sortthis ordering is preserveddespite the fact that the various smith objects have been moved to new locations comparing the simple sorts there' probably no point in using the bubble sortunless you don' have your algorithm book handy the bubble sort is so simple that you can write it from memory even soit' practical only if the amount of data is small (for discussion of what "smallmeanssee "when to use what "the selection sort minimizes the number of swapsbut the number of comparisons is still high this sort might be useful when the amount of data is small and swapping data items is very time-consuming compared with comparing them the insertion sort is the most versatile of the three and is the best bet in most situationsassuming the amount of data is small or the data is almost sorted for larger amounts of dataquicksort is generally considered the fastest approachwe'll examine quicksort in we've compared the sorting algorithms in terms of speed another consideration for any algorithm is how much memory space it needs all three of the algorithms in this carry out their sort in placemeaning thatbesides the initial arrayvery little extra memory is required all the sorts require an extra variable to store an item temporarily while it' being swapped you can recompile the example programssuch as bubblesort javato sort larger amounts of data by timing them for larger sortsyou can get an idea of the differences between them and the time required to sort different amounts of data on your particular system summary the sorting algorithms in this all assume an array as data storage structure sorting involves comparing the keys of data items in the array and moving the items (actuallyreferences to the itemsaround until they're in sorted order
22,625
all the algorithms in this execute in ( time neverthelesssome can be substantially faster than others an invariant is condition that remains unchanged while an algorithm runs the bubble sort is the least efficientbut the simplestsort the insertion sort is the most commonly used of the ( sorts described in this sort is stable if the order of elements with the same key is retained none of the sorts in this require more than single temporary variablein addition to the original array questions these questions are intended as self-test for readers answers may be found in appendix computer sorting algorithms are more limited than humans in that humans are better at inventing new algorithms computers can handle only fixed amount of data humans know what to sortwhereas computers need to be told computers can compare only two things at time the two basic operations in simple sorting are items and them (or sometimes them true or falsethe bubble sort always ends up comparing every item with every other item the bubble sort algorithm alternates between comparing and swapping moving and copying moving and comparing copying and comparing true or falseif there are itemsthe bubble sort makes exactly * comparisons
22,626
simple sorting in the selection sorta the largest keys accumulate on the left (low indicesb minimum key is repeatedly discovered number of items must be shifted to insert each item in its correctly sorted position the sorted items accumulate on the right true or falseifin particular sorting situationswaps take much longer than comparisonsthe selection sort is about twice as fast as the bubble sort copy is times as fast as swap what is the invariant in the selection sort in the insertion sortthe "marked playerdescribed in the text corresponds to which variable in the insertsort java programa in out temp [out in the insertion sort"partially sortedmeans that some items are already sortedbut they may need to be moved most items are in their final sorted positionsbut few still need to be sorted only some of the items are sorted group items are sorted among themselvesbut items outside the group may need to be inserted in it shifting group of items left or right requires repeated in the insertion sortafter an item is inserted in the partially sorted groupit will never be moved again never be shifted to the left often be moved out of this group find that its group is steadily shrinking
22,627
the invariant in the insertion sort is that stability might refer to items with secondary keys being excluded from sort keeping cities sorted by increasing population within each statein sort by state keeping the same first names matched with the same last names items keeping the same order of primary keys without regard to secondary keys experiments carrying out these experiments will help to provide insights into the topics covered in the no programming is involved in bubblesort java (listing rewrite main(so it creates large array and fills that array with data you can use the following code to generate random numbersfor(int = <maxsizej++/fill array with /random numbers long (long)java lang math random()*(maxsize- )arr insert( )try inserting , items display the data before and after the sort you'll see that scrolling the display takes long time comment out the calls to display(so you can see how long the sort itself takes the time will vary on different machines sorting , numbers will probably take less than seconds pick an array size that takes about this long and time it then use the same array size to time selectsort java (listing and insertsort java (listing see how the speeds of these three sorts compare devise some code to insert data in inversely sorted order ( , , , into bubblesort java use the same amount of data as in experiment see how fast the sort runs compared with the random data in experiment repeat this experiment with selectsort java and insertsort java write code to insert data in already-sorted order ( into bubblesort java see how fast the sort runs compared with experiments and repeat this experiment with selectsort java and insertsort java
22,628
simple sorting programming projects writing programs that solve the programming projects helps to solidify your understanding of the material and demonstrates how the concepts are applied (as noted in the introductionqualified instructors may obtain completed solutions to the programming projects on the publisher' web site in the bubblesort java program (listing and the bubblesort workshop appletthe in index always goes from left to rightfinding the largest item and carrying it toward out on the right modify the bubblesort(method so that it' bidirectional this means the in index will first carry the largest item from left to right as beforebut when it reaches outit will reverse and carry the smallest item from right to left you'll need two outer indexesone on the right (the old outand another on the left add method called median(to the arrayins class in the insertsort java program (listing this method should return the median value in the array (recall that in group of numbers half are larger than the median and half are smaller do it the easy way to the insertsort java program (listing )add method called nodups(that removes duplicates from previously sorted array without disrupting the order (you can use the insertionsort(method to sort the dataor you can simply use main(to insert the data in sorted order one can imagine schemes in which all the items from the place where duplicate was discovered to the end of the array would be shifted down one space every time duplicate was discoveredbut this would lead to slow ( timeat least when there were lot of duplicates in your algorithmmake sure no item is moved more than onceno matter how many duplicates there are this will give you an algorithm with (ntime another simple sort is the odd-even sort the idea is to repeatedly make two passes through the array on the first pass you look at all the pairs of itemsa[jand [ + ]where is odd ( if their key values are out of orderyou swap them on the second pass you do the same for all the even values ( you do these two passes repeatedly until the array is sorted replace the bubblesort(method in bubblesort java (listing with an oddevensort(method make sure it works for varying amounts of data you'll need to figure out how many times to do the two passes the odd-even sort is actually useful in multiprocessing environmentwhere separate processor can operate on each odd pair simultaneously and then on each even pair because the odd pairs are independent of each othereach pair can be checked--and swappedif necessary--by different processor this makes for very fast sort
22,629
modify the insertionsort(method in insertsort java (listing so it counts the number of copies and the number of comparisons it makes during sort and displays the totals to count comparisonsyou'll need to break up the double condition in the inner while loop use this program to measure the number of copies and comparisons for different amounts of inversely sorted data do the results verify ( efficiencydo the same for almost-sorted data (only few items out of placewhat can you deduce about the efficiency of this algorithm for almost-sorted data here' an interesting way to remove duplicates from an array the insertion sort uses loop-within- -loop algorithm that compares every item in the array with every other item if you want to remove duplicatesthis is one way to start (see also exercise in modify the insertionsort(method in the insertsort java program so that it removes duplicates as it sorts here' one approachwhen duplicate is foundwrite over one of the duplicated items with key value less than any normally used (such as - if all the normal keys are positivethen the normal insertion sort algorithmtreating this new key like any other itemwill put it at index from now on the algorithm can ignore this item the next duplicate will go at index and so on when the sort is finishedall the removed dups (now represented by - valueswill be found at the beginning of the array the array can then be resized and shifted down so it starts at
22,630
stacks and queues in this different kind of structure stacks queues in this we'll examine three data storage structuresthe stackthe queueand the priority queue we'll begin by discussing how these structures differ from arraysthen we'll examine each one in turn in the last sectionwe'll look at an operation in which the stack plays significant roleparsing arithmetic expressions different kind of structure there are significant differences between the data structures and algorithms we've seen in previous and those we'll look at now we'll discuss three of these differences before we examine the new structures in detail programmer' tools arrays--the data storage structure we've been examining thus far--as well as many other structures we'll encounter later in this book (linked liststreesand so onare appropriate for the kind of data you might find in database application they're typically used for personnel recordsinventoriesfinancial dataand so on--data that corresponds to real-world objects or activities these structures facilitate access to datathey make it easy to insertdeleteand search for particular items the structures and algorithms we'll examine in this on the other handare more often used as programmer' tools they're primarily conceptual aids rather than full-fledged data storage devices their lifetime is typically shorter than that of the database-type structures they are created and used to carry out particular task during the operation of programwhen the task is completedthey're discarded priority queues parsing arithmetic expressions
22,631
stacks and queues restricted access in an arrayany item can be accessedeither immediately--if its index number is known--or by searching through sequence of cells until it' found in the data structures in this howeveraccess is restrictedonly one item can be read or removed at given time (unless you cheatthe interface of these structures is designed to enforce this restricted access access to other items is (in theorynot allowed more abstract stacksqueuesand priority queues are more abstract entities than arrays and many other data storage structures they're defined primarily by their interfacethe permissible operations that can be carried out on them the underlying mechanism used to implement them is typically not visible to their user the underlying mechanism for stackfor examplecan be an arrayas shown in this or it can be linked list the underlying mechanism for priority queue can be an array or special kind of tree called heap we'll return to the topic of one data structure being implemented by another when we discuss abstract data types (adtsin "linked lists stacks stack allows access to only one data itemthe last item inserted if you remove this itemyou can access the next-to-last item insertedand so on this capability is useful in many programming situations in this section we'll see how stack can be used to check whether parenthesesbracesand brackets are balanced in computer program source file at the end of this we'll see stack playing vital role in parsing (analyzingarithmetic expressions such as *( + stack is also handy aid for algorithms applied to certain complex data structures in "binary trees,we'll see it used to help traverse the nodes of tree in "graphs,we'll apply it to searching the vertices of graph ( technique that can be used to find your way out of mazemost microprocessors use stack-based architecture when method is calledits return address and arguments are pushed onto stackand when it returnsthey're popped off the stack operations are built into the microprocessor some older pocket calculators used stack-based architecture instead of entering arithmetic expressions using parenthesesyou pushed intermediate results onto stack we'll learn more about this approach when we discuss parsing arithmetic expressions in the last section in this
22,632
the postal analogy to understand the idea of stackconsider an analogy provided by the postal service many peoplewhen they get their mailtoss it onto stack on the hall table or into an "inbasket at work thenwhen they have spare momentthey process the accumulated mail from the top down firstthey open the letter on the top of the stack and take appropriate action--paying the billthrowing it awayor whatever after the first letter has been disposed ofthey examine the next letter downwhich is now the top of the stackand deal with that eventuallythey work their way down to the letter on the bottom of the stack (which is now the topfigure shows stack of mail this letter processed first newly arrived letters placed on top of stack figure stack of letters this "do the top one firstapproach works all right as long as you can easily process all the mail in reasonable time if you can'tthere' the danger that letters on the bottom of the stack won' be examined for monthsand the bills they contain will become overdue
22,633
stacks and queues of coursemany people don' rigorously follow this top-to-bottom approach they mayfor exampletake the mail off the bottom of the stackso as to process the oldest letter first or they might shuffle through the mail before they begin processing it and put higher-priority letters on top in these casestheir mail system is no longer stack in the computer-science sense of the word if they take letters off the bottomit' queueand if they prioritize itit' priority queue we'll look at these possibilities later another stack analogy is the tasks you perform during typical workday you're busy on long-term project ( )but you're interrupted by coworker asking you for temporary help with another project (bwhile you're working on bsomeone in accounting stops by for meeting about travel expenses ( )and during this meeting you get an emergency call from someone in sales and spend few minutes troubleshooting bulky product (dwhen you're done with call dyou resume meeting cwhen you're done with cyou resume project band when you're done with byou can (finally!get back to project lower-priority projects are "stacked upwaiting for you to return to them placing data item on the top of the stack is called pushing it removing it from the top of the stack is called popping it these are the primary stack operations stack is said to be last-in-first-out (lifostorage mechanism because the last item inserted is the first one to be removed the stack workshop applet let' use the stack workshop applet to get an idea how stacks work when you start up this appletyou'll see four buttonsnewpushpopand peekas shown in figure figure the stack workshop applet
22,634
the stack workshop applet is based on an arrayso you'll see an array of data items although it' based on an arraya stack restricts accessso you can' access elements using an index in factthe concept of stack and the underlying data structure used to implement it are quite separate as we noted earlierstacks can also be implemented by other kinds of storage structuressuch as linked lists the new button the stack in the workshop applet starts off with four data items already inserted if you want to start with an empty stackthe new button creates new stack with no items the next three buttons carry out the significant stack operations the push button to insert data item on the stackuse the button labeled push after the first press of this buttonyou'll be prompted to enter the key value of the item to be pushed after you type the value into the text fielda few more presses will insert the item on the top of the stack red arrow always points to the top of the stack--that isthe last item inserted notice howduring the insertion processone step (button pressincrements (moves upthe top arrowand the next step actually inserts the data item into the cell if you reversed the orderyou would overwrite the existing item at top when you're writing the code to implement stackit' important to keep in mind the order in which these two steps are executed if the stack is full and you try to push another itemyou'll get the can' insertstack is full message (theoreticallyan adt stack doesn' become fullbut the array implementing it does the pop button to remove data item from the top of the stackuse the pop button the value popped appears in the number text fieldthis corresponds to pop(routine returning value againnotice the two steps involvedfirstthe item is removed from the cell pointed to by topthen top is decremented to point to the highest occupied cell this is the reverse of the sequence used in the push operation the pop operation shows an item actually being removed from the array and the cell color becoming gray to show the item has been removed this is bit misleadingin that deleted items actually remain in the array until written over by new data howeverthey cannot be accessed after the top marker drops below their positionso conceptually they are goneas the applet shows after you've popped the last item off the stackthe top arrow points to - below the lowest cell this position indicates that the stack is empty if the stack is empty and you try to pop an itemyou'll get the can' popstack is empty message
22,635
stacks and queues the peek button push and pop are the two primary stack operations howeverit' sometimes useful to be able to read the value from the top of the stack without removing it the peek operation does this by pushing the peek button few timesyou'll see the value of the item at top copied to the number text fieldbut the item is not removed from the stackwhich remains unchanged notice that you can peek only at the top item by designall the other items are invisible to the stack user stack size stacks are typically smalltemporary data structureswhich is why we've shown stack of only cells of coursestacks in real programs may need bit more room than thisbut it' surprising how small stack needs to be very long arithmetic expressionfor examplecan be parsed with stack of only dozen or so cells java code for stack let' examine programstack javathat implements stack using class called stackx listing contains this class and short main(routine to exercise it listing the stack java program /stack java /demonstrates stacks /to run this programc>java stackapp ///////////////////////////////////////////////////////////////class stackx private int maxsize/size of stack array private long[stackarrayprivate int top/top of stack //public stackx(int /constructor maxsize /set array size stackarray new long[maxsize]/create array top - /no items yet //public void push(long /put item on top of stack stackarray[++topj/increment topinsert item
22,636
listing continued //public long pop(/take item from top of stack return stackarray[top--]/access itemdecrement top //public long peek(/peek at top of stack return stackarray[top]//public boolean isempty(/true if stack is empty return (top =- )//public boolean isfull(/true if stack is full return (top =maxsize- )///end class stackx ///////////////////////////////////////////////////////////////class stackapp public static void main(string[argsstackx thestack new stackx( )/make new stack thestack push( )/push items onto stack thestack push( )thestack push( )thestack push( )while!thestack isempty(long value thestack pop()system out print(value)system out print(")/end while system out println("")/end main(/until it' empty/delete item from stack /display it
22,637
listing stacks and queues continued /end class stackapp ///////////////////////////////////////////////////////////////the main(method in the stackapp class creates stack that can hold itemspushes items onto the stackand then displays all the items by popping them off the stack until it' empty here' the output notice how the order of the data is reversed because the last item pushed is the first one poppedthe appears first in the output this version of the stackx class holds data elements of type long as noted in "simple sorting,you can change this to any other typeincluding object types stackx class methods the constructor creates new stack of size specified in its argument the fields of the stack are made up of variable to hold its maximum size (the size of the array)the array itselfand variable topwhich stores the index of the item on the top of the stack (note that we need to specify stack size only because the stack is implemented using an array if it had been implemented using linked listfor examplethe size specification would be unnecessary the push(method increments top so it points to the space just above the previous top and stores data item there notice again that top is incremented before the item is inserted the pop(method returns the value at top and then decrements top this effectively removes the item from the stackit' inaccessiblealthough the value remains in the array (until another item is pushed into the cellthe peek(method simply returns the value at topwithout changing the stack the isempty(and isfull(methods return true if the stack is empty or fullrespectively the top variable is at - if the stack is empty and maxsize- if the stack is full figure shows how the stack class methods work error handling there are different philosophies about how to handle stack errors what happens if you try to push an item onto stack that' already full or pop an item from stack that' empty
22,638
top top new item pushed on stack top top top two items popped from stack figure operation of the stackx class methods we've left the responsibility for handling such errors up to the class user the user should always check to be sure the stack is not full before inserting an itemif!thestack isfull(insert(item)else system out print("can' insertstack is full")in the interest of simplicitywe've left this code out of the main(routine (and anywayin this simple programwe know the stack isn' full because it has just been initializedwe do include the check for an empty stack when main(calls pop(many stack classes check for these errors internallyin the push(and pop(methods this is the preferred approach in javaa good solution for stack class that discovers such errors is to throw an exceptionwhich can then be caught and processed by the class user
22,639
stacks and queues stack example reversing word for our first example of using stackwe'll examine very simple taskreversing word when you run the programit asks you to type in word when you press enterit displays the word with the letters in reverse order stack is used to reverse the letters firstthe characters are extracted one by one from the input string and pushed onto the stack then they're popped off the stack and displayed because of its last-in-first-out characteristicthe stack reverses the order of the characters listing shows the code for the reverse java program listing the reverse java program /reverse java /stack used to reverse string /to run this programc>java reverseapp import java io */for / ///////////////////////////////////////////////////////////////class stackx private int maxsizeprivate char[stackarrayprivate int top//public stackx(int max/constructor maxsize maxstackarray new char[maxsize]top - //public void push(char /put item on top of stack stackarray[++topj//public char pop(/take item from top of stack return stackarray[top--]//public char peek(/peek at top of stack return stackarray[top]
22,640
listing continued //public boolean isempty(/true if stack is empty return (top =- )///end class stackx ///////////////////////////////////////////////////////////////class reverser private string input/input string private string output/output string //public reverser(string in/constructor input in//public string dorev(/reverse the string int stacksize input length()/get max stack size stackx thestack new stackx(stacksize)/make stack for(int = <input length() ++char ch input charat( )/get char from input thestack push(ch)/push it output ""while!thestack isempty(char ch thestack pop()/pop charoutput output ch/append to output return output/end dorev(///end class reverser ///////////////////////////////////////////////////////////////class reverseapp public static void main(string[argsthrows ioexception
22,641
listing stacks and queues continued string inputoutputwhile(truesystem out print("enter string")system out flush()input getstring()/read string from kbd ifinput equals(""/quit if [enterbreak/make reverser reverser thereverser new reverser(input)output thereverser dorev()/use it system out println("reversedoutput)/end while /end main(//public static string getstring(throws ioexception inputstreamreader isr new inputstreamreader(system in)bufferedreader br new bufferedreader(isr)string br readline()return ///end class reverseapp ///////////////////////////////////////////////////////////////we've created class reverser to handle the reversing of the input string its key component is the method dorev()which carries out the reversalusing stack the stack is created within dorev()which sizes the stack according to the length of the input string in main(we get string from the usercreate reverser object with this string as an argument to the constructorcall this object' dorev(methodand display the return valuewhich is the reversed string here' some sample interaction with the programenter stringpart reversedtrap enter string
22,642
stack example delimiter matching one common use for stacks is to parse certain kinds of text strings typicallythe strings are lines of code in computer languageand the programs parsing them are compilers to give the flavor of what' involvedwe'll show program that checks the delimiters in line of text typed by the user this text doesn' need to be line of real java code (although it could be)but it should use delimiters the same way java does the delimiters are the braces and }brackets and ]and parentheses and each opening or left delimiter should be matched by closing or right delimiterthat isevery should be followed by matching and so on alsoopening delimiters that occur later in the string should be closed before those occurring earlier here are some examplesc[da{ [ ] } { ( ] } [ { } ]ea{ ( /correct /correct /not correctdoesn' match /not correctnothing matches final /not correctnothing matches opening opening delimiters on the stack this delimiter-matching program works by reading characters from the string one at time and placing opening delimiters when it finds themon stack when it reads closing delimiter from the inputit pops the opening delimiter from the top of the stack and attempts to match it with the closing delimiter if they're not the same type (there' an opening brace but closing parenthesisfor example)an error occurs alsoif there is no opening delimiter on the stack to match closing oneor if delimiter has not been matchedan error occurs delimiter that hasn' been matched is discovered because it remains on the stack after all the characters in the string have been read let' see what happens on the stack for typical correct stringa{ ( [ ] )ftable shows how the stack looks as each character is read from this string the entries in the second column show the stack contentsreading from the bottom of the stack on the left to the top on the right as the string is readeach opening delimiter is placed on the stack each closing delimiter read from the input is matched with the opening delimiter popped from the top of the stack if they form pairall is well non-delimiter characters are not inserted on the stackthey're ignored
22,643
stacks and queues table stack contents in delimiter matching character read stack contents { {{( {({ { this approach works because pairs of delimiters that are opened last should be closed first this matches the last-in-first-out property of the stack java code for brackets java the code for the parsing programbrackets javais shown in listing we've placed check()the method that does the parsingin class called bracketchecker listing the brackets java program /brackets java /stacks used to check matching brackets /to run this programc>java bracketsapp import java io */for / ///////////////////////////////////////////////////////////////class stackx private int maxsizeprivate char[stackarrayprivate int top//public stackx(int /constructor maxsize sstackarray new char[maxsize]top - /
22,644
listing continued public void push(char /put item on top of stack stackarray[++topj//public char pop(/take item from top of stack return stackarray[top--]//public char peek(/peek at top of stack return stackarray[top]//public boolean isempty(/true if stack is empty return (top =- )///end class stackx ///////////////////////////////////////////////////////////////class bracketchecker private string input/input string //public bracketchecker(string in/constructor input in//public void check(int stacksize input length()/get max stack size stackx thestack new stackx(stacksize)/make stack for(int = <input length() ++char ch input charat( )switch(chcase '{'case '['/get chars in turn /get char /opening symbols
22,645
listing stacks and queues continued case '('thestack push(ch)break/push them case '}'/closing symbols case ']'case ')'if!thestack isempty(/if stack not emptychar chx thestack pop()/pop and check if(ch=='}&chx!='{'|(ch==']&chx!='['|(ch==')&chx!='('system out println("error"+ch+at "+ )else /prematurely empty system out println("error"+ch+at "+ )breakdefault/no action on other characters break/end switch /end for /at this pointall characters have been processed if!thestack isempty(system out println("errormissing right delimiter")/end check(///end class bracketchecker ///////////////////////////////////////////////////////////////class bracketsapp public static void main(string[argsthrows ioexception string inputwhile(truesystem out print"enter string containing delimiters")system out flush()input getstring()/read string from kbd ifinput equals(""/quit if [enter
22,646
listing continued break/make bracketchecker bracketchecker thechecker new bracketchecker(input)thechecker check()/check brackets /end while /end main(//public static string getstring(throws ioexception inputstreamreader isr new inputstreamreader(system in)bufferedreader br new bufferedreader(isr)string br readline()return ///end class bracketsapp ///////////////////////////////////////////////////////////////the check(routine makes use of the stackx class from the reverse java program (listing notice how easy it is to reuse this class all the code you need is in one place this is one of the payoffs for object-oriented programming the main(routine in the bracketsapp class repeatedly reads line of text from the usercreates bracketchecker object with this text string as an argumentand then calls the check(method for this bracketchecker object if it finds any errorsthe check(method displays themotherwisethe syntax of the delimiters is correct if it canthe check(method reports the character number where it discovered the error (starting at on the leftand the incorrect character it found there for examplefor the input string { ( ] } the output from check(will be errorat the stack as conceptual aid notice how convenient the stack is in the brackets java program you could have set up an array to do what the stack doesbut you would have had to worry about keeping track of an index to the most recently added characteras well as other bookkeeping tasks the stack is conceptually easier to use by providing limited access to its contentsusing the push(and pop(methodsthe stack has made your
22,647
stacks and queues program easier to understand and less error prone (as carpenters will tell youit' safer to use the right tool for the job efficiency of stacks items can be both pushed and popped from the stack implemented in the stackx class in constant ( time that isthe time is not dependent on how many items are in the stack and is therefore very quick no comparisons or moves are necessary queues the word queue is british for line (the kind you wait inin britainto "queue upmeans to get in line in computer science queue is data structure that is somewhat like stackexcept that in queue the first item inserted is the first to be removed (first-in-first-outfifo)while in stackas we've seenthe last item inserted is the first to be removed (lifoa queue works like the line at the moviesthe first person to join the rear of the line is the first person to reach the front of the line and buy ticket the last person to line up is the last person to buy ticket (or--if the show is sold out--to fail to buy ticketfigure shows how such queue looks people join the queue at the rear people leave the queue at the front figure queue of people queues are used as programmer' tool as stacks are we'll see an example where queue helps search graph in they're also used to model real-world situations such as people waiting in line at bankairplanes waiting to take offor data packets waiting to be transmitted over the internet there are various queues quietly doing their job in your computer' (or the network'soperating system there' printer queue where print jobs wait for the
22,648
printer to be available queue also stores keystroke data as you type at the keyboard this wayif you're using word processor but the computer is briefly doing something else when you hit keythe keystroke won' be lostit waits in the queue until the word processor has time to read it using queue guarantees the keystrokes stay in order until they can be processed the queue workshop applet let' use the queue workshop applet to get an idea how queues work when you start up the appletyou'll see queue with four items preinstalledas shown in figure figure the queue workshop applet this applet demonstrates queue based on an array this is common approachalthough linked lists are also commonly used to implement queues the two basic queue operations are inserting an itemwhich is placed at the rear of the queueand removing an itemwhich is taken from the front of the queue this is similar to person joining the rear of line of movie-goers andhaving arrived at the front of the line and purchased ticketremoving herself from the front of the line the terms for insertion and removal in stack are fairly standardeveryone says push and pop standardization hasn' progressed this far with queues insert is also called put or add or enquewhile remove may be called delete or get or deque the rear of the queuewhere items are insertedis also called the back or tail or end the frontwhere items are removedmay also be called the head we'll use the terms insertremovefrontand rear
22,649
stacks and queues the insert button by repeatedly pressing the ins button in the queue workshop appletyou can insert new item after the first pressyou're prompted to enter key value for new item into the number text fieldthis should be number from to subsequent presses will insert an item with this key at the rear of the queue and increment the rear arrow so it points to the new item the remove button similarlyyou can remove the item at the front of the queue using the rem button the item is removedthe item' value is stored in the number field (corresponding to the remove(method returning value)and the front arrow is incremented in the appletthe cell that held the deleted item is grayed to show it' gone in normal implementationit would remain in memory but would not be accessible because front had moved past it the insert and remove operations are shown in figure rear rear front front new item inserted at rear of queue rear rear rear front front front two items removed from front of queue figure operation of the queue class methods
22,650
unlike the situation in stackthe items in queue don' always extend all the way down to index in the array after some items are removedfront will point at cell with higher indexas shown in figure in figure notice that front lies below rear in the arraythat isfront has lower index as we'll see in momentthis isn' always true the peek button we show one other queue operationpeek peek finds the value of the item at the front of the queue without removing the item (like insert and removepeekwhen applied to queueis also called by variety of other names if you press the peek buttonyou'll see the value at front transferred to the number field the queue is unchanged this peek(method returns the value at the front of the queue some queue implementations have rearpeek(and frontpeek(methodbut usually you want to know what you're about to removenot what you just inserted maxsize- empty cells rear front empty cells figure queue with some items removed the new button if you want to start with an empty queueyou can use the new button to create one empty and full if you try to remove an item when there are no more items in the queueyou'll get the can' removequeue is empty error message if you try to insert an item when all the cells are already occupiedyou'll get the can' insertqueue is full message
22,651
stacks and queues circular queue when you insert new item in the queue in the queue workshop appletthe front arrow moves upwardtoward higher numbers in the array when you remove an itemrear also moves upward try these operations with the workshop applet to convince yourself it' true you may find the arrangement counter-intuitivebecause the people in line at the movies all move forwardtoward the frontwhen person leaves the line we could move all the items in queue whenever we deleted onebut that wouldn' be very efficient insteadwe keep all the items in the same place and move the front and rear of the queue the trouble with this arrangement is that pretty soon the rear of the queue is at the end of the array (the highest indexeven if there are empty cells at the beginning of the arraybecause you've removed them with remyou still can' insert new item because rear can' go any further or can itthis situation is shown in figure maxsize- new itemwhere can it go front rear figure rear arrow at the end of the array wrapping around to avoid the problem of not being able to insert more items into the queue even when it' not fullthe front and rear arrows wrap around to the beginning of the array the result is circular queue (sometimes called ring bufferyou can see how wraparound works with the workshop applet insert enough items to bring the rear arrow to the top of the array (index remove some items from
22,652
the front of the array now insert another item you'll see the rear arrow wrap around from index to index the new item will be inserted there this situation is shown in figure insert few more items the rear arrow moves upward as you' expect notice that after rear has wrapped aroundit' now below frontthe reverse of the original arrangement you can call this broken sequencethe items in the queue are in two different sequences in the array maxsize- front rear figure the rear arrow wraps around delete enough items so that the front arrow also wraps around now you're back to the original arrangementwith front below rear the items are in single contiguous sequence java code for queue the queue java program features queue class with insert()remove()peek()isfull()isempty()and size(methods the main(program creates queue of five cellsinserts four itemsremoves three itemsand inserts four more the sixth insertion invokes the wraparound feature all the items are then removed and displayed the output looks like this
22,653
stacks and queues listing shows the queue java program listing the queue java program /queue java /demonstrates queue /to run this programc>java queueapp ///////////////////////////////////////////////////////////////class queue private int maxsizeprivate long[quearrayprivate int frontprivate int rearprivate int nitems//public queue(int /constructor maxsize squearray new long[maxsize]front rear - nitems //public void insert(long /put item at rear of queue if(rear =maxsize- /deal with wraparound rear - quearray[++rearj/increment rear and insert nitems++/one more item //public long remove(/take item from front of queue long temp quearray[front++]/get value and incr front if(front =maxsize/deal with wraparound front nitems--/one less item return temp//public long peekfront(/peek at front of queue
22,654
listing continued return quearray[front]//public boolean isempty(/true if queue is empty return (nitems== )//public boolean isfull(/true if queue is full return (nitems==maxsize)//public int size(/number of items in queue return nitems///end class queue ///////////////////////////////////////////////////////////////class queueapp public static void main(string[argsqueue thequeue new queue( )/queue holds items thequeue insert( )thequeue insert( )thequeue insert( )thequeue insert( )/insert items thequeue remove()thequeue remove()thequeue remove()/remove items /( thequeue insert( )thequeue insert( )thequeue insert( )thequeue insert( )/insert more items /(wraps aroundwhile!thequeue isempty(/remove and display /all items
22,655
listing stacks and queues continued long thequeue remove()system out print( )system out print(")system out println("")/end main(/end class queueapp /( we've chosen an approach in which queue class fields include not only front and rearbut also the number of items currently in the queuenitems some queue implementations don' use this fieldwe'll show this alternative later the insert(method the insert(method assumes that the queue is not full we don' show it in main()but normally you should call insert(only after calling isfull(and getting return value of false (it' usually preferable to place the check for fullness in the insert(routine and cause an exception to be thrown if an attempt was made to insert into full queue normallyinsertion involves incrementing rear and inserting at the cell rear now points to howeverif rear is at the top of the arrayat maxsize- then it must wrap around to the bottom of the array before the insertion takes place this is done by setting rear to - so when the increment occursrear will become the bottom of the array finallynitems is incremented the remove(method the remove(method assumes that the queue is not empty you should call isempty(to ensure this is true before calling remove()or build this error-checking into remove(removal always starts by obtaining the value at front and then incrementing front howeverif this puts front beyond the end of the arrayit must then be wrapped around to the return value is stored temporarily while this possibility is checked finallynitems is decremented the peek(method the peek(method is straightforwardit returns the value at front some implementations allow peeking at the rear of the array as wellsuch routines are called something like peekfront(and peekrear(or just front(and rear(the isempty()isfull()and size(methods the isempty()isfull()and size(methods all rely on the nitems fieldrespectively checking if it' if it' maxsizeor returning its value
22,656
implementation without an item count the inclusion of the field nitems in the queue class imposes slight overhead on the insert(and remove(methods in that they must respectively increment and decrement this variable this may not seem like an excessive penaltybut if you're dealing with huge numbers of insertions and deletionsit might influence performance accordinglysome implementations of queues do without an item count and rely on the front and rear fields to figure out whether the queue is empty or full and how many items are in it when this is donethe isempty()isfull()and size(routines become surprisingly complicated because the sequence of items may be either broken or contiguousas we've seen alsoa strange problem arises the front and rear pointers assume certain positions when the queue is fullbut they can assume these exact same positions when the queue is empty the queue can then appear to be full and empty at the same time this problem can be solved by making the array one cell larger than the maximum number of items that will be placed in it listing shows queue class that implements this no-count approach this class uses the no-count implementation listing the queue class without nitems class queue private int maxsizeprivate long[quearrayprivate int frontprivate int rear//public queue(int /constructor maxsize + /array is cell larger quearray new long[maxsize]/than requested front rear - //public void insert(long /put item at rear of queue if(rear =maxsize- rear - quearray[++rearj//public long remove(/take item from front of queue
22,657
listing stacks and queues continued long temp quearray[front++]if(front =maxsizefront return temp//public long peek(/peek at front of queue return quearray[front]//public boolean isempty(/true if queue is empty return rear+ ==front |(front+maxsize- ==rear)//public boolean isfull(/true if queue is full return rear+ ==front |(front+maxsize- ==rear)//public int size(/(assumes queue not emptyif(rear >front/contiguous sequence return rear-front+ else /broken sequence return (maxsize-front(rear+ )///end class queue notice the complexity of the isfull()isempty()and size(methods this no-count approach is seldom needed in practiceso we'll refrain from discussing it in detail efficiency of queues as with stackitems can be inserted and removed from queue in ( time
22,658
deques deque is double-ended queue you can insert items at either end and delete them from either end the methods might be called insertleft(and insertright()and removeleft(and removeright(if you restrict yourself to insertleft(and removeleft((or their equivalents on the right)the deque acts like stack if you restrict yourself to insertleft(and removeright((or the opposite pair)it acts like queue deque provides more versatile data structure than either stack or queue and is sometimes used in container class libraries to serve both purposes howeverit' not used as often as stacks and queuesso we won' explore it further here priority queues priority queue is more specialized data structure than stack or queue howeverit' useful tool in surprising number of situations like an ordinary queuea priority queue has front and rearand items are removed from the front howeverin priority queueitems are ordered by key value so that the item with the lowest key (or in some implementations the highest keyis always at the front items are inserted in the proper position to maintain the order here' how the mail sorting analogy applies to priority queue every time the postman hands you letteryou insert it into your pile of pending letters according to its priority if it must be answered immediately (the phone company is about to disconnect your modem line)it goes on topwhereas if it can wait for leisurely answer ( letter from your aunt mabel)it goes on the bottom letters with intermediate priorities are placed in the middlethe higher the prioritythe higher their position in the pile the top of the pile of letters corresponds to the front of the priority queue when you have time to answer your mailyou start by taking the letter off the top (the front of the queue)thus ensuring that the most important letters are answered first this situation is shown in figure like stacks and queuespriority queues are often used as programmer' tools we'll see one used in finding something called minimum spanning tree for graphin "weighted graphs alsolike ordinary queuespriority queues are used in various ways in certain computer systems in preemptive multitasking operating systemfor exampleprograms may be placed in priority queue so the highest-priority program is the next one to receive time-slice that allows it to execute
22,659
stacks and queues letter on top is always processed first more urgent letters are inserted higher less urgent letters are inserted lower figure letters in priority queue in many situations you want access to the item with the lowest key value (which might represent the cheapest or shortest way to do somethingthusthe item with the smallest key has the highest priority somewhat arbitrarilywe'll assume that' the case in this discussionalthough there are other situations in which the highest key has the highest priority besides providing quick access to the item with the smallest keyyou also want priority queue to provide fairly quick insertion for this reasonpriority queues areas we noted earlieroften implemented with data structure called heap we'll look at heaps in "heaps in this we'll show priority queue implemented by simple array this implementation suffers from slow insertionbut it' simpler and is appropriate when the number of items isn' high or insertion speed isn' critical the priorityq workshop applet the priorityq workshop applet implements priority queue with an arrayin which the items are kept in sorted order it' an ascending-priority queuein which the item with smallest key has the highest priority and is accessed with remove((if the highest-key item were accessedit would be descending-priority queue
22,660
the minimum-key item is always at the top (highest indexin the arrayand the largest item is always at index figure shows the arrangement when the applet is started initiallythere are five items in the queue figure the priorityq workshop applet the insert button try inserting an item you'll be prompted to type the new item' key value into the number field choose number that will be inserted somewhere in the middle of the values already in the queue for examplein figure you might choose thenas you repeatedly press insyou'll see that the items with smaller keys are shifted up to make room black arrow shows which item is being shifted when the appropriate position is foundthe new item is inserted into the newly created space notice that there' no wraparound in this implementation of the priority queue insertion is slow of necessity because the proper in-order position must be foundbut deletion is fast wraparound implementation wouldn' improve the situation note too that the rear arrow never movesit always points to index at the bottom of the array the delete button the item to be removed is always at the top of the arrayso removal is quick and easythe item is removed and the front arrow moves down to point to the new top of the array no shifting or comparisons are necessary in the priorityq workshop appletwe show front and rear arrows to provide comparison with an ordinary queuebut they're not really necessary the algorithms
22,661
stacks and queues know that the front of the queue is always at the top of the array at nitems- and they insert items in ordernot at the rear figure shows the operation of the priorityq class methods front front rear rear new item inserted in priority queue front rear front rear front rear two items removed from front of priority queue figure operation of the priorityq class methods the peek and new buttons you can peek at the minimum item (find its value without removing itwith the peek buttonand you can create newemptypriority queue with the new button other implementation possibilities the implementation shown in the priorityq workshop applet isn' very efficient for insertionwhich involves moving an average of half the items another approachwhich also uses an arraymakes no attempt to keep the items in sorted order new items are simply inserted at the top of the array this makes
22,662
insertion very quickbut unfortunately it makes deletion slow because the smallest item must be searched for this approach requires examining all the items and shifting half of themon the averagedown to fill in the hole in most situations the quick-deletion approach shown in the workshop applet is preferred for small numbers of itemsor situations in which speed isn' criticalimplementing priority queue with an array is satisfactory for larger numbers of itemsor when speed is criticalthe heap is better choice java code for priority queue the java code for simple array-based priority queue is shown in listing listing the priorityq java program /priorityq java /demonstrates priority queue /to run this programc>java priorityqapp ///////////////////////////////////////////////////////////////class priorityq /array in sorted orderfrom max at to min at size- private int maxsizeprivate long[quearrayprivate int nitems//public priorityq(int /constructor maxsize squearray new long[maxsize]nitems //public void insert(long item/insert item int jif(nitems== /if no itemsquearray[nitems++item/insert at else /if itemsfor( =nitems- >= --/start at endifitem quearray[ /if new item largerquearray[ + quearray[ ]/shift upward
22,663
listing stacks and queues continued else /if smallerbreak/done shifting /end for quearray[ + item/insert it nitems++/end else (nitems /end insert(//public long remove(/remove minimum item return quearray[--nitems]//public long peekmin(/peek at minimum item return quearray[nitems- ]//public boolean isempty(/true if queue is empty return (nitems== )//public boolean isfull(/true if queue is full return (nitems =maxsize)///end class priorityq ///////////////////////////////////////////////////////////////class priorityqapp public static void main(string[argsthrows ioexception priorityq thepq new priorityq( )thepq insert( )thepq insert( )thepq insert( )thepq insert( )thepq insert( )while!thepq isempty(long item thepq remove()system out print(item ")/ /end while system out println("")/end main(///end class priorityqapp
22,664
in main(we insert five items in random orderand then remove and display them the smallest item is always removed firstso the output is the insert(method checks whether there are any itemsif notit inserts one at index otherwiseit starts at the top of the array and shifts existing items upward until it finds the place where the new item should go then it inserts the item and increments nitems note that if there' any chance the priority queue is fullyou should check for this possibility with isfull(before using insert(the front and rear fields aren' necessary as they were in the queue class becauseas we notedfront is always at nitems- and rear is always at the remove(method is simplicity itselfit decrements nitems and returns the item from the top of the array the peekmin(method is similarexcept it doesn' decrement nitems the isempty(and isfull(methods check if nitems is or maxsizerespectively efficiency of priority queues in the priority-queue implementation we show hereinsertion runs in (ntimewhile deletion takes ( time we'll see how to improve insertion time with heaps in parsing arithmetic expressions so far in this we've introduced three different data storage structures let' shift gears now and focus on an important application for one of these structures this application is parsing (that isanalyzingarithmetic expressions such as + or *( + or (( + )* )+ *( - the storage structure it uses is the stack in the brackets java program (listing )we saw how stack could be used to check whether delimiters were formatted correctly stacks are used in similaralthough more complicatedway for parsing arithmetic expressions in some sense this section should be considered optional it' not prerequisite to the rest of the bookand writing code to parse arithmetic expressions is probably not something you need to do every dayunless you are compiler writer or are designing pocket calculators alsothe coding details are more complex than any we've seen so far howeverseeing this important use of stacks is educationaland the issues raised are interesting in their own right as it turns outit' fairly difficultat least for computer algorithmto evaluate an arithmetic expression directly it' easier for the algorithm to use two-step process
22,665
stacks and queues transform the arithmetic expression into different formatcalled postfix notation evaluate the postfix expression step is bit involvedbut step is easy in any casethis two-step approach results in simpler algorithm than trying to parse the arithmetic expression directly of coursefor human it' easier to parse the ordinary arithmetic expression we'll return to the difference between the human and computer approaches in moment before we delve into the details of steps and we'll introduce postfix notation postfix notation everyday arithmetic expressions are written with an operator (+-*or /placed between two operands (numbersor symbols that stand for numbersthis is called infix notation because the operator is written inside the operands thuswe say + and / orusing letters to stand for numbersa+ and / in postfix notation (which is also called reverse polish notationor rpnbecause it was invented by polish mathematician)the operator follows the two operands thusa+ becomes ab+and / becomes abmore complex infix expressions can likewise be translated into postfix notationas shown in table we'll explain how the postfix expressions are generated in moment table infix and postfix expressions infix postfix + - * / + * * + *( +ca* + * ( + )*( - (( + )* )- + *( - /( + )ab+cab*cabc*ab*cabc+ab*cd*ab+cd-ab+ *dabcdef+/-*some computer languages also have an operator for raising quantity to power (typicallythe character)but we'll ignore that possibility in this discussion besides infix and postfixthere' also prefix notationin which the operator is written before the operands+ab instead of abthis notation is functionally similar to postfix but seldom used
22,666
translating infix to postfix the next several pages are devoted to explaining how to translate an expression from infix notation into postfix this algorithm is fairly involvedso don' worry if every detail isn' clear at first if you get bogged downyou may want to skip ahead to the section "evaluating postfix expressions to understand how to create postfix expressionyou might find it helpful to see how postfix expression is evaluatedfor examplehow the value is extracted from the expression +*which is the postfix equivalent of *( + (notice that in this discussionfor ease of writingwe restrict ourselves to expressions with single-digit numbersalthough these expressions may evaluate to multidigit numbers how humans evaluate infix how do you translate infix to postfixlet' examine slightly easier question firsthow does human evaluate normal infix expressionalthoughas we stated earliersuch evaluation is difficult for computerwe humans do it fairly easily because of countless hours in mr klemmer' math class it' not hard for us to find the answer to + + or *( + by analyzing how we evaluate this expressionwe can achieve some insight into the translation of such expressions into postfix roughly speakingwhen you "solvean arithmetic expressionyou follow rules something like this you read from left to right (at leastwe'll assume this is true sometimes people skip aheadbut for purposes of this discussionyou should assume you must read methodicallystarting at the left when you've read enough to evaluate two operands and an operatoryou do the calculation and substitute the answer for these two operands and operator (you may also need to solve other pending operations on the leftas we'll see later you continue this process--going from left to right and evaluating when possible--until the end of the expression tables and show three examples of how simple infix expressions are evaluated laterin tables and we'll see how closely these evaluations mirror the process of translating infix to postfix to evaluate + - you would carry out the steps shown in table
22,667
stacks and queues table evaluating + - item read expression parsed so far comments + - when you see the -you can evaluate + end when you reach the end of the expressionyou can evaluate - you can' evaluate the + until you see what operator follows the if it' an or /you need to wait before applying the sign until you've evaluated the or howeverin this example the operator following the is -which has the same precedence as +so when you see the -you know you can evaluate + which is the then replaces the + you can evaluate the - when you arrive at the end of the expression figure shows this process in more detail notice how you go from left to right reading items from the inputand thenwhen you have enough informationyou go from right to leftrecalling previously examined input and evaluating each operandoperator-operand combination because of precedence relationshipsevaluating + * is bit more complicatedas shown in table table evaluating + * item read expression parsed so far + + + * + end comments you can' evaluate + because is higher precedence than when you see the you can evaluate * when you see the end of the expressionyou can evaluate + here you can' add the until you know the result of * why notbecause multiplication has higher precedence than addition in factboth and have higher precedence than and -so all multiplications and divisions must be carried out before any additions or subtractions (unless parentheses dictate otherwisesee the next example
22,668
read the read the read the read the end evaluate + recall the read the read the end recall the recall the recall the recall the end evaluate recall - the recall the figure details of evaluating + - often you can evaluate as you go from left to rightas in the preceding example howeveryou need to be surewhen you come to an operand-operator-operand combination such as +bthat the operator on the right side of the isn' one with higher precedence than the if it does have higher precedenceas in this exampleyou can' do the addition yet howeverafter you've read the the multiplication can be carried out because it has the highest priorityit doesn' matter whether or follows the howeveryou still can' do the addition until you've found out what' beyond the when you find there' nothing beyond the but the end of the expressionyou can go ahead and do the addition figure shows this process parentheses are used to override the normal precedence of operators table shows how you would evaluate *( + without the parenthesesyou would do the multiplication firstwith themyou do the addition first
22,669
stacks and queues read the read the read the read the read the end evaluate * recall the recall the recall the recall the recall the read the end end evaluate recall + the recall the figure details of evaluating + * table evaluating *( + item read expression parsed so far * *( *( *( + *( + * end comments you can' evaluate * because of the parenthesis you can' evaluate + yet when you see the )you can evaluate + after you've evaluated + you can evaluate * nothing left to evaluate here we can' evaluate anything until we've reached the closing parenthesis multiplication has higher or equal precedence compared to the other operatorsso ordinarily we could carry out * as soon as we see the howeverparentheses have an even higher precedence than and accordinglywe must evaluate anything in parentheses before using the result as an operand in any other calculation the
22,670
closing parenthesis tells us we can go ahead and do the addition we find that + is and when we know thiswe can evaluate * to obtain reaching the end of the expression is an anticlimax because there' nothing left to evaluate this process is shown in figure read the read the read the read the read the read the recall the discard the read the end evaluate discard + the recall the recall the recall the recall the end evaluate recall * the recall the end end recall the figure details of evaluating *( + as we've seenin evaluating an infix arithmetic expressionyou go both forward and backward through the expression you go forward (left to rightreading operands and operators when you have enough information to apply an operatoryou go backwardrecalling two operands and an operator and carrying out the arithmetic sometimes you must defer applying operators if they're followed by higher precedence operators or by parentheses when this happensyou must apply the laterhigher-precedenceoperator firstthen go backward (to the leftand apply earlier operators we could write an algorithm to carry out this kind of evaluation directly howeveras we notedit' actually easier to translate into postfix notation first
22,671
stacks and queues how humans translate infix to postfix to translate infix to postfix notationyou follow similar set of rules to those for evaluating infix howeverthere are few small changes you don' do any arithmetic the idea is not to evaluate the infix expressionbut to rearrange the operators and operands into different formatpostfix notation the resulting postfix expression will be evaluated later as beforeyou read the infix from left to rightlooking at each character in turn as you go alongyou copy these operands and operators to the postfix output string the trick is knowing when to copy what if the character in the infix string is an operandyou copy it immediately to the postfix string that isif you see an in the infixyou write an to the postfix there' never any delayyou copy the operands as you get to themno matter how long you must wait to copy their associated operators knowing when to copy an operator is more complicatedbut it' the same as the rule for evaluating infix expressions whenever you could have used the operator to evaluate part of the infix expression (if you were evaluating instead of translating to postfix)you instead copy it to the postfix string table shows how + - is translated into postfix notation table translating + - into postfix character read from infix expression infix expression parsed so far postfix expression written so far aa+ +ba ab abc end + - + - ab+ ab+ccomments when you see the -you can copy the to the postfix string when you reach the end of the expressionyou can copy the notice the similarity of this table to table which showed the evaluation of the infix expression + - at each point where you would have done an evaluation in the earlier tableyou instead simply write an operator to the postfix output table shows the translation of + * to postfix this evaluation is similar to table which covered the evaluation of + *
22,672
table translating + * to postfix character read from infix expression infix expression parsed so far postfix expression written so far aa+ +ba ab ab + * + * + * abc abcabc*end comments you can' copy the because is higher precedence than when you see the cyou can copy the when you see the end of the expressionyou can copy the as the final exampletable shows how *( +cis translated to postfix this process is similar to evaluating *( + in table you can' write any postfix operators until you see the closing parenthesis in the input table translating *( +cinto postfix character read from infix expression infix expression parsed so far postfix expression written so far aa* *( ab *(ba*( + *( +ca*( +cab abc abcabc+end *( +cabc+comments you can' copy because of the parenthesis you can' copy the yet when you see the )you can copy the after you've copied the +you can copy the nothing left to copy as in the numerical evaluation processyou go both forward and backward through the infix expression to complete the translation to postfix you can' write an operator to the output (postfixstring if it' followed by higher-precedence operator or left parenthesis if it isthe higher-precedence operator or the operator in parentheses must be written to the postfix before the lower-priority operator
22,673
stacks and queues saving operators on stack you'll notice in both table and table that the order of the operators is reversed going from infix to postfix because the first operator can' be copied to the output until the second one has been copiedthe operators were output to the postfix string in the opposite order they were read from the infix string longer example may make this operation clearer table shows the translation to postfix of the infix expression + *( -dwe include column for stack contentswhich we'll explain in moment table translating + *( -dto postfix character read from infix expression infix expression parsed so far postfix expression written so far aa+ +ba+ * + *( + *(ca+ *( - + *( -da+ *( -da+ *( -da+ *( -da+ *( -da ab ab ab abc abc abcd abcdabcdabcdabcd-abcd-*stack contents ++*+*+*(+*(+*+*+here we see the order of the operands is +*in the original infix expressionbut the reverse order-*+in the final postfix expression this happens because has higher precedence than +and -because it' in parentheseshas higher precedence than this order reversal suggests stack might be good place to store the operators while we're waiting to use them the last column in table shows the stack contents at various stages in the translation process popping items from the stack allows you toin sensego backward (right to leftthrough the input string you're not really examining the entire input stringonly the operators and parentheses they were pushed on the stack when reading the inputso now you can recall them in reverse order by popping them off the stack the operands (aband so onappear in the same order in infix and postfixso you can write each one to the output as soon as you encounter itthey don' need to be stored on stack
22,674
translation rules let' make the rules for infix-to-postfix translation more explicit you read items from the infix input string and take the actions shown in table these actions are described in pseudocodea blend of java and english in this tablethe symbols refer to the operator precedence relationshipnot numerical values the opthis operator has just been read from the infix inputwhile the optop operator has just been popped off the stack table infix to postfix translation rules item read from input (infixaction operand open parenthesis close parenthesis write it to output (postfixpush it on stack while stack not emptyrepeat the followingpop an itemif item is not (write it to output quit loop if item is if stack emptypush opthis otherwisewhile stack not emptyrepeatpop an itemif item is (push itor if item is an operator (optop)and if optop opthispush optopor if optop >opthisoutput optop quit loop if optop opthis or item is push opthis while stack not emptypop itemoutput it operator (opthisno more items convincing yourself that these rules work may take some effort tables and show how the rules apply to three example infix expressions these tables are similar to tables and except that the relevant rules for each step have been added try creating similar tables by starting with other simple infix expressions and using the rules to translate some of them to postfix
22,675
stacks and queues table translation rules applied to + - character read from infix infix parsed so far postfix written so far aa+ +ba+ba ab ab abstack contents rule write operand to output if stack emptypush opthis write operand to output stack not emptyso pop item opthis is -optop is +optop>=opthisso output optop end +ba+ - + - abab+ ab+ctable translation rules applied to + * character read from infix infix parsed so far postfix written so far aa+ +ba ab ab +bab end +ba+ * + * + * ab abc abcabc*++table translation rules applied to *( +ccharacter read from infix infix parsed so far postfix written so far aa* stack contents stack contents *then push opthis write operand to output pop leftover itemoutput it rule write operand to postfix if stack emptypush opthis write operand to output stack not emptyso pop optop opthis is *optop is +optop<opthisso push optop then push opthis write operand to output pop leftover itemoutput it pop leftover itemoutput it rule write operand to postfix if stack emptypush opthis push on stack
22,676
table continued character read from infix infix parsed so far postfix written so far stack contents rule *( *(ba*(ba*(ba*( + *( +ca*( +ca*( +cab ab ab ab abc abcabcabc+***(*(*write operand to postfix stack not emptyso pop item it' (so push it then push opthis write operand to postfix pop itemwrite to output quit popping if pop leftover itemoutput it end java code to convert infix to postfix listing shows the infix java programwhich uses the rules from table to translate an infix expression to postfix expression listing the infix java program /infix java /converts infix arithmetic expressions to postfix /to run this programc>java infixapp import java io */for / ///////////////////////////////////////////////////////////////class stackx private int maxsizeprivate char[stackarrayprivate int top//public stackx(int /constructor maxsize sstackarray new char[maxsize]top - //public void push(char /put item on top of stack stackarray[++topj//public char pop(/take item from top of stack
22,677
listing stacks and queues continued return stackarray[top--]//public char peek(/peek at top of stack return stackarray[top]//public boolean isempty(/true if stack is empty return (top =- )//public int size(/return size return top+ //public char peekn(int /return item at index return stackarray[ ]//public void displaystack(string ssystem out print( )system out print("stack (bottom-->top)")for(int = <size() ++system out printpeekn( )system out print(')system out println("")///end class stackx ///////////////////////////////////////////////////////////////class intopost /infix to postfix conversion private stackx thestackprivate string inputprivate string output ""//public intopost(string in/constructor input inint stacksize input length()thestack new stackx(stacksize)/
22,678
listing continued public string dotrans(/do translation to postfix for(int = <input length() ++char ch input charat( )thestack displaystack("for "+ch+")/*diagnosticswitch(chcase '+'/it' or case '-'gotoper(ch )/go pop operators break/(precedence case '*'/it' or case '/'gotoper(ch )/go pop operators break/(precedence case '('/it' left paren thestack push(ch)/push it breakcase ')'/it' right paren gotparen(ch)/go pop operators breakdefault/must be an operand output output ch/write it to output break/end switch /end for while!thestack isempty(/pop remaining opers thestack displaystack("while ")/*diagnosticoutput output thestack pop()/write to output thestack displaystack("end ")/*diagnosticreturn output/return postfix /end dotrans(//public void gotoper(char opthisint prec /got operator from input while!thestack isempty(char optop thestack pop()
22,679
listing stacks and queues continued ifoptop ='(thestack push(optop)breakelse int prec /if it' '(/restore '(/it' an operator /precedence of new op if(optop=='+|optop=='-'/find new op prec prec else prec if(prec prec /if prec of new op less /than prec of old thestack push(optop)/save newly-popped op breakelse /prec of new not less output output optop/than prec of old /end else (it' an operator/end while thestack push(opthis)/push new operator /end gotop(//public void gotparen(char ch/got right paren from input while!thestack isempty(char chx thestack pop()ifchx ='(/if popped '(break/we're done else /if popped operator output output chx/output it /end while /end popops(///end class intopost ///////////////////////////////////////////////////////////////class infixapp
22,680
listing continued public static void main(string[argsthrows ioexception string inputoutputwhile(truesystem out print("enter infix")system out flush()input getstring()/read string from kbd ifinput equals(""/quit if [enterbreak/make translator intopost thetrans new intopost(input)output thetrans dotrans()/do the translation system out println("postfix is output '\ ')/end while /end main(//public static string getstring(throws ioexception inputstreamreader isr new inputstreamreader(system in)bufferedreader br new bufferedreader(isr)string br readline()return ///end class infixapp ///////////////////////////////////////////////////////////////the main(routine in the infixapp class asks the user to enter an infix expression the input is read with the readstring(utility method the program creates an intopost objectinitialized with the input string then it calls the dotrans(method for this object to perform the translation this method returns the postfix output stringwhich is displayed the dotrans(method uses switch statement to handle the various translation rules shown in table it calls the gotoper(method when it reads an operator and the gotparen(method when it reads closing parenthesisthese methods implement the second two rules in the tablewhich are more complex than other rules we've included displaystack(method to display the entire contents of the stack in the stackx class in theorythis isn' playing by the rulesyou're supposed to access the item only at the top howeveras diagnostic aidthis routine is useful if
22,681
stacks and queues you want to see the contents of the stack at each stage of the translation here' some sample interaction with infix javaenter infixa*( + )- /( +ffor stack (bottom-->top)for stack (bottom-->top)for stack (bottom-->top)for stack (bottom-->top)for stack (bottom-->top)for stack (bottom-->top)for stack (bottom-->top)for stack (bottom-->top)for stack (bottom-->top)for stack (bottom-->top)for stack (bottom-->top)for stack (bottom-->top)for stack (bottom-->top)for stack (bottom-->top)for stack (bottom-->top)while stack (bottom-->top)while stack (bottom-->top)end stack (bottom-->top)postfix is abc+*def+/the output shows where the displaystack(method was called (from the for loopthe while loopor at the end of the programandwithin the for loopwhat character has just been read from the input string you can use single-digit numbers like and instead of symbols like and they're all just characters to the program for exampleenter infix + * for stack (bottom-->top)for stack (bottom-->top)for stack (bottom-->top)for stack (bottom-->top)for stack (bottom-->top)while stack (bottom-->top)while stack (bottom-->top)end stack (bottom-->top)postfix is *of coursein the postfix outputthe means the separate numbers and
22,682
the infix java program doesn' check the input for errors if you type an incorrect infix expressionthe program will provide erroneous output or crash and burn experiment with this program start with some simple infix expressionsand see if you can predict what the postfix will be then run the program to verify your answer pretty soonyou'll be postfix gurumuch sought after at cocktail parties evaluating postfix expressions as you can seeconverting infix expressions to postfix expressions is not trivial is all this trouble really necessaryyesthe payoff comes when you evaluate postfix expression before we show how simple the algorithm islet' examine how human might carry out such an evaluation how humans evaluate postfix figure shows how human can evaluate postfix expression using visual inspection and pencil figure visual approach to postfix evaluation of +* +/start with the first operator on the leftand draw circle around it and the two operands to its immediate left then apply the operator to these two operands-performing the actual arithmetic--and write down the result inside the circle in the figureevaluating + gives now go to the next operator to the rightand draw circle around itthe circle you already drewand the operand to the left of that apply the operator to the previous circle and the new operandand write the result in the new circle here * gives continue this process until all the operators have been applied + is and / is the answer is the result in the largest circle - is rules for postfix evaluation how do we write program to reproduce this evaluation processas you can seeeach time you come to an operatoryou apply it to the last two operands you've seen this suggests that it might be appropriate to store the operands on stack
22,683
stacks and queues (this is the opposite of the infix-to-postfix translation algorithmwhere operators were stored on the stack you can use the rules shown in table to evaluate postfix expressions table evaluating postfix expression item read from postfix expression action operand operator push it onto the stack pop the top two operands from the stack and apply the operator to them push the result when you're donepop the stack to obtain the answer that' all there is to it this process is the computer equivalent of the human circle-drawing approach of figure java code to evaluate postfix expressions in the infix-to-postfix translationwe used symbols (aband so onto stand for numbers this approach worked because we weren' performing arithmetic operations on the operands but merely rewriting them in different format now we want to evaluate postfix expressionwhich means carrying out the arithmetic and obtaining an answer thusthe input must consist of actual numbers to simplify the codingwe've restricted the input to single-digit numbers our program evaluates postfix expression and outputs the result remember numbers are restricted to one digit here' some simple interactionenter postfix stack (bottom-->top) stack (bottom-->top) stack (bottom-->top) evaluates to you enter digits and operatorswith no spaces the program finds the numerical equivalent although the input is restricted to single-digit numbersthe results are notit doesn' matter if something evaluates to numbers greater than as in the infix java programwe use the displaystack(method to show the stack contents at each step listing shows the postfix java program listing the postfix java program /postfix java /parses postfix arithmetic expressions /to run this programc>java postfixapp
22,684
listing continued import java io */for / ///////////////////////////////////////////////////////////////class stackx private int maxsizeprivate int[stackarrayprivate int top//public stackx(int size/constructor maxsize sizestackarray new int[maxsize]top - //public void push(int /put item on top of stack stackarray[++topj//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 =- )//public boolean isfull(/true if stack is full return (top =maxsize- )//public int size(/return size return top+ //public int peekn(int /peek at index return stackarray[ ]//public void displaystack(string ssystem out print( )system out print("stack (bottom-->top)")for(int = <size() ++
22,685
listing stacks and queues continued system out printpeekn( )system out print(')system out println("")///end class stackx ///////////////////////////////////////////////////////////////class parsepost private stackx thestackprivate string input//public parsepost(string sinput //public int doparse(thestack new stackx( )/make new stack char chint jint num num interansfor( = <input length() ++/for each charch input charat( )/read from input thestack displaystack(""+ch+")/*diagnosticif(ch >' &ch <' '/if it' number thestack push(int)(ch-' ')/push it else /it' an operator num thestack pop()/pop operands num thestack pop()switch(ch/do arithmetic case '+'interans num num breakcase '-'interans num num
22,686
listing continued breakcase '*'interans num num breakcase '/'interans num num breakdefaultinterans /end switch thestack push(interans)/push result /end else /end for interans thestack pop()/get answer return interans/end doparse(/end class parsepost ///////////////////////////////////////////////////////////////class postfixapp public static void main(string[argsthrows ioexception string inputint outputwhile(truesystem out print("enter postfix")system out flush()input getstring()/read string from kbd ifinput equals(""/quit if [enterbreak/make parser parsepost aparser new parsepost(input)output aparser doparse()/do the evaluation system out println("evaluates to output)/end while /end main(//public static string getstring(throws ioexception
22,687
listing stacks and queues continued inputstreamreader isr new inputstreamreader(system in)bufferedreader br new bufferedreader(isr)string br readline()return ///end class postfixapp ///////////////////////////////////////////////////////////////the main(method in the postfixapp class gets the postfix string from the user and then creates parsepost objectinitialized with this string it then calls the doparse(method of parsepost to carry out the evaluation the doparse(method reads through the input string character by character if the character is digitit' pushed onto the stack if it' an operatorit' applied immediately to the two operators on the top of the stack (these operators are guaranteed to be on the stack already because the input string is in postfix notation the result of the arithmetic operation is pushed onto the stack after the last character (which must be an operatoris read and appliedthe stack contains only one itemwhich is the answer to the entire expression here' some interaction with more complex inputthe postfix expression +* +/-which we showed human evaluating in figure this expression corresponds to the infix *( + )- /( + (we saw an equivalent translation using letters instead of numbers in the previous sectiona*( + )- /( +fin infix is abc+*def+/in postfix here' how the postfix is evaluated by the postfix java programenter postfix +* +/ stack (bottom-->top) stack (bottom-->top) stack (bottom-->top) stack (bottom-->top) stack (bottom-->top) stack (bottom-->top) stack (bottom-->top) stack (bottom-->top) stack (bottom-->top) stack (bottom-->top) stack (bottom-->top) evaluates to
22,688
as with the infix java program (listing )postfix java doesn' check for input errors if you type in postfix expression that doesn' make senseresults are unpredictable experiment with the program trying different postfix expressions and seeing how they're evaluated will give you an understanding of the process faster than reading about it summary stacksqueuesand priority queues are data structures usually used to simplify certain programming operations in these data structuresonly one data item can be accessed stack allows access to the last item inserted the important stack operations are pushing (insertingan item onto the top of the stack and popping (removingthe item that' on the top queue allows access to the first item that was inserted the important queue operations are inserting an item at the rear of the queue and removing the item from the front of the queue queue can be implemented as circular queuewhich is based on an array in which the indices wrap around from the end of the array to the beginning priority queue allows access to the smallest (or sometimes the largestitem the important priority queue operations are inserting an item in sorted order and removing the item with the smallest key these data structures can be implemented with arrays or with other mechanisms such as linked lists ordinary arithmetic expressions are written in infix notationso-called because the operator is written between the two operands in postfix notationthe operator follows the two operands arithmetic expressions are typically evaluated by translating them to postfix notation and then evaluating the postfix expression stack is useful tool both for translating an infix to postfix expression and for evaluating postfix expression
22,689
stacks and queues questions these questions are intended as self-test for readers answers may be found in appendix suppose you push and onto the stack then you pop three items which one is left on the stack which of the following is truea the pop operation on stack is considerably simpler than the remove operation on queue the contents of queue can wrap aroundwhile those of stack cannot the top of stack corresponds to the front of queue in both the stack and the queueitems removed in sequence are taken from increasingly high index cells in the array what do lifo and fifo mean true or falsea stack or queue often serves as the underlying mechanism on which an adt array is based assume an array is numbered with index on the left queue representing line of movie-goerswith the first to arrive numbered has the ticket window on the right then there is no numerical correspondence between the index numbers and the movie-goer numbers the array index numbers and the movie-goer numbers increase in opposite left-right directions the array index numbers correspond numerically to the locations in the line of movie-goers the movie-goers and the items in the array move in the same direction as other items are inserted and removeddoes particular item in queue move along the array from lower to higher indicesor higher to lower suppose you insert and into queue then you remove three items which one is left true or falsepushing and popping items on stack and inserting and removing items in queue all take (ntime
22,690
queue might be used to hold the items to be sorted in an insertion sort reports of variety of imminent attacks on the star ship enterprise keystrokes made by computer user writing letter symbols in an algebraic expression being evaluated inserting an item into typical priority queue takes what big time the term priority in priority queue means that the highest priority items are inserted first the programmer must prioritize access to the underlying array the underlying array is sorted by the priority of the items the lowest priority items are deleted first true or falseat least one of the methods in the priorityq java program (listing uses linear search one difference between priority queue and an ordered array is that the lowest-priority item cannot be extracted easily from the array as it can from the priority queue the array must be ordered while the priority queue need not be the highest priority item can be extracted easily from the priority queue but not from the array all of the above suppose you based priority queue class on the ordarray class in the orderedarray java program (listing in "arrays this will buy you binary search capability if you wanted the best performance for your priority queuewould you need to modify the ordarray class priority queue might be used to hold passengers to be picked up by taxi from different parts of the city keystrokes made at computer keyboard squares on chessboard in game program planets in solar system simulation
22,691
stacks and queues experiments carrying out these experiments will help to provide insights into the topics covered in the no programming is involved start with the initial configuration of the queue workshop applet alternately remove and insert items (this wayyou can reuse the deleted key value for the new item without typing it notice how the group of four items crawls up to the top of the queue and then reappears at the bottom and keeps climbing using the priorityq workshop appletfigure out the positions of the front and rear arrows when the priority queue is full and when it is empty why can' priority queue wrap around like an ordinary queue think about how you remember the events in your life are there times when they seem to be stored in your brain in stackin queuein priority queueprogramming projects writing programs that solve the programming projects helps to solidify your understanding of the material and demonstrates how the concepts are applied (as noted in the introductionqualified instructors may obtain completed solutions to the programming projects on the publisher' web site write method for the queue class in the queue java program (listing that displays the contents of the queue note that this does not mean simply displaying the contents of the underlying array you should show the queue contents from the first item inserted to the lastwithout indicating to the viewer whether the sequence is broken by wrapping around the end of the array be careful that one item and no items display properlyno matter where front and rear are create deque class based on the discussion of deques (double-ended queuesin this it should include insertleft()insertright()removeleft()removeright()isempty()and isfull(methods it will need to support wraparound at the end of the arrayas queues do write program that implements stack class that is based on the deque class in programming project this stack class should have the same methods and capabilities as the stackx class in the stack java program (listing the priority queue shown in listing features fast removal of the high-priority item but slow insertion of new items write program with revised priorityq class that has fast ( insertion time but slower removal of the highpriority item include method that displays the contents of the priority queueas suggested in programming project
22,692
queues are often used to simulate the flow of peoplecarsairplanestransactionsand so on write program that models checkout lines at supermarketusing the queue class from the queue java program (listing several lines of customers should be displayedyou can use the display(method of programming project you can add new customer by pressing key you'll need to determine how the customer will decide which line to join the checkers will take random amounts of time to process each customer (presumably depending on how many groceries the customer hasonce checked outthe customer is removed from the line for simplicityyou can simulate the passing of time by pressing key perhaps every keypress indicates the passage of one minute (javaof coursehas more sophisticated ways to handle time
22,693
linked lists in this links simple linked list finding and deleting in "arrays,we saw that arrays had certain specified links disadvantages as data storage structures in an unordered arraysearching is slowwhereas in an ordered arrayinsertion is slow in both kinds of arraysdeletion is slow alsothe size of an array can' be changed after it' created double-ended lists in this we'll look at data storage structure that solves some of these problemsthe linked list linked lists are probably the second most commonly used generalpurpose storage structures after arrays sorted lists the linked list is versatile mechanism suitable for use in many kinds of general-purpose databases it can also replace an array as the basis for other storage structures such as stacks and queues in factyou can use linked list in many cases in which you use an arrayunless you need frequent random access to individual items using an index linked lists aren' the solution to all data storage problemsbut they are surprisingly versatile and conceptually simpler than some other popular structures such as trees we'll investigate their strengths and weaknesses as we go along in this we'll look at simple linked listsdoubleended listssorted listsdoubly linked listsand lists with iterators (an approach to random access to list elementswe'll also examine the idea of abstract data types (adts)and see how stacks and queues can be viewed as adts and how they can be implemented as linked lists instead of arrays links in linked listeach data item is embedded in link link is an object of class called something like link because there are many similar links in listit makes sense to use separate class for themdistinct from the linked-list efficiency abstract data types doubly linked lists iterators
22,694
linked lists linked list itself each link object contains reference (usually called nextto the next link in the list field in the list itself contains reference to the first link this relationship is shown in figure linked list link link link link data data data data next next next next first null figure links in list here' part of the definition of class link it contains some data and reference to the next linkclass link public int idatapublic double ddatapublic link next/data /data /reference to next link this kind of class definition is sometimes called self-referential because it contains field--called next in this case--of the same type as itself we show only two data items in the linkan int and double in typical application there would be many more personnel recordfor examplemight have nameaddresssocial security numbertitlesalaryand many other fields often an object of class that contains this data is used instead of the itemsclass link public inventoryitem iipublic link next/object holding data /reference to next link references and basic types you can easily get confused about references in the context of linked listsso let' review how they work
22,695
being able to put field of type link inside the class definition of this same type may seem odd wouldn' the compiler be confusedhow can it figure out how big to make link object if link contains link and the compiler doesn' already know how big link object isthe answer is that in java link object doesn' really contain another link objectalthough it may look like it does the next field of type link is only reference to another linknot an object reference is number that refers to an object it' the object' address in the computer' memorybut you don' need to know its valueyou just treat it as magic number that tells you where the object is in given computer/operating systemall referencesno matter what they refer toare the same size thusit' no problem for the compiler to figure out how big this field should be and thereby construct an entire link object note that in javaprimitive types such as int and double are stored quite differently than objects fields containing primitive types do not contain referencesbut actual numerical values like or variable definition like double salary creates space in memory and puts the number into this space howevera reference to an object like link alink somelinkputs reference to an object of type linkcalled somelinkinto alink the somelink object itself is located elsewhere it isn' movedor even createdby this statementit must have been created before to create an objectyou must always use newlink somelink new link()even the somelink field doesn' hold an objectit' still just reference the object is somewhere else in memoryas shown in figure other languagessuch as ++handle objects quite differently than java in + field like link nextactually contains an object of type link you can' write self-referential class definition in +(although you can put pointer to link in class linka pointer is similar to referencec+programmers should keep in mind how java handles objectsthis usage may be counter-intuitive
22,696
linked lists alink somelink alink and somelink refer to an object of type link object of type link memory figure objects and references in memory relationshipnot position let' examine one of the major ways in which linked lists differ from arrays in an array each item occupies particular position this position can be directly accessed using an index number it' like row of housesyou can find particular house using its address in list the only way to find particular element is to follow along the chain of elements it' more like human relations maybe you ask harry where bob is harry doesn' knowbut he thinks jane might knowso you go and ask jane jane saw bob leave the office with sallyso you call sally' cell phone she dropped bob off at
22,697
peter' officeso but you get the idea you can' access data item directlyyou must use relationships between the items to locate it you start with the first itemgo to the secondthen the thirduntil you find what you're looking for the linklist workshop applet the linklist workshop applet provides three list operations you can insert new data itemsearch for data item with specified keyand delete data item with specified key these operations are the same ones we explored in the array workshop applet in they're suitable for general-purpose database application figure shows how the linklist workshop applet looks when it' started initiallythere are links on the list figure the linklist workshop applet the insert button if you think is an unlucky numberyou can insert new link press the ins buttonand you'll be prompted to enter key value between and subsequent presses will generate link with this data in itas shown in figure in this version of linked listnew links are always inserted at the beginning of the list this is the simplest approachalthough you can also insert links anywhere in the listas we'll see later final press on ins will redraw the list so the newly inserted link lines up with the other links this redrawing doesn' represent anything happening in the program itselfit just makes the display neater
22,698
linked lists figure new link being inserted the find button the find button allows you to find link with specified key value when promptedtype in the value of an existing linkpreferably one somewhere in the middle of the list as you continue to press the buttonyou'll see the red arrow move along the listlooking for the link message informs you when the arrow finds the link if you type non-existent key valuethe arrow will search all the way to the end of the list before reporting that the item can' be found the delete button you can also delete key with specified value type in the value of an existing link and repeatedly press del againthe arrow will move along the listlooking for the link when the arrow finds the linkit simply removes that link and connects the arrow from the previous link straight across to the following link this is how links are removedthe reference to the preceding link is changed to point to the following link final keypress redraws the picturebut again redrawing just provides evenly spaced links for aesthetic reasonsthe length of the arrows doesn' correspond to anything in the program note the linklist workshop applet can create both unsorted and sorted lists unsorted is the default we'll show how to use the applet for sorted lists when we discuss them later in this
22,699
simple linked list our first example programlinklist javademonstrates simple linked list the only operations allowed in this version of list are inserting an item at the beginning of the list deleting the item at the beginning of the list iterating through the list to display its contents these operations are fairly easy to carry outso we'll start with them (as we'll see laterthese operations are also all you need to use linked list as the basis for stack before we get to the complete linklist java programwe'll look at some important parts of the link and linklist classes the link class you've already seen the data part of the link class here' the complete class definitionclass link public int idata/data item public double ddata/data item public link next/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 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(using the shorter name would be in the spirit of polymorphismbut it makes the listing somewhat harder to understand when you see statement like