id
int64
0
25.6k
text
stringlengths
0
4.59k
22,500
data structures algorithms in javasecond edition storing objects the person class the classdataarray java program big notation insertion in an unordered arrayconstant linear searchproportional to binary searchproportional to log( don' need the constant why not use arrays for everything summary questions experiments pro...
22,501
questions experiments programming projects stacks and queues different kind of structure programmer' tools restricted access more abstract stacks the postal analogy the stack workshop applet java code for stack stack example reversing word stack example delimiter matching efficiency of stacks queues the queue workshop ...
22,502
data structures algorithms in javasecond edition the linklist workshop applet the insert button the find button the delete button simple linked list the link class the linklist class the insertfirst(method the deletefirst(method the displaylist(method the linklist java program finding and deleting specified links the f...
22,503
where does the iterator point the atend(method iterative operations other methods summary questions experiments programming projects recursion triangular numbers finding the nth term using loop finding the nth term using recursion the triangle java program what' really happening characteristics of recursive methods is ...
22,504
data structures algorithms in javasecond edition the knapsack problem combinationspicking team summary questions experiments programming projects advanced sorting shellsort insertion sorttoo many copies -sorting diminishing gaps the shellsort workshop applet java code for the shellsort other interval sequences efficien...
22,505
binary trees why use binary trees slow insertion in an ordered array slow searching in linked list trees to the rescue what is tree tree terminology path root parent child leaf subtree visiting traversing levels keys binary trees an analogy how do binary search trees work the binary tree workshop applet representing th...
22,506
data structures algorithms in javasecond edition the efficiency of binary trees trees represented as arrays duplicate keys the complete tree java program the huffman code character codes decoding with the huffman tree creating the huffman tree coding the message creating the huffman code summary questions experiments p...
22,507
experiment an unbalanced tree more experiments the red-black rules and balanced trees null children rotations simple rotations the weird crossover node subtrees on the move human beings versus computers inserting new node preview of the insertion process color flips on the way down rotations after the node is inserted ...
22,508
data structures algorithms in javasecond edition the dataitem class the node class the tree class the tree app class the complete tree java program trees and red-black trees transformation from to red-black operational equivalence efficiency of trees speed storage requirements - trees node splits implementation externa...
22,509
hash functions quick computation random keys non-random keys hashing strings folding hashing efficiency open addressing separate chaining open addressing versus separate chaining hashing and external storage table of file pointers non-full blocks full blocks summary questions experiments programming projects heaps intr...
22,510
data structures algorithms in javasecond edition tree-based heap heapsort trickling down in place using the same array the heapsort java program the efficiency of heapsort summary questions experiments programming projects graphs introduction to graphs definitions historical note representing graph in program adding ve...
22,511
weighted graphs minimum spanning tree with weighted graphs an examplecable tv in the jungle the graphw workshop applet send out the surveyors creating the algorithm java code the mstw java program the shortest-path problem the railroad line dijkstra' algorithm agents and train rides using the graphdw workshop applet ja...
22,512
data structures algorithms in javasecond edition priority queue comparison of special-purpose structures sorting graphs external storage sequential storage indexed files -trees hashing virtual memory onward appendixes running the workshop applets and example programs the workshop applets the example programs the sun mi...
22,513
simple sorting answers to questions stacks and queues answers to questions linked lists answers to questions recursion answers to questions advanced sorting answers to questions binary trees answers to questions red-black trees answers to questions trees and external storage answers to questions hash tables answers to ...
22,514
robert lafore has degrees in electrical engineering and mathematicshas worked as systems analyst for the lawrence berkeley laboratoryfounded his own software companyand is best-selling writer in the field of computer programming some of his current titles are +interactive course and objectoriented programming in +earli...
22,515
this book is dedicated to my readerswho have rewarded me over the years not only by buying my booksbut with helpful suggestions and kind words thanks to you all
22,516
my gratitude for the following people (and many otherscannot be fully expressed in this short acknowledgment as alwaysmitch waite had the java thing figured out before anyone else he also let me bounce the applets off him until they did the joband extracted the overall form of the project from miasma of speculation my ...
22,517
as the reader of this bookyou are our most important critic and commentator we value your opinion and want to know what we're doing rightwhat we could do betterwhat areas you' like to see us publish inand any other words of wisdom you're willing to pass our way as an executive editor for sams publishingi welcome your c...
22,518
this introduction tells you briefly what' new in the second edition what this book is about why it' different who might want to read it what you need to know before you read it the software and equipment you need to use it how this book is organized what' new in the second edition this second edition of data structures...
22,519
data structures algorithms in javasecond edition the knapsack problem listing things taken at time folding-digits hash functions the radix sort end-of-questions short questions covering the key points of each are included at the end of each the answers can be found in appendix "answers to questions these questions are ...
22,520
almost every computer programeven simple oneuses data structures and algorithms for exampleconsider program that prints address labels the program might use an array containing the addresses to be printed and simple for loop to step through the arrayprinting each address the array in this example is data structureand t...
22,521
data structures algorithms in javasecond edition howeverit' our belief that data structures and algorithms are complicated enough without involving this additional disciplineso we have deliberately de-emphasized software engineering in this book (we'll discuss the relationship of data structures and algorithms to softw...
22,522
java example code the java language is easier to understand (and writethan languages such as and +the biggest reason for this is that java doesn' use pointers some people are surprised that pointers aren' necessary for the creation of complex data structures and algorithms in facteliminating pointers makes such code no...
22,523
data structures algorithms in javasecond edition the software you need to use this book to run the workshop appletsyou need web browser such as microsoft internet explorer or netscape communicator you can also use an applet viewer utility applet viewers are available with various java development systemsincluding the f...
22,524
"linked lists,introduces linked listsincluding doubly linked lists and double-ended lists the use of references as "painless pointersin java is explained workshop applet shows how insertionsearchingand deletion are carried out in "recursion,we explore recursionone of the few topics that is not data structure many examp...
22,525
data structures algorithms in javasecond edition appendix "further reading,describes some books appropriate for further reading on data structures and other related topics appendix "answers to questions,contains the answers to the end-of-questions in the text enjoy yourselfwe hope we've made the learning process as pai...
22,526
overview in this what are data structures and algorithms good foroverview of data structures as you start this bookyou may have some questionswhat are data structures and algorithmsoverview of algorithms some definitions what good will it do me to know about themobject-oriented programming why can' just use arrays and ...
22,527
overview what sorts of problems can you solve with knowledge of these topicsas rough approximationwe might divide the situations in which they're useful into three categoriesreal-world data storage programmer' tools modeling these are not hard-and-fast categoriesbut they may help give you feeling for the usefulness of ...
22,528
of coursemost programs are more complex than index cards imagine the database the department of motor vehicles (or whatever it' called in your stateuses to keep track of driverslicensesor an airline reservations system that stores passenger and flight information such systems may include many data structures designing ...
22,529
overview table continued data structure advantages disadvantages stack provides last-infirst-out access provides first-infirst-out access quick insertionquick deletion quick searchinsertiondeletion (if tree remains balancedquick searchinsertiondeletion tree always balanced quick searchinsertiondeletion tree always bala...
22,530
you may also need to know how to iterate through all the items in data structurevisiting each one in turn so as to display it or perform some other action on it another important algorithm category is sorting there are many ways to sort dataand we devote "simple sorting,and "advanced sorting,to these algorithms the con...
22,531
overview employee numbersocial security numberlast namefirst namestreet addresscitystatezip codephone numberdate of birthdate of first employmentsalaryfigure record with multiple fields key to search for record within databaseyou need to designate one of the record' fields as key (or search keyyou'll search for the rec...
22,532
there were two kinds of problems one was the lack of correspondence between the program and the real worldand the other was the internal organization of the program poor modeling of the real world conceptualizing real-world problem using procedural languages is difficult methods carry out taskwhile data stores informat...
22,533
overview objects here' the amazing breakthrough that is the key to oopan object contains both methods and variables thermostat objectfor examplewould contain not only furnace_on(and furnace_off(methodsbut also variables called currenttemp and desiredtemp in javaan object' variables such as these are called fields this ...
22,534
programmers will recognize this syntax as similar to structurewhile +programmers will notice that it' very much like class in ++except that there' no semicolon at the end (why did we need the semicolon in +anyway?creating objects specifying class doesn' create any objects of that class (in the same wayspecifying struct...
22,535
overview these concepts are deep and far reaching it' almost impossible to assimilate them the first time you see themso don' worry if you feel bit confused as you see more classes and what they dothe mist should start to clear runnable object-oriented program let' look at an object-oriented program that runs and gener...
22,536
listing continued class bankapp public static void main(string[argsbankaccount ba new bankaccount( )/create acct system out print("before transactions")ba display()/display balance ba deposit( )ba withdraw( )/make deposit /make withdrawal system out print("after transactions")ba display()/display balance /end main(/end...
22,537
overview the system out print(method displays the string used as its argumentbefore transactions:and the account displays its balance with this statementba display()the program then makes deposit toand withdrawal fromthe accountba deposit( )ba withdraw( )finallythe program displays the new account balance and terminate...
22,538
inheritance and polymorphism we'll briefly mention two other key features of object-oriented programminginheritance and polymorphism inheritance is the creation of one classcalled the extended or derived classfrom another class called the base class the extended class has all the features of the base classplus some add...
22,539
overview it' not clear that mixing software engineering on one hand and data structures and algorithms on the other actually helps the student understand either topic software engineering is rather abstract and is difficult to grasp until you've been involved yourself in large project the use of data structures and alg...
22,540
in the first statementa memory location called intvar actually holds numerical value such as (assuming such value has been placed therehoweverthe memory location bc does not hold the data of bankaccount object insteadit contains the address of bankaccount object that is actually stored elsewhere in memory the name bc i...
22,541
overview the new operator any object in java must be created using new howeverin javanew returns referencenot pointer as in +thuspointers aren' necessary to use new here' one way to create an objectbankaccount ba ba new bankaccount()eliminating pointers makes for more secure system as programmeryou can' find out the ac...
22,542
equality and identity in javaif you're talking about primitive typesthe equality operator (==will tell you whether two variables have the same valueint intvar int intvar intvar if(intvar =intvar system out println("they're equal")this is the same as the syntax in and ++but in javabecause relational operators use refere...
22,543
overview table primitive data types name size in bits range of values boolean true or false byte char short int long float double - to + '\ to '\uffff- , to + , - , , , to + , , , - , , , , , , to + , , , , , , approximately - to + significant digits approximately - to + significant digits unlike and ++which use intege...
22,544
output you can send any primitive type (numbers and characters)and string objects as wellto the display with these statementssystem out print(var)system out println(var)/displays varno linefeed /displays varthen starts new line the print(method leaves the cursor on the same lineprintln(moves it to the beginning of the ...
22,545
overview this method returns string objectwhich is composed of characters typed on the keyboard and terminated with the enter key the details of the inputstreamreader and bufferedreader classes need not concern us here besides importing java io *you'll need to add throws ioexception to all input methodsas shown in the ...
22,546
for simplicitywe don' show any error-checking in the input routines in the example programs the user must type appropriate inputor an exception will occur with the code shown here the exception will cause the program to terminate in serious program you should analyze the input string before attempting to convert it and...
22,547
overview summary data structure is the organization of data in computer' memory or in disk file the correct choice of data structure allows major improvements in program efficiency examples of data structures are arraysstacksand linked lists an algorithm is procedure for carrying out particular task in javaan algorithm...
22,548
in databasea field is specific data item specific object part of record part of an algorithm the field used when searching for particular record is the in object-oriented programmingan object is class may contain data and methods is program may contain classes class is blueprint for many objects represents specific rea...
22,549
arrays the array is the most commonly used data storage structureit' built into most programming languages because arrays are so well knownthey offer convenient jumpingoff place for introducing data structures and for seeing how object-oriented programming and data structures relate to one another in this we'll introdu...
22,550
arrays check to see whether particular player is presentby searching for the player' number in the structure delete player from the data structure when that player goes home these three operations--insertionsearchingand deletion--will be the fundamental ones in most of the data storage structures we'll study in this bo...
22,551
this applet demonstrates the three fundamental procedures mentioned earlierthe ins button inserts new data item the find button searches for specified data item the del button deletes specified data item using the new buttonyou can create new array of size you specify you can fill this array with as many data items as ...
22,552
arrays in no-duplicates mode you're on your honor not to insert an item with the same key as an existing item if you dothe applet displays an error messagebut it won' prevent the insertion the assumption is that you won' make this mistake searching to begin searchclick the find button you'll be prompted for the key num...
22,553
implicit in the deletion algorithm is the assumption that holes are not allowed in the array hole is one or more empty cells that have filled cells above them (at higher index numbersif holes are allowedall the algorithms become more complicated because they must check to see whether cell is empty before examining its ...
22,554
arrays of coursefor the baseball playersduplicate numbers should not be allowed keeping track of the players would be hard if more than one wore the same number the array workshop applet lets you select either option when you use new to create new arrayyou're prompted to specify both its size and whether duplicates are...
22,555
deletion will need to be shifted three spaces to see how this operation worksset the applet to dups ok and insert three or four items with the same key then try deleting them table shows the average number of comparisons and moves for the three operationsfirst where no duplicates are allowed and then where they are all...
22,556
arrays creating an array as we noted in "overview,there are two kinds of data in javaprimitive types (such as int and doubleand objects in many programming languages (even object-oriented ones such as ++)arrays are primitive typesbut in java they're treated as objects accordinglyyou must use the new operator to create ...
22,557
if you use an index that' less than or greater than the size of the array less you'll get the array index out of bounds runtime error initialization unless you specify otherwisean array of integers is automatically initialized to when it' created unlike ++this is true even of arrays defined within method (functionsay y...
22,558
listing arrays continued int /loop counter long searchkey/key of item to search for //arr[ /insert items arr[ arr[ arr[ arr[ arr[ arr[ arr[ arr[ arr[ nelems /now items in array //for( = <nelemsj++/display items system out print(arr[ ")system out println("")//searchkey /find item with key for( = <nelemsj++/for each elem...
22,559
in this programwe create an array called arrplace data items (kidsnumbersin itsearch for the item with value (the shortstoplouisa)display all the itemsremove the item with value (freddywho had dentist appointment)and then display the remaining items the output of the program looks like this found the data we're storing...
22,560
arrays we're going to provide gradual introduction to an object-oriented approachusing two steps in the firstwe'll separate the data storage structure (the arrayfrom the rest of the program the remaining part of the program will become user of the structure in the second stepwe'll improve the communication between the ...
22,561
listing continued /end class lowarray ///////////////////////////////////////////////////////////////class lowarrayapp public static void main(string[argslowarray arr/reference arr new lowarray( )/create lowarray object int nelems /number of items in array int /loop variable arr setelem( )arr setelem( )arr setelem( )ar...
22,562
listing arrays continued arr setelem(karr getelem( + )nelems--/decrement size for( = <nelemsj++/display items system out printarr getelem( ")system out println("")/end main(/end class lowarrayapp ///////////////////////////////////////////////////////////////the output from the lowarray java program is similar to that ...
22,563
this point is especially true when class may have many different users typicallya class can be used over and over by different users (or the same userfor different purposes for examplesomeone might use the lowarray class in some other program to store the serial numbers of his traveler' checks the class can handle this...
22,564
arrays array java program the only difference was that it related to setelem(and getelem(instead of the [operator it' not clear that this approach is an improvement also notice that there' no convenient way to display the contents of the array somewhat crudelythe lowarrayapp class simply uses for loop and the getelem(m...
22,565
private data in er (de (let (find (higharra interface figure the higharray interface listing the higharray java program /higharray java /demonstrates array class with high-level interface /to run this programc>java higharrayapp ///////////////////////////////////////////////////////////////class higharray private long[...
22,566
listing arrays continued break/exit loop before end if( =nelems/gone to endreturn false/yescan' find it else return true/nofound it /end find(//public void insert(long value/put element into array [nelemsvalue/insert it nelems++/increment size //public boolean delete(long valueint jfor( = <nelemsj++/look for it ifvalue...
22,567
listing continued int maxsize /array size higharray arr/reference to array arr new higharray(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 int searchkey /search for ite...
22,568
arrays notice how short and simple main(is the details that had to be handled by main(in lowarray java are now handled by higharray class methods in the higharray classthe find(method looks through the array for the item whose key value was passed to it as an argument it returns true or falsedepending on whether it fin...
22,569
why would we want to arrange data in orderone advantage is that we can speed up search times dramatically using binary search start the ordered workshop appletusing the procedure described in you'll see an arrayit' similar to the one in the array workshop appletbut the data is ordered figure shows this applet figure th...
22,570
arrays use the del button to delete an item from the middle of the array deletion works much the same as it did in the array appletshifting items with higher index numbers down to fill in the hole left by the deletion in the ordered arrayhoweverthe deletion algorithm can quit partway through if it doesn' find the itemj...
22,571
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 th...
22,572
arrays figure range in step of the binary search 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 ...
22,573
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 be...
22,574
arrays 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 lowerbound lowerbound upperbound curin upperbound curin lowerbound upperbound curin new range if searchkey< [c...
22,575
listing the orderedarray java program /orderedarray java /demonstrates ordered array class /to run this programc>java orderedapp ///////////////////////////////////////////////////////////////class ordarray private long[ /ref to array private int nelems/number of data items //public ordarray(int max/constructor new lon...
22,576
listing arrays continued public void insert(long value/put element into array int jfor( = <nelemsj++/find where it goes if( [jvalue/(linear searchbreakfor(int =nelemsk>jk--/move bigger ones up [ka[ - ] [jvalue/insert it nelems++/increment size /end insert(//public boolean delete(long valueint find(value)if( ==nelems/ca...
22,577
listing continued arr new ordarray(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 int searchkey /search for item ifarr find(searchkey!arr size(system out println("found searchkey)else system out pr...
22,578
arrays existing ones would probably be infrequent occurrences compared with accessing an existing employee' record for informationor 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 deleti...
22,579
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 findi...
22,580
arrays 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 our original question was the opposite of the one just describedgiven the rangewe want to know how many comparisons are required to complete search that isgiven rwe want an equation tha...
22,581
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 strin...
22,582
arrays the 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...
22,583
listing continued public string getlast(/get last name return lastname/end class person ///////////////////////////////////////////////////////////////class classdataarray private person[ /reference to array private int nelems/number of data items public classdataarray(int max/constructor new person[max]/create the arr...
22,584
listing arrays continued return falseelse /found it for(int =jk<nelemsk++/shift down [ka[ + ]nelems--/decrement size return true/end delete(//public void displaya(/displays array contents for(int = <nelemsj++/for each elementa[jdisplayperson()/display it ///end class classdataarray /////////////////////////////////////...
22,585
listing continued found=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()/display items again /end main(/en...
22,586
arrays the classdataarray java 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 a...
22,587
as with insertionsdiscovering the value of in this equation would require timing search for some (probably largevalue of and then using the resulting value of to calculate when you know kyou can calculate for any other value of for handier formulawe could lump the into the our new is equal to the old divided by now we ...
22,588
arrays 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 ( nu...
22,589
quicklyin ( timebut searching takes slow (ntime in an ordered array you can search quicklyin (logntimebut insertion takes (ntime for both kinds of arraysdeletion takes (ntime because 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--...
22,590
arrays 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 questions these questions are intended as self-test for readers answers...
22,591
ordered arrayscompared with unordered arraysare much quicker at deletion quicker at insertion quicker to create quicker at searching logarithm is the inverse of the base logarithm of , is the maximum number of elements that must be examined to complete binary search in an array of elements is the base logarithm of is t...
22,592
arrays in an array holding an even number of data itemsthere is no middle item which item does the binary search algorithm examine firstuse the ordered workshop applet to find out programming projects writing programs to solve the programming projects helps to solidify your understanding of the material and demonstrate...
22,593
simple sorting in this how would you do itbubble sort selection sort 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 populationcount...
22,594
simple sorting 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...
22,595
computer program isn' able to glance over the data in this way it can compare only two players at one time because 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 mustthereforec...
22,596
simple sorting swap no swap swap swap figure bubble sortthe beginning of the first pass
22,597
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 true becauseas soon as you encounter the tallest kidyou'll end up swapping him (or herevery time you compare two kidsuntil eventually he (or s...
22,598
simple sorting figure the bubblesort workshop applet the run button this workshop applet contains two-speed graphyou can either let it run by itselfor you can single-step through the process to get quick idea what happensclick the run button the algorithm will bubble-sort the bars when it finishesin seconds or sothe ba...
22,599
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 orderas shown in figure and an inverse ordering where the bars are sorted backward this inverse ordering provides an extra challen...