id
int64
0
25.6k
text
stringlengths
0
4.59k
24,800
too high - too low - correct the correct number is identified in only seven guesses this is the maximum you might get lucky and guess the number before you've worked your way all the way down to range of one this would happen if the number to be guessed was for exampleor binary search in the ordered workshop applet to perform binary search with the ordered workshop appletyou must use the new button to create new array after the first press you'll be asked to specify the size of the array (maximum and which kind of searching scheme you wantlinear or binary choose binary by clicking the binary radio button after the array is createduse the fill button to fill it with data items when promptedtype the amount (not more than the size of the arraya few more presses fills in all the items once the array is filledpick one of the values in the array and see how the find button can be used to locate it after few preliminary pressesyou'll see the red arrow pointing to the algorithm' current guessand you'll see the range shown by vertical blue line adjacent to the appropriate cells figure depicts the situation when the range is the entire array at each press of the find button the range is halved and new guess is chosen in the middle of the range figure shows the next step in the process even with maximum array size of itemsa half-dozen button presses suffices to locate any item try using the binary search with different array sizes can you figure out how many steps are necessary before you run the appletwe'll return to this question in the last section of this notice that the insertion and deletion operations also employ the binary search (when it' selectedthe place where an item should be inserted is found with binary searchas is an item to be deleted in this appletitems with duplicate keys are not permitted figure initial range in binary search
24,801
java code for an ordered array let' examine some java code that implements an ordered array we'll use the ordarray class to encapsulate the array and its algorithms the heart of this class is the find(methodwhich uses binary search to locate specified data item we'll examine this method in detail before showing the complete program binary search with the find(method the find(method searches for specified item by repeatedly dividing in half the range of array elements to be considered here' how this method lookspublic int find(double searchkeyint lowerbound int upperbound nelems- int curinwhile(truecurin (lowerbound upperbound if( [curin]==searchkeyreturn curin/found it else if(lowerbound upperboundreturn nelems/can' find it else /divide range if( [curinsearchkeylowerbound curin /it' in upper half else upperbound curin /it' in lower half /end else divide range /end while /end find(the method begins by setting the lowerbound and upperbound variables to the first and last occupied cells in the array this specifies the range where the item we're looking forsearchkeymay be found thenwithin the while loopthe current indexcurin
24,802
if we're luckycurin may already be pointing to the desired itemso we first check if this is true if it iswe've found the item so we return with its indexcurin each time through the loop we divide the range in half eventually it will get so small it can' be divided any more we check for this in the next statementif lowerbound is greater than upperboundthe range has ceased to exist (when lowerbound equals upperbound the range is one and we need one more pass through the loop we can' continue the search without valid rangebut we haven' found the desired itemso we return nelemsthe total number of items this isn' valid indexbecause the last filled cell in the array is nelems- the class user interprets this value to mean that the item wasn' found if curin is not pointing at the desired itemand the range is still big enoughthen we're ready to divide the range in half we compare the value at the current indexa[curin]which is in the middle of the rangewith the value to be foundsearchkey if searchkey is largerthen we know we should look in the upper half of the range accordinglywe move lowerbound up to curin actually we move it one cell beyond curinbecause we've already checked curin itself at the beginning of the loop if searchkey is smaller than [curin]we know we should look in the lower half of the range so we move upperbound down to one cell below curin figure shows how the range is altered in these two situations figure dividing the range in binary search the ordarray class in generalthe orderedarray java program is similar to higharray java the main difference is that find(uses binary searchas we've seen we could have used binary search to locate the position where new item will be inserted this involves variation on the find(routinebut for simplicity we retain the linear search in insert(the speed penalty may not be important becauseas we've seenan average of half the items must be moved anyway when an insertion is performedso insertion will not be very fast even if we locate the item with binary search howeverfor the last ounce of speedyou could change the initial part of insert(to binary search (as is done in the ordered workshop appletsimilarlythe delete(method could call find(to figure out the location of the item to be deleted
24,803
items currently in the array this is helpful for the class usermain()when it calls find(if find(returns nelemswhich main(can discover with size()then the search was unsuccessful listing shows the complete listing for the orderedarray java program listing the orderedarray java program /orderedarray java /demonstrates ordered array class /to run this programc>java orderedapp import java io */for / ///////////////////////////////////////////////////////////////class ordarray private double[ /ref to array private int nelems/number of data items //public ordarray(int maxa new double[max]nelems /constructor /create array //public int size(return nelems//public int find(double searchkeyint lowerbound int upperbound nelems- int curinwhile(truecurin (lowerbound upperbound if( [curin]==searchkeyreturn curin/found it else if(lowerbound upperboundreturn nelems/can' find it else /divide range if( [curinsearchkeylowerbound curin /it' in upper half else upperbound curin /it' in lower half /end else divide range /end while
24,804
/end find(//public void insert(double valueint jfor( = <nelemsj++if( [jvaluebreakfor(int =nelemsk>jk-- [ka[ - ] [jvaluenelems++/end insert(/put element into array /find where it goes /(linear search/move higher ones up /insert it /increment size //public boolean delete(double valueint find(value)if( ==nelems/can' find it return falseelse /found it for(int =jk<nelemsk++/move higher ones down [ka[ + ]nelems--/decrement size return true/end delete(//public void display(/displays array contents for(int = <nelemsj++/for each elementsystem out print( [ ")/display it system out println("")///end class ordarray ///////////////////////////////////////////////////////////////class orderedapp public static void main(string[argsint maxsize /array size ordarray arr/reference to array arr new ordarray(maxsize)/create the array
24,805
arr insert( )arr insert( )arr insert( )arr insert( )arr insert( )arr insert( )arr insert( )arr insert( )arr insert( )/insert items int searchkey /search for item ifarr find(searchkey!arr size(system out println("found searchkey)else system out println("can' find searchkey)arr display()/display items arr delete( )arr delete( )arr delete( )/delete items arr display()/end main(/display items again /end class orderedapp advantages of ordered arrays what have we gained by using an ordered arraythe major advantage is that search times are much faster than in an unordered array the disadvantage is that insertion takes longerbecause all the data items with higher key value must be moved up to make room deletions are slow in both ordered and unordered arraysbecause items must be moved down to fill the hole left by the deleted item ordered arrays are therefore useful in situations in which searches are frequentbut insertions and deletions are not an ordered array might be appropriate for database of company employeesfor example hiring new employees and laying off existing ones would probably be infrequent occurrences compared with accessing an existing employee' record for information or updating it to reflect changes in salaryaddressand so on retail store inventoryon the other handwould not be good candidate for an ordered array because the frequent insertions and deletionsas items arrived in the store and were soldwould run slowly logarithms in this section we'll explain how logarithms are used to calculate the number of steps necessary in binary search if you're math majoryou can probably skip this section if math makes you break out in rashyou can also skip itexcept for taking longhard look at table
24,806
search in the number guessing gamewith range from to it takes maximum of seven guesses to identify any number using binary searchjust as in an array of recordsit takes seven comparisons to find record with specified key value how about other rangestable shows some representative ranges and the number of comparisons needed for binary search table comparisons needed in binary search ange comparisons needed , , , , , , , , , , , , notice the differences between binary search times and linear search times for very small numbers of itemsthe difference isn' dramatic searching items would take an average of five comparisons with linear search ( / )and maximum of four comparisons with binary search but the more items there arethe bigger the difference with itemsthere are comparisons in linear searchbut only seven in binary search for , itemsthe numbers are versus and for , , itemsthey're , versus we can conclude that for all but very small arraysthe binary search is greatly superior the equation you can verify the results of table by repeatedly dividing range (from the first columnin half until it' too small to divide further the number of divisions this process requires is the number of comparisons shown in the second column repeatedly dividing the range by two is an algorithmic approach to finding the number of comparisons you might wonder if you could also find the number using simple equation of coursethere is such an equation and it' worth exploring here because it pops up from time to time in the study of data structures this formula involves logarithms (don' panic yet
24,807
like"what is the exact size of the maximum range that can be searched in five steps?to solve thiswe must create similar tablebut one that starts at the beginningwith range of oneand works up from there by multiplying the range by two each time table shows how this looks for the first ten steps table powers of two step ssame as log (rrange range expressed as power of ( for our original problem with range of we can see that six steps doesn' produce range quite big enough ( )while seven steps covers it handily ( thusthe seven steps that are shown for items in table are correctas are the steps for range of doubling the range each time creates series that' the same as raising two to poweras shown in the third column of table we can express this as formula if represents steps (the number of times you multiply by two--that isthe power to which two is raisedand represents the rangethen the equation is if you know sthe number of stepsthis tells you rthe range for exampleif is the range is or the opposite of raising two to power
24,808
comparisons it will take to complete search that isgiven rwe want an equation that gives us raising something to power is the inverse of logarithm here' the formula we wantexpressed with logarithms log (rthis says that the number of steps (comparisonsis equal to the logarithm to the base of the range what' logarithmthe base- logarithm of number is the number of times you must multiply two by itself to get in table we show that the numbers in the first columnsare equal to log (rhow do you find the logarithm of number without doing lot of dividingpocket calculators and most computer languages have log function this is usually log to the base but you can convert easily to base by multiplying by for examplelog ( so log ( times or rounded up to the whole number this is what appears in the column to the right of in table in any casethe point here isn' to calculate logarithms it' more important to understand the relationship between number and its logarithm look again at table which compares the number of items and the number of steps needed to find particular item every time you multiply the number of items (the rangeby factor of you add only three or four steps (actually before rounding off to whole numbersto the number needed to find particular element this is becauseas number grows largerits logarithm doesn' grow nearly as fast we'll compare this logarithmic growth rate with that of other mathematical functions when we talk about big notation later in this storing objects in the java examples we've shown so farwe've stored primitive variables of type double in our data structures this simplifies the program examplesbut it' not repre sentative of how you use data storage structures in the real world usuallythe data items (recordsyou want to store are combinations of many fields for personnel recordyou would store last namefirst nameagesocial security numberand so forth for stamp collectionyou' store the name of the country that issued the stampits catalog numberconditioncurrent valueand so on in our next java examplewe'll show how objectsrather than variables of primitive typescan be stored the person class in javaa data record is usually represented by class object let' examine typical class used for storing personnel data here' the code for the person classclass person private string lastnameprivate string firstnameprivate int age//public person(string laststring firstint /constructor
24,809
firstname firstage //public void displayperson(system out print(last namelastname)system out print("first namefirstname)system out println("ageage)//public string getlast(return lastname/end class person /get last name we show only three variables in this classfor person' last namefirst nameand age of courserecords for most applications would contain many additional fields constructor enables new person object to be created and its fields initialized the displayperson(method displays person object' dataand the getlast(method returns the person' last namethis is the key field used for searches the classdataarray java program the program that makes use of the person class is similar to the higharray java program that stored items of type double only few changes are necessary to adapt that program to handle person objects here are the major onesthe type of the array is changed to person the key field (the last nameis now string objectso comparisons require the equals(method rather than the =operator the getlast(method of person obtains the last name of person objectand equals(does the comparisonifa[jgetlast(equals(searchname/found itemthe insert(method creates new person object and inserts it in the arrayinstead of inserting double value the main(method has been modified slightlymostly to handle the increased quantity of output we still insert itemsdisplay themsearch for onedelete three itemsand display them all again here' the listing for classdataarray java/classdataarray java /data items as class objects /to run this programc>java classdataapp import java io */for / ///////////////////////////////////////////////////////////////class person
24,810
private 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(return lastname/end class person /get last name ///////////////////////////////////////////////////////////////class classdataarray private person[aprivate int nelems/reference to array /number of data items //public classdataarray(int maxa new person[max]nelems /constructor /create the array /no items yet /public person find(string searchname/find specified value int jfor( = <nelemsj++/for each elementifa[jgetlast(equals(searchname/found itembreak/exit loop before end if( =nelems/gone to endreturn null/yescan' find it
24,811
return [ ]/end find(/nofound it ///put person into array public void insert(string laststring firstint agea[nelemsnew person(lastfirstage)nelems++/increment size /public boolean delete(string searchname/delete person from array int jfor( = <nelemsj++/look for it ifa[jgetlast(equals(searchnamebreakif( ==nelems/can' find it return falseelse /found it for(int =jk<nelemsk++/shift down [ka[ + ]nelems--/decrement size return true/end delete(//public void displaya(for(int = <nelemsj++ [jdisplayperson()/displays array contents /for each element/display it ///end class classdataarray ///////////////////////////////////////////////////////////////class classdataapp public static void main(string[argsint maxsize /array size classdataarray arr/reference to array arr new classdataarray(maxsize)/create the array
24,812
arr insert("evans""patty" )arr insert("smith""lorraine" )arr insert("yee""tom" )arr insert("adams""henry" )arr insert("hashimoto""sato" )arr insert("stimson""henry" )arr insert("velasquez""jose" )arr insert("lamarque""henry" )arr insert("vang""minh" )arr insert("creswell""lucinda" )arr displaya()/display items string searchkey "stimson"/search for item person foundfound=arr find(searchkey)if(found !nullsystem out print("found ")found displayperson()else system out println("can' find searchkey)system out println("deleting smithyeeand creswell")arr delete("smith")/delete items arr delete("yee")arr delete("creswell")arr displaya()/end main(/display items again /end class classdataapp here' the output of this programlast nameevansfirst namepattyage last namesmithfirst namelorraineage last nameyeefirst nametomage last nameadamsfirst namehenryage last namehashimotofirst namesatoage last namestimsonfirst namehenryage last namevelasquezfirst namejoseage last namelamarquefirst namehenryage last namevangfirst nameminhage last namecreswellfirst namelucindaage found last namestimsonfirst namehenryage deleting smithyeeand creswell last nameevansfirst namepattyage last nameadamsfirst namehenryage last namehashimotofirst namesatoage
24,813
last namevelasquezfirst namejoseage last namelamarquefirst namehenryage last namevangfirst nameminhage this program shows that class objects can be handled by data storage structures in much the same way as primitive types (note that serious program using the last name as key would need to account for duplicate last nameswhich would complicate the programming as discussed earlier big notation automobiles are divided by size into several categoriessubcompactscompactsmidsizeand so on these categories provide quick idea what size car you're talking aboutwithout needing to mention actual dimensions similarlyit' useful to have shorthand way to say how efficient computer algorithm is in computer sciencethis rough measure is called big notation you might think that in comparing algorithms you would say things like "algorithm is twice as fast as algorithm ,but in fact this sort of statement isn' too meaningful why notbecause the proportion can change radically as the number of items changes perhaps you increase the number of items by %and now is three times as fast as or you have half as many itemsand and are now equal what you need is comparison that' related to the number of items let' see how this looks for the algorithms we've seen so far insertion in an unordered arrayconstant insertion into an unordered array is the only algorithm we've seen that doesn' depend on how many items are in the array the new item is always placed in the next available positionat [nelems]and nelems is then incremented this requires the same amount of time no matter how big --the number of items in the array--is we can say that the timetto insert an item into an unsorted array is constant kt in real situationthe actual time (in microseconds or whateverrequired by the insertion is related to the speed of the microprocessorhow efficiently the compiler has generated the program codeand other factors the constant in the equation above is used to account for all such factors to find out what is in real situationyou need to measure how long an insertion took (software exists for this very purpose would then be equal to that time linear searchproportional to we've seen thatin linear search of items in an arraythe number of comparisons that must be made to find specified item ison the averagehalf of the total number of items thusif is the total number of itemsthe search time is proportional to half of nt as with insertionsdiscovering the value of in this equation would require timing search for some (probably largevalue of nand then using the resulting value of to calculate once you knew kthen you could calculate for any other value of
24,814
divided by now we have this says that average linear search times are proportional to the size of the array if an array is twice as bigit will take twice as long to search binary searchproportional to log(nsimilarlywe can concoct formula relating and for binary searcht log (nas we saw earlierthe time is proportional to the base logarithm of actuallybecause any logarithm is related to any other logarithm by constant ( to go from base to base )we can lump this constant into as well then we don' need to specify the baset log(ndon' need the constant big notation looks like these formulasbut it dispenses with the constant when comparing algorithms you don' really care about the particular microprocessor chip or compilerall you want to compare is how changes for different values of nnot what the actual numbers are thereforethe constant isn' needed big notation uses the uppercase letter owhich you can think of as meaning "order of in big notationwe would say that linear search takes (ntimeand binary search takes (log ntime insertion into an unordered array takes ( )or constant time (that' the numeral in the parentheses table running times in big notation algorithm running time in big notation linear search (nbinary search (log ninsertion in unordered array ( insertion in ordered array (ndeletion in unordered array (ndeletion in ordered array (
24,815
table summarizes the running times of the algorithms we've discussed so far figure graphs some big relationships between time and number of items based on this graphwe might rate the various big values (very subjectivelylike thiso( is excellento(log nis goodo(nis fairand ( is poor ( occurs in the bubble sort and also in certain graph algorithms that we'll look at later in this book the idea in big notation isn' to give an actual figure for running timebut to convey how the running times are affected by the number of items this is the most meaningful way to compare algorithmsexcept perhaps actually measuring running times in real installation why not use arrays for everythingthey seem to get the job doneso why not use arrays for all data storagewe've already seen some of their disadvantages in an unordered array you can insert items quicklyin ( timebut searching takes slow (ntime in an ordered array you can search quicklyin (logntimebut insertion takes (ntime for both kinds of arraysdeletion takes (ntimebecause half the items (on the averagemust be moved to fill in the hole it would be nice if there were data structures that could do everything--insertiondeletionand searching--quicklyideally in ( timebut if not thatthen in (logntime in the aheadwe'll see how closely this ideal can be approachedand the price that must be paid in complexity another problem with arrays is that their size is fixed when the array is first created with new usually when the program first startsyou don' know exactly how many items will be placed in the array later onso you guess how big it should be if your guess is too largeyou'll waste memory by having cells in the array that are never filled if your guess is too smallyou'll overflow the arraycausing at best message to the program' userand at worst program crash other data structures are more flexible and can expand to hold the number of items inserted in them the linked listdiscussed in "linked lists,is such structure we should mention that java includes class called vector that acts much like an array but is expandable this added capability comes at the expense of some loss of efficiency
24,816
the internal array in this classthe insertion algorithm creates new array of larger sizecopies the old array contents to the new arrayand then inserts the new item all this would be invisible to the class user summary arrays in java are objectscreated with the new operator unordered arrays offer fast insertion but slow searching and deletion wrapping an array in class protects the array from being inadvertently altered class interface comprises the methods (and occasionally fieldsthat the class user can access class interface can be designed to make things simple for the class user binary search can be applied to an ordered array the logarithm to the base of number is (roughlythe number of times you can divide by before the result is less than linear searches require time proportional to the number of items in an array binary searches require time proportional to the logarithm of the number of items big notation provides convenient way to compare the speed of algorithms an algorithm that runs in ( time is the besto(log nis goodo(nis fairand ( is pretty bad simple sorting overview as soon as you create significant databaseyou'll probably think of reasons to sort it in various ways you need to arrange names in alphabetical orderstudents by gradecustomers by zip codehome sales by pricecities in order of increasing populationcountries by gnpstars by magnitudeand so on sorting data may also be preliminary step to searching it as we saw in the last binary searchwhich can be applied only to sorted datais much faster than linear search because sorting is so important and potentially so time-consumingit has been the subject of extensive research in computer scienceand some very sophisticated methods have been developed in this we'll look at three of the simpler algorithmsthe bubble sortthe selection sortand the insertion sort each is demonstrated with its own workshop applet in "advanced sorting,we'll look at more sophisticated approachesshellsort and quicksort the techniques described in this while unsophisticated and comparatively sloware nevertheless worth examining besides being easier to understandthey are actually better in some circumstances than the more sophisticated algorithms the insertion sort
24,817
insertion sort is commonly used as part of quicksort implementation the example programs in this build on the array classes we developed in the last the sorting algorithms are implemented as methods of similar array classes be sure to try out the workshop applets included in this they are more effective in explaining how the sorting algorithms work than prose and static pictures could ever be how would you do itimagine that your kids-league baseball team (mentioned in "overview,"is lined up on the fieldas shown in figure the regulation nine playersplus an extrahave shown up for practice you want to arrange the players in order of increasing height (with the shortest player on the left)for the team picture how would you go about this sorting processas human beingyou have advantages over computer program you can see all the kids at onceand you can pick out the tallest kid almost instantlyyou don' need to laboriously measure and compare everyone alsothe kids don' need to occupy particular places they can jostle each otherpush each other little to make roomand stand behind or in front of each other after some ad hoc rearrangingyou would have no trouble in lining up all the kidsas shown in figure computer program isn' able to glance over the data in this way it can only compare two players at oncebecause that' how the comparison operators work this tunnel vision on the part of algorithms will be recurring theme things may seem simple to us humansbut the algorithm can' see the big picture and mustthereforeconcentrate on the details and follow some simple rules the three algorithms in this all involve two stepsexecuted over and over until the data is sorted compare two items swap two items or copy one item howevereach algorithm handles the details in different way figure the unordered baseball team
24,818
bubble sort the bubble sort is notoriously slowbut it' conceptually the simplest of the sorting algorithmsand for that reason is good beginning for our exploration of sorting techniques bubble-sorting the baseball players imagine that you're nearsighted (like computer programso that you can see only two of the baseball players at the same timeif they're next to each other and if you stand very close to them given this impedimenthow would you sort themlet' assume there are playersand the positions they're standing in are numbered from on the left to on the right the bubble sort routine works like this you start at the left end of the line and compare the two kids in positions and if the one on the left (in is talleryou swap them if the one on the right is talleryou don' do anything then you move over one position and compare the kids in positions and againif the one on the left is talleryou swap them this is shown in figure here are the rules you're following compare two players if the one on the left is tallerswap them move one position right you continue down the line this way until you reach the right end you have by no means finished sorting the kidsbut you do know that the tallest kid is on the right this must be truebecause as soon as you encounter the tallest kidyou'll end up swapping him every time you compare two kidsuntil eventually he (or shewill reach the right end of the line this is why it' called the bubble sortas the algorithm progressesthe biggest items "bubble upto the top end of the array figure shows the baseball players at the end of the first pass
24,819
figure bubble sortend of first pass after this first pass through all the datayou've made - comparisons and somewhere between and - swapsdepending on the initial arrangement of the players the item at the end of the array is sorted and won' be moved again now you go back and start another pass from the left end of the line again you go toward the rightcomparing and swapping when appropriate howeverthis time you can stop one player short of the end of the lineat position - because you know the last positionat - already contains the tallest player this rule could be stated as when you reach the first sorted playerstart over at the left end of the line you continue this process until all the players are in order this is all much harder to describe than it is to demonstrateso let' watch the bubblesort workshop applet at work the bubblesort workshop applet start the bubblesort workshop applet you'll see something that looks like bar graphwith the bar heights randomly arrangedas shown in figure the run button this is two-speed graphyou can either let it run by itself or you can single-step through the process to get quick idea of what happensclick the run button the algorithm will bubble sort the bars when it finishesin seconds or sothe bars will be sortedas
24,820
figure the bubblesort workshop applet figure after the bubble sort the new button to do another sortpress the new button new creates new set of bars and initializes the sorting routine repeated presses of new toggle between two arrangements of barsa random order as shown in figure and an inverse ordering where the bars are sorted backward this inverse ordering provides an extra challenge for many sorting algorithms the step button the real payoff for using the bubblesort workshop applet comes when you single-step through sort you'll be able to see exactly how the algorithm carries out each step start by creating new randomly arranged graph with new you'll see three arrows pointing at different bars two arrowslabeled inner and inner+ are side-by-side on the left another arrowouterstarts on the far right (the names are chosen to correspond to the inner and outer loop variables in the nested loops used in the algorithm click once on the step button you'll see the inner and the inner+ arrows move together one position to the rightswapping the bars if it' appropriate these arrows correspond to the two players you comparedand possibly swappedin the baseball scenario
24,821
be swappedbut you know this just from comparing the barsif the taller one is on the leftthey'll be swapped messages at the top of the graph tell you how many swaps and comparisons have been carried out so far ( complete sort of bars requires comparisons andon the averageabout swaps continue pressing step each time inner and inner+ finish going all the way from to outerthe outer pointer moves one position to the left at all times during the sorting processall the bars to the right of outer are sortedthose to the left of (and atouter are not the size button the size button toggles between bars and bars figure shows what the random bars look like you probably don' want to single-step through the sorting process for bars unless you're unusually patient press run insteadand watch how the blue inner and inner+ pointers seem to find the tallest unsorted bar and carry it down the row to the rightinserting it just to the left of the sorted bars figure shows the situation partway through the sorting process the bars to the right of the red (longestarrow are sorted the bars to the left are beginning to look sortedbut much work remains to be done 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 operationor press run again to return to high-speed mode figure the bubblesort applet with bars
24,822
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 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 double 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 the last section of this 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 double[ /ref to array private int nelems/number of data items //public arraybub(int max/constructor new double[max]/create the array nelems /no items yet //public void insert(double value/put element into array [nelemsvalue/insert it nelems++/increment size //public void display(/displays array contents
24,823
system out print( [ ")system out println("")/for each element/display it //public void bubblesort(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 twodouble 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( )/insert items arr insert( )arr insert( )arr insert( )arr insert( )arr insert( )arr insert( )arr insert( )arr insert( )arr insert( )arr display()/display items arr bubblesort()/bubble sort them arr display()/display them again
24,824
/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 compared and 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 secondthen setting the second cell to the temporary value actuallyusing separate swap(method may not be good idea in practicebecause 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 outer are sorted this remains true throughout the running of the algorithm (on the first
24,825
it starts on the rightmost element efficiency of the bubble sort as you can see by watching the workshop applet with barsthe inner and inner+ arrows make comparisons on the first pass on the secondand so ondown to comparison on the last pass for items this 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 thus the algorithm makes about / comparisons (ignoring the - which doesn' make much differenceespecially if is largethere are fewer swaps than there are comparisonsbecause 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 workshop applet with bars whenever you see nested loops such 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 (typically this 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 thus you'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 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
24,826
won' need to be moved again notice that in this algorithm the sorted players accumulate on the left (lower indices)while 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 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 playerand 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 notebookand move the towelwhenever you find shorter player when you're donethe magenta towel will be in front of the shortest player 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 leftbecause this player has already been sorted thus the 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 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 gradually it 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 whileand 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
24,827
figure the selectsort workshop appletred 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(outer/end selectionsort(
24,828
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 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 double[ /ref to array private int nelems/number of data items //public arraysel(int max/constructor new double[max]/create the array nelems /no items yet //public void insert(double 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
24,829
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(outer/end selectionsort(//private void swap(int oneint twodouble 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 /
24,830
invariant in the selectsort java programthe data items with indices less than or equal to outer 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 nit 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 start 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 throw 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 left howeverthey aren' necessarily in their final positionsbecause they may still need to be moved when previously unsorted players are inserted between them 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 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 is shown in
24,831
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 is shown in figure figure the insertion sort on baseball players 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 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 it' hard to see what' there (unless you slow down to single-step modesorting bars
24,832
sure they're in random order 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 copy means that there are now two bars with the same height and color shown on the graph this is slightly misleadingbecause in real java program there are actually two references pointing to the same objectnot two identical objects howevershowing two identical bars is meant to convey the idea of copying the reference figure the insertsort workshop applet with bars what happens next depends on whether the first two bars are already in order (smaller on the leftif they areyou'll see 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 performedbecause 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 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 againit' easier to see what' happening 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
24,833
figure the insertsort workshop applet with bars 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 double temp [out]/remove marked item in out/start shifts at out while(in> & [in- >temp/until one is smallera[ina[in- ]/shift item right--in/go left one position [intemp/insert marked item /end for /end insertionsort(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 workshop applet and the codeso figure is flow diagram of the insertionsort(methodwith the corresponding messages from the insertsort workshop applet listing shows the complete insertsort java program listing the insertsort java program /insertsort java /demonstrates insertion sort
24,834
//class arrayins private double[ /ref to array private int nelems/number of data items //public arrayins(int max/constructor new double[max]/create the array nelems /no items yet //public void insert(double 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 double temp [out]/remove marked item in out/start shifts at out while(in> & [in- >temp/until one is smallera[ina[in- ]/shift item right--in/go left one position [intemp/insert marked item /end for /end insertionsort(/
24,835
/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()/end main(/end class insertsortapp /display them again here' the output from the insertsort java programit' the same as that from the other programs in this
24,836
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 givesn*( - )/ 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
24,837
primitive types accordinglywe show java programobjectsort javathat sorts an array of person objects (last seen in the classdataarray java program in java code for sorting objects the algorithm used is the insertion sort from the last 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(return lastname/end class person /get last name ///////////////////////////////////////////////////////////////class arrayinob private person[aprivate int nelems/ref to array /number of data items
24,838
/constructor 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 outfoundwhile(in> &/out is dividing line /remove marked person /start shifting at out /until smaller one [in- getlast(compareto(temp getlast())> [ina[in- ]--ina[intemp/end for /end insertionsort(/shift item to the right /go left one position /insert marked item ///end class arrayinob ///////////////////////////////////////////////////////////////
24,839
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 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
24,840
last nameyeefirst nametomage lexicographical comparisons the insertionsort(method 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 insertionsort(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( equals return value < > for exampleif is "catand is "dog"the function will return number less than in the program this 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 happen to 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 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 there are three persons with the last name of smith initially the 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
24,841
book handy the bubble sort is so simple 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 it 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 thatbeside 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 how long it takes 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 (actually references to the itemsaround until they're in sorted order 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 inthis require more than single temporary variable in addition to the original array part ii list stacks and queues linked lists
24,842
recursion stacks and queues overview 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 the array--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 on)are appropriate for the kind of data you might find in database application they're typically used for personnel recordsinventoriesfinancial dataand so ondata 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 fullfledged data storage devices their lifetime is typically shorter than that of the databasetype structures they are created and used to carry out particular task during the operation of programwhen the task is completedthey're discarded 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 the 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 for examplethe underlying mechanism for stack can 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
24,843
stack allows access to only one data itemthe last item inserted if you remove this itemthen you can access the next-to-last item insertedand so on this is useful capability in many programming situations in this sectionwe'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 returns they'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 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 first they open the letter on the top of the stack and take appropriate action--paying the billthrowing it awayor whatever when the first letter has been disposed ofthey examine the next letter downwhich is now the top of the stackand deal with that eventually they work their way down to the letter on the bottom of the stack (which is now the topfigure shows stack of mail 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 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
24,844
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 you 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 mechanismbecause 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 the appletyou'll see four buttonsnewpushpopand peekas shown in figure 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 it as you would an array 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 figure the stack workshop applet
24,845
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 push 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 typing it 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 stackthat 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' overwrite the existing item at top when 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 pop 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 involvedfirst the 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 arrayand 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 once the top marker drops below their positionso conceptually they are goneas the applet shows when you've popped the last item off the stackthe top arrow points to - below the lowest cell this 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 peek 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 only peek 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
24,846
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 import java io */for / ///////////////////////////////////////////////////////////////class stackx private int maxsize/size of stack array private double[stackarrayprivate int top/top of stack //public stackx(int /constructor maxsize /set array size stackarray new double[maxsize]/create array top - /no items yet //public void push(double /put item on top of stack stackarray[++topj/increment topinsert item //public double pop(/take item from top of stack return stackarray[top--]/access itemdecrement top //public double peek(/peek at top of stack return stackarray[top]//public boolean isempty(/true if stack is empty
24,847
//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( )stack while!thestack isempty(/until it' empty/delete item from double value thestack pop()system out print(value)/display it system out print(")/end while system out println("")/end main(/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 double as noted in the last 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 comprise 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
24,848
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 topand stores data item there notice 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 figure operation of the stackx class methods 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 fullor pop an item from stack that' emptywe'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(
24,849
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 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 first the 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
24,850
return stackarray[top]//public boolean isempty(/true if stack is empty return (top =- )///end class stackx ///////////////////////////////////////////////////////////////class reverser private string inputprivate string output/input string /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 input for(int = <input length() ++char ch input charat( )/get char from thestack push(ch)output ""while!thestack isempty(char ch thestack pop()output output chreturn output/end dorev(/push it /pop char/append to output ///end class reverser ///////////////////////////////////////////////////////////////
24,851
public static void main(string[argsthrows ioexception 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 it 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 stringstack example delimiter matching one common use for stacks is to parse certain kinds of text strings typically the 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
24,852
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 examplesc[da{ [ ] } { ( ] } [ { } ]ea{ ( /correct /correct /not correctdoesn' match /not correctnothing matches final /not correctnothing matches opening opening delimiters on the stack the program works by reading characters from the string one at time and placing opening delimiterswhen 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)then an error has occurred alsoif there is no opening delimiter on the stack to match closing oneor if delimiter has not been matchedan error has occurred 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 stack contents are shown in the second column the entries in this column show the stack contentsreading from the bottom of the stack on the left to the top on the right as it' 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 nondelimiter characters are not inserted on the stackthey're ignored table stack contents in delimiter matching character read stack contents { {{(
24,853
{({ { 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 - //public void push(char /put item on top of stack stackarray[++topj/
24,854
/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 '['case '('thestack push(ch)breakcase '}'/get chars in turn /get char /opening symbols /push them /closing symbols
24,855
case ']'case ')'if!thestack isempty(/if stack not char 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 [enterbreak/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)
24,856
string br readline()return ///end class bracketsapp the check(routine makes use of the stackx class from the last program 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 left)and 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 program easier to understand and less error prone (carpenters will also tell you it' 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 stackand 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 similar to stackexcept that in queue the first item inserted is the first to be removed (fifo)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 this looks
24,857
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 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 start up the queue workshop applet you'll see queue with four items preinstalledas shown in figure 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-goersandhaving arrived at the front of the line and purchased ticketremoving themselves 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 figure the queue workshop applet
24,858
frontwhere items are removedmay also be called the head we'll use the terms insertremovefrontand rear insert 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 remove similarlyyou can remove the item at the front of the queue using the rem button the person is removedthe person' value is stored in the number field (corresponding to the remove(method returning valueand 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 unlike the situation in stackthe items in queue don' always extend all the way down to index in the array once some items are removedfront will point at cell with higher indexas shown in figure figure operation of the queue class methods notice that in this figure front lies below rear in the arraythat isfront has lower index as we'll see in momentthis isn' always true peek we show one other queue operationpeek this finds the value of the item at the front of the queue without removing the item (like insert and removepeek when applied to queue is also called by variety of other names if you press the peek buttonyou'll see the value at front transferred to the number box the queue is unchanged
24,859
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 new 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 circular queue when you insert new item in the queue in the 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 instead we 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 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 the front of the array nowinsert another item you'll see the rear arrow wrap around from index to index the new item will be inserted there this is shown in figure
24,860
once 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 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 figure rear arrow at the end of the array figure rear arrow wraps around 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
24,861
listing the queue java program /queue java /demonstrates queue /to run this programc>java queueapp import java io */for / ///////////////////////////////////////////////////////////////class queue private int maxsizeprivate int[quearrayprivate int frontprivate int rearprivate int nitems//public queue(int /constructor maxsize squearray new int[maxsize]front rear - nitems //public void insert(int /put item at rear of queue if(rear =maxsize- /deal with wraparound rear - quearray[++rearj/increment rear and insert nitems++/one more item //public int remove(/take item from front of queue int temp quearray[front++]/get value and incr front if(front =maxsize/deal with wraparound front nitems--/one less item return temp//public int peekfront(/peek at front of queue
24,862
//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(int thequeue remove()system out print( )/remove and display /all items /(
24,863
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 only call insert(after calling isfull(and getting return value of false (it' usually preferable to place the check for fullness in the insert(routineand 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 occurs rear will become the bottom of the array finally nitems 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 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
24,864
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 int[quearrayprivate int frontprivate int rear//public queue(int /constructor maxsize + /array is cell larger quearray new int[maxsize]/than requested front rear - //public void insert(int /put item at rear of queue if(rear =maxsize- rear - quearray[++rearj//public int remove(/take item from front of queue int temp quearray[front++]if(front =maxsizefront return temp//public int peek(/peek at front of queue return quearray[front]
24,865
//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 nocount 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 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)then the deque acts like stack if you restrict yourself to insertleft(and removeright((or the opposite pair)then it acts like queue deque provides more versatile data structure than either stack or queueand 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 however
24,866
queue has front and rearand items are removed from the front howeverin priority queueitems are ordered by key valueso 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 topwhile if it can wait for leisurely answer ( letter from your aunt mabel)it goes on the bottom 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 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 figure letters in priority queue 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 in many situations you want access to the item with the lowest key value (which might represent the cheapest or shortest way to do somethingthus the 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 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
24,867
items are kept in sorted order it' an ascending-priority queuein which the item with the smallest key has the highest priority and is accessed with remove((if the highest-key item were accessedit would be descending-priority queue 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 initially there are five items in the queue figure the priorityq workshop applet insert 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 once 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 delete 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 comparisons or shifting 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 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 peek and new 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
24,868
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 insertion very quickbut unfortunately it makes deletion slowbecause the smallest item must be searched for this requires examining all the items and shifting half of themon the averagedown to fill in the hole generallythe quick-deletion approach shown in the workshop applet is preferred for small numbers of itemsor situations where speed isn' criticalimplementing priority queue with an array is satisfactory for larger numbers of itemsor when speed is criticalthe heap is better choice figure operation of the priorityq class methods 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 import java io */for / ///////////////////////////////////////////////////////////////class priorityq /array in sorted orderfrom max at to min at size- private int maxsizeprivate double[quearrayprivate int nitems//public priorityq(int /constructor
24,869
quearray new double[maxsize]nitems //public void insert(double item/insert item int jif(nitems== /if no itemsquearray[nitems++item/insert at else /if any itemsfor( =nitems- >= --/start at endifitem quearray[ /if new item largerquearray[ + quearray[ ]/shift upward else /if smallerbreak/done shifting /end for quearray[ + item/insert it nitems++/end else (nitems /end insert(//public double remove(/remove minimum item return quearray[--nitems]//public double 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( )
24,870
thepq insert( )thepq insert( )thepq insert( )thepq insert( )while!thepq isempty(double item thepq remove()system out print(item ")/end while system out println("")/end main(/ ///end class priorityqapp in main(we insert five items in random order and then remove and display them the smallest item is always removed firstso the output is the insert(method checks if 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 it and increments nitems note that if there' any chance the priority queue is full you should check for this possibility with isfull(before using insert(the front and rear fields aren' necessary as they were in the queue classbecauseas 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 like + or *( + or (( + )* )+ *( - )and the storage structure it uses is the stack in the brackets java programwe 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
24,871
howeverit' educational to see this important use of stacksand 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 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 notationbecause the operator is written inside the operands thus we 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 thus + 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 + - ab+ca* / ab*ca+ * abc* * + ab*ca*( +cabc+ * + * ab*cd*( + )*( -dab+cd-(( + )* )- ab+ *
24,872
abcdef+/-*some computer languages also have an operator for raising quantity to power (typically the 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 is functionally similar to postfix but seldom used translating infix to postfix the next several pages are devoted to explaining how to translate an expression from infix notation into postfix this is fairly involved algorithmso 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 in understanding how to create postfix expressionit may be 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 earlierthis 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 do thiswe 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 least we'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 this process is continued--going from left to right and evaluating when possible-until the end of the expression in tables and we're going to 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 table evaluating + - item read expression parsed so far comments
24,873
+ 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' 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 how this looks 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 operand-operatoroperand combination because of precedence relationshipsit' bit more complicated to evaluate + * as shown in table table evaluating + * item read expression parsed so far comments + + can' evaluate + because is higher precedence than + * when you see the you can evaluate *
24,874
end 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 examplefigure evaluating + * often you can evaluate as you go from left to rightas in the last example howeveryou need to be surewhen you come to an operand-operator-operand combination like +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 howeveronce you've read the the multiplication can be carried out because it has the highest priorityit doesn' matter if 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 can by used to override the normal precedence of operators table shows how you would evaluate *( + without the parentheses you' do the multiplication firstwith them you do the addition first
24,875
table evaluating *( + item read expression parsed so far comments * *( *( *( + can' evaluate + yet *( + when you see the ')you can evaluate + * when you've evaluated + you can evaluate * can' evaluate * because of parentheses end 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
24,876
parentheses before using the result as an operand in any other calculation the closing parenthesis tells us we can go ahead and do the addition we find that + is and once we know thiswe can evaluate * to obtain reaching the end of the expression is an anticlimax because there' nothing left to evaluate the process is shown in figure 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 happens you must apply the laterhigherprecedenceoperator firstthen go backward (to the leftand apply earlier operators figure evaluating *( + we could write an algorithm to carry out this kind of evaluation directly howeveras we notedit' actually easier to translate into postfix notation first 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
24,877
table translating + - into postfix character read from infix expression infix expression parsed so far postfix expression written so far aa + ab +babc + - ab+ end + - 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 is similar to table which covered the evaluation of + * table translating + * to postfix character read from infix expression infix expression parsed so far postfix expression written so far aa + ab comments
24,878
+bab can' copy the +because is higher precedence than + * abc when you see the cyou can copy the + * abca+ * abc*end when you see the end of the expressionyou can copy the as the final exampletable shows how *( +cis translated to postfix this is similar to evaluating *( + in table you can' write any postfix operators until you see the closing parenthesis in the input table translating *( + into postfix character read from infix expression infix expression parsed so far postfix expression written so far aa * *( ab *(bab *( + abc can' copy the yet *( +cabcwhen you see the you can copy the *( +cabc+when you've copied the +you can copy the comments can' copy because of parenthesis
24,879
*( +cabc+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 operatoror the operator in parenthesesmust be written to the postfix before the lower priority operator 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 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 + ab +bab + + *ab +* + *( abc +* + *(cabc +*( + *( - abcd +*( + *( -dabcd+* + *( -dabcd+* + *( -dabcd+ + *( -dabcd- + *( -dabcd-* stack contents
24,880
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 these 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 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 translation rules item read from input(infixaction operand write it to output (postfixopen parenthesis push it on stack close parenthesis while stack not emptyrepeat the followingpop an itemif item is not (write it to output quit loop if item is operator (opthisif stack emptypush opthis otherwise
24,881
pop 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 no more items while stack not emptypop itemoutput it it may take some work to convince yourself that these rules work tables and show how the rules apply to three sample infix expressions these 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 table translation rules applied to + - character read from infix infix parsed so far postfix written so far stack contents rule aa if stack emptypush opthis + ab write operand to output +bab stack not emptyso pop item +babopthis is -optop is +optop>=opthisso output optop write operand to output
24,882
abthen push opthis + - ab+ write operand to output end + - ab+cpop leftover itemoutput it table translation rules applied to + * character read from infix infix parsed so far postfix written so far stack contents rule aa if stack emptypush opthis + ab write operand to output +bab stack not emptyso pop optop +bab opthis is *optop is optop<opthisso push optop +bab +then push opthis + * abc +write operand to output end + * abcpop leftover itemoutput it + * abc*write operand to postfix pop leftover itemoutput it
24,883
character read from infix infix parsed so far postfix written so far aa if stack emptypush opthis * *push on stack *( ab *write operand to postfix *(bab stack not emptyso pop item *(bab *it' (so push it *(bab *(then push opthis *( + abc *(write operand to postfix *( +cabc*pop itemwrite to output *( +cabcquit popping if *( +cabc+end stack contents rule write operand to postfix pop leftover itemoutput it java code to convert infix to postfix listing shows the infix java programwhich uses the rules of 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 /
24,884
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 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(')
24,885
system out println("")///end class stackx ////////////////////////////////////////////////////////////////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)//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
24,886
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()ifoptop ='(/if it' '(thestack push(optop)/restore '(breakelse /it' an operator int prec /precedence of new op less if(optop=='+|optop=='-'/find new op prec prec else prec if(prec prec /if prec of new op /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
24,887
else output output chx/end while /end popops(/if popped operator /output it ///end class intopost ///////////////////////////////////////////////////////////////class infixapp 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 parenthesis ')these methods
24,888
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 only supposed to access the item at the top howeveras diagnostic aid it' useful to see the contents of the stack at each stage of the translation here' some sample interaction with infix javaenter infixinput= *( + )- /( +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)parsing arithmetic expressionsfor 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 programand within 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 infixinput= + * 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 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
24,889
as you can seeit' not trivial to convert infix expressions to postfix expressions 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 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 figure visual approach to postfix evaluation of +* +/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 (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 push it onto the stack operator pop the top two operands from the stackand apply the operator to them push the result
24,890
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 worked because we weren' performing arithmetic operations on the operandsbut merely rewriting them in different format now we want to evaluate postfix expressionwhich means carrying out the arithmetic and obtaining an answer thus the input must consist of actual numbers to simplify the coding we'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 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
24,891
//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() ++system out printpeekn( )system out print(')system out println("")///end class stackx ///////////////////////////////////////////////////////////////class parsepost private stackx thestack
24,892
//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 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 ///////////////////////////////////////////////////////////////
24,893
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 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 stringcharacter 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 alreadybecause the input string is in postfix notation the result of the arithmetic operation is pushed onto the stack once 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 corresponds to the infix *( + )- /( + (we saw an equivalent translation using letters instead of numbers in the last sectiona*( + )- /( +fin infix is abc+*def+/in postfix here' how the postfix is evaluated by the postfix java program
24,894
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 as with the last programpostfix 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
24,895
evaluating postfix expression linked lists overview in "arrays,we saw that arrays had certain disadvantages as data storage structures in an unordered arraysearching is slowwhereas in an ordered arrayinsertion is slow in both kinds of arrays deletion is slow alsothe size of an array can' be changed after it' created 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 general-purpose storage structures after arrays 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 where you use an array (unless you need frequent random access to individual items using an indexlinked 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 listsdouble-ended listssorted listsdoubly linked listsand lists with iterators (an approach to random access to list elementswe'll also examine the idea of abstract data types (adtsand 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 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 is shown in figure here' part of the definition of class link it contains some data and reference to the next link class 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 items
24,896
public inventoryitem iipublic link next/object holding data /reference to next link figure links in list references and basic types it' easy to get confused about references in the context of linked listsso let' review how they work it may seem odd that you can put field of type link inside the class definition of this same type 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 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 thus it' no problem for the compiler to figure out how big this field should beand thereby construct an entire link object note that in javaprimitive types like 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 objectlike link alink somelinkputs reference to an object of type linkcalled somelinkinto alink the somelink object isn' movedor even createdby this statementit must have been created before to create an object you must always use newlink somelink new link()
24,897
somewhere else in memoryas shown in figure other languageslike ++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 objectsit may be counter intuitive 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 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 up initially there are links on the list
24,898
insert if you think is an unlucky numberyou can insert new link click on 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 it' also possible to 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 look neater find the find button allows you 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 it finds it if you type nonexistent key valuethe arrow will search all the way to the end of the list before reporting that the item can' be found figure new link being inserted delete you can also delete key with specified value type in the value of an existing linkand
24,899
finds itit simply removes it 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 this just provides evenly spaced links for aesthetic reasonsthe length of the arrows doesn' correspond to anything in the program unsorted and sorted 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 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 idatapublic double ddatapublic link next/data item /data item /next link in list /public link(int iddouble dd/constructor idata id/initialize data ddata dd/('nextis automatically /set to null/public void displaylink(/display ourself system out print("{idata "ddata "")