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 programming projects simple sorting how would you do it bubble sort bubble sort on the baseball players the bubblesort workshop applet java code for bubble sort invariants efficiency of the bubble sort selection sort selection sort on the baseball players the selectsort workshop applet java code for selection sort invariant efficiency of the selection sort insertion sort insertion sort on the baseball players the insertsort workshop applet java code for insertion sort invariants in the insertion sort efficiency of the insertion sort sorting objects java code for sorting objects lexicographical comparisons stability comparing the simple sorts summary
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 applet circular queue java code for queue efficiency of queues deques priority queues the priorityq workshop applet java code for priority queue efficiency of priority queues parsing arithmetic expressions postfix notation translating infix to postfix evaluating postfix expressions summary questions experiments programming projects linked lists links references and basic types relationshipnot position vii
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 find(method the delete(method other methods double-ended lists linked-list efficiency abstract data types stack implemented by linked list queue implemented by linked list data types and abstraction adt lists adts as design tool sorted lists java code to insert an item in sorted list the sortedlist java program efficiency of sorted linked lists list insertion sort doubly linked lists traversal insertion deletion the doublylinked java program doubly linked list as basis for deques iterators reference in the list itself an iterator class additional iterator features iterator methods the interiterator java program
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 recursion efficient mathematical induction factorials anagrams recursive binary search recursion replaces the loop divide-and-conquer algorithms the towers of hanoi the towers workshop applet moving subtrees the recursive algorithm the towers java program mergesort merging two sorted arrays sorting by merging the mergesort workshop applet the mergesort java program efficiency of the mergesort eliminating recursion recursion and stacks simulating recursive method what does this prove some interesting recursive applications raising number to power ix
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 efficiency of the shellsort partitioning the partition workshop applet the partition java program the partition algorithm efficiency of the partition algorithm quicksort the quicksort algorithm choosing pivot value the quicksort workshop applet degenerates to ( performance median-of-three partitioning handling small partitions removing recursion efficiency of quicksort radix sort algorithm for the radix sort designing program efficiency of the radix sort summary questions experiments programming projects
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 the tree in java code finding node using the workshop applet to find node java code for finding node tree efficiency inserting node using the workshop applet to insert node java code for inserting node traversing the tree inorder traversal java code for traversing traversing three-node tree traversing with the workshop applet preorder and postorder traversals finding maximum and minimum values deleting node case the node to be deleted has no children case the node to be deleted has one child case the node to be deleted has two children xi
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 programming projects red-black trees our approach to the discussion conceptual top-down insertion balanced and unbalanced trees degenerates to ( balance to the rescue red-black tree characteristics fixing rule violations using the rbtree workshop applet clicking on node the start button the ins button the del button the flip button the rol button the ror button the / button text messages where' the find button experimenting with the workshop applet experiment inserting two red nodes experiment rotations experiment color flips
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 rotations on the way down deletion the efficiency of red-black trees red-black tree implementation other balanced trees summary questions experiments trees and external storage introduction to trees what' in name tree organization searching tree insertion node splits splitting the root splitting on the way down the tree workshop applet the fill button the find button the ins button the zoom button viewing different nodes experiments java code for tree xiii
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 external storage accessing external data sequential ordering -trees indexing complex search criteria sorting external files summary questions experiments programming projects hash tables introduction to hashing employee numbers as keys dictionary hashing collisions open addressing linear probing java code for linear probe hash table quadratic probing double hashing separate chaining the hashchain workshop applet java code for separate chaining
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 introduction to heaps priority queuesheapsand adts weakly ordered removal insertion not really swapped the heap workshop applet the fill button the change button the remove button the insert button java code for heaps insertion removal key change the array size the heap java program expanding the heap array efficiency of heap operations xv
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 vertices and edges to graph the graph class searches depth-first search breadth-first search minimum spanning trees graphn workshop applet java code for the minimum spanning tree the mst java program topological sorting with directed graphs an examplecourse prerequisites directed graphs topological sorting the graphd workshop applet cycles and trees java code connectivity in directed graphs the connectivity table warshall' algorithm implementation of warshall' algorithm summary questions experiments programming projects
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 java code the path java program the all-pairs shortest-path problem efficiency intractable problems the knight' tour the traveling salesman problem hamiltonian cycles summary questions experiments programming projects when to use what general-purpose data structures speed and algorithms libraries arrays linked lists binary search trees balanced trees hash tables comparing the general-purpose storage structures special-purpose data structures stack queue xvii
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 microsystem' software development kit command-line programs setting the path viewing the workshop applets operating the workshop applets running the example programs compiling the example programs editing the source code terminating the example programs multiple class files other development systems further reading data structures and algorithms object-oriented programming languages object-oriented design (oodand software engineering answers to questions overview answers to questions arrays answers to questions
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 questions heaps answers to questions graphs answers to questions weighted graphs answers to questions xix
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 +earlier best-selling titles include assembly language primer for the ibm pc and xt and (back at the beginning of the computer revolutionsoul of cp/
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 editorkurt stephanfound great reviewersmade sure everyone was on the same pagekept the ball rollingand gently but firmly ensured that did what was supposed to do harry henderson provided skilled appraisal of the first draftalong with many valuable suggestions richard wrightjr as technical editorcorrected numerous problems with his keen eye for detail jaime ninoph of the university of new orleansattempted to save me from myself and occasionally succeededbut should bear no responsibility for my approach or coding details susan walton has been staunch and much-appreciated supporter in helping to convey the essence of the project to the non-technical carmela carvajal was invaluable in extending our contacts with the academic world dan scherf not only put the cd-rom togetherbut was tireless in keeping me up to date on rapidly evolving software changes finallycecile kaufman ably shepherded the book through its transition from the editing to the production process acknowledgments to the second edition my thanks to the following people at sams publishing for their competenceeffortand patience in the development of this second edition acquisitions editor carol ackerman and development editor songlin qiu ably guided this edition through the complex production process project editor matt purcell corrected semi-infinite number of grammatical errors and made sure everything made sense tech editor mike kopak reviewed the programs and saved me from several problems last but not leastdan scherfan old friend from previous eraprovides skilled management of my code and applets on the sams web site
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 comments you can email or write me directly to let me know what you did or didn' like about this book--as well as what we can do to make our books better please note that cannot help you with technical problems related to the topic of this book we do have user services grouphoweverwhere will forward specific technical questions related to the book when you writeplease be sure to include this book' title and author as well as your nameemail addressand phone number will carefully review your comments and share them with the author and editors who worked on the book emailfeedback@samspublishing com mailmichael stephens executive editor sams publishing east th street indianapolisin usa for more information about this book or another sams publishing titlevisit our web site at www samspublishing com type the isbn (excluding hyphensor the title of book in the search field to find the page you're looking for
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 and algorithms in java has been augmented to make it easier for the reader and for instructors using it as text in computer science classes besides coverage of additional topicswe've added end-of-questionsexperimentsand programming projects additional topics we've added variety of interesting new topics to the book many provide basis for programming projects these new topics include depth-first-search and game simulations the josephus problem huffman codes for data compression the traveling salesman problem hamiltonian cycles the knight' tour puzzle floyd' algorithm warshall' algorithm - trees
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 intended as self-test for readersto ensure that they have understood the material experiments we include some suggested activities for the reader these experiments often involve using the workshop applets or example programs to examine certain features of an algorithm' operationbut some are pencil-and-paper or "thought experiments programming projects most importantlywe have included at the end of each number (usually fiveof challenging programming projects they cover range of difficulty the easiest are simple variations on the example programs the most challenging are implementations of topics discussed in the text but for which there are no example programs solutions to the programming projects are not provided in this bookbut see the adjacent note note it is expected that the programming projects will be useful for instructors looking for class assignments to this endqualified instructors can obtain suggested solutions to the programming projects in the form of source code and executable code contact the sams web site for information on instructors programs what this book is about this book is about data structures and algorithms as used in computer programming data structures are ways in which data is arranged in your computer' memory (or stored on diskalgorithms are the procedures software program uses to manipulate the data in these structures
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 the for loopused for sequential access to the arrayexecutes simple algorithm for uncomplicated programs with small amounts of datasuch simple approach might be all you need howeverfor programs that handle even moderately large amounts of dataor which solve problems that are slightly out of the ordinarymore sophisticated techniques are necessary simply knowing the syntax of computer language such as java or +isn' enough this book is about what you need to know after you've learned programming language the material we cover here is typically taught in colleges and universities as second-year course in computer scienceafter student has mastered the fundamentals of programming what' different about this book there are dozens of books on data structures and algorithms what' different about this onethree thingsour primary goal in writing this book is to make the topics we cover easy to understand demonstration programs called workshop applets bring to life the topics we covershowing you step by stepwith "moving pictures,how data structures and algorithms work the example code is written in javawhich is easier to understand than cc++or pascalthe languages traditionally used to demonstrate computer science topics let' look at these features in more detail easy to understand typical computer science textbooks are full of theorymathematical formulasand abstruse examples of computer code this bookon the other handconcentrates on simple explanations of techniques that can be applied to real-world problems we avoid complex proofs and heavy math there are lots of figures to augment the text many books on data structures and algorithms include considerable material on software engineering software engineering is body of study concerned with designing and implementing large and complex software projects
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 software engineering in "overview "of coursewe do use an object-oriented approachand we discuss various aspects of object-oriented design as we go alongincluding mini-tutorial on oop in our primary emphasishoweveris on the data structures and algorithms themselves workshop applets from the sams web site you can download demonstration programsin the form of java appletsthat cover the topics we discuss these appletswhich we call workshop appletswill run on most web browsers (see appendix "running the workshop applets and example programs,for more details the workshop applets create graphic images that show you in "slow motionhow an algorithm works for examplein one workshop appleteach time you push buttona bar chart shows you one step in the process of sorting the bars into ascending order the values of variables used in the sorting algorithm are also shownso you can see exactly how the computer code works when executing the algorithm text displayed in the picture explains what' happening another applet models binary tree arrows move up and down the treeso you can follow the steps involved in inserting or deleting node from the tree there are more than workshop appletsat least one for each of the major topics in the book these workshop applets make it far more obvious what data structure really looks likeor what an algorithm is supposed to dothan text description ever could of coursewe provide text description as well the combination of workshop appletsclear textand illustrations should make things easy these workshop applets are standalone graphics-based programs you can use them as learning tool that augments the material in the book note that they're not the same as the example code found in the text of the bookwhich we'll discuss next note the workshop appletsin the form of java class filesare available on the sams web site at search box and click search when the book' title is displayedclick the title to go to page where you can download the applets
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 not only easier to write and to understandbut more secure and less prone to errors as well java is modern object-oriented languagewhich means we can use an objectoriented approach for the programming examples this is importantbecause objectoriented programming (oopoffers compelling advantages over the old-fashioned procedural approachand is quickly supplanting it for serious program development don' be alarmed if you aren' familiar with oop it' not that hard to understandespecially in pointer-free environment such as java we'll explain the basics of oop in note like the workshop appletsthe example programs (both source and executable filescan be downloaded from the sams web site who this book is for this book can be used as text in data structures and algorithms coursetypically taught in the second year of computer science curriculum howeverit is also designed for professional programmers and for anyone else who needs to take the next step up from merely knowing programming language because it' easy to understandit is also appropriate as supplemental text to more formal course what you need to know before you read this book the only prerequisite for using this book is knowledge of some programming language although the example code is written in javayou don' need to know java to follow what' happening java is not hard to understandand we've tried to keep the syntax as general as possibleavoiding baroque or java-specific constructions whenever possible of courseit won' hurt if you're already familiar with java knowing +is essentially just as goodbecause java syntax is based so closely on +the differences are minor as they apply to our example programs (except for the welcome elimination of pointers)and we'll discuss them in
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 free system from sun microsystemswhich we'll discuss in appendix to run the example programsyou can use the ms-dos utility in microsoft windows (called ms-dos promptor similar text-oriented environment if you want to modify the source code for the example programs or write your own programsyou'll need java development system such systems are available commerciallyor you can download an excellent basic system from sun microsystemsas described in appendix how this book is organized this section is intended for teachers and others who want quick overview of the contents of the book it assumes you're already familiar with the topics and terms involved in study of data structures and algorithms the first two are intended to ease the reader into data structures and algorithms as painlessly as possible "overview,presents an overview of the topics to be discussed and introduces small number of terms that will be needed later on for readers unfamiliar with object-oriented programmingit summarizes those aspects of this discipline that will be needed in the balance of the bookand for programmers who know +but not javathe key differences between these languages are reviewed "arrays,focuses on arrays howeverthere are two subtextsthe use of classes to encapsulate data storage structures and the class interface searchinginsertionand deletion in arrays and ordered arrays are covered linear searching and binary searching are explained workshop applets demonstrate these algorithms with unordered and ordered arrays in "simple sorting,we introduce three simple (but slowsorting techniquesthe bubble sortselection sortand insertion sort each is demonstrated by workshop applet "stacks and queues,covers three data structures that can be thought of as abstract data types (adts)the stackqueueand priority queue these structures reappear later in the bookembedded in various algorithms each is demonstrated by workshop applet the concept of adts is discussed
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 examples of recursion are givenincluding the towers of hanoi puzzle and the mergesortwhich are demonstrated by workshop applets "advanced sorting,delves into some advanced sorting techniquesshellsort and quicksort workshop applets demonstrate shellsortpartitioning (the basis of quicksort)and two flavors of quicksort in "binary trees,we begin our exploration of trees this covers the simplest popular tree structureunbalanced binary search trees workshop applet demonstrates insertiondeletionand traversal of such trees "red-black trees,explains red-black treesone of the most efficient balanced trees the workshop applet demonstrates the rotations and color switches necessary to balance the tree in trees and external storage,we cover trees as an example of multiway trees workshop applet shows how they work we also discuss - trees and the relationship of trees to -treeswhich are useful in storing external (diskfiles "hash tables,moves into new fieldhash tables workshop applets demonstrate several approacheslinear and quadratic probingdouble hashingand separate chaining the hash-table approach to organizing external files is discussed in "heaps,we discuss the heapa specialized tree used as an efficient implementation of priority queue "graphs,and "weighted graphs,deal with graphsthe first with unweighted graphs and simple searching algorithmsand the second with weighted graphs and more complex algorithms involving the minimum spanning trees and shortest paths in "when to use what,we summarize the various data structures described in earlier with special attention to which structure is appropriate in given situation appendix "running the workshop applets and example programs,provides details on how to use these two kinds of software it also tells how to use the software development kit from sun microsystemswhich can be used to modify the example programs and develop your own programsand to run the applets and example programs
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 painless as possible ideallyit should even be fun let us know if you think we've succeeded in reaching this idealor if notwhere you think improvements might be made
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 for loops to handle my datasoftware engineering when does it make sense to apply what learn herejava for +programmers java library data structures this attempts to answer these questions we'll also introduce some terms you'll need to know and generally set the stage for the more detailed to follow nextfor those of you who haven' yet been exposed to an object-oriented languagewe'll briefly explain enough about oop to get you started finallyfor +programmers who don' know java we'll point out some of the differences between these languages what are data structures and algorithms good forthe subject of this book is data structures and algorithms data structure is an arrangement of data in computer' memory (or sometimes on diskdata structures include arrayslinked listsstacksbinary treesand hash tablesamong others algorithms manipulate the data in these structures in various wayssuch as searching for particular data item and sorting the data
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 this book' subject matter let' look at them in more detail real-world data storage many of the structures and techniques we'll discuss are concerned with how to handle real-world data storage by real-world datawe mean data that describes physical entities external to the computer as some examplesa personnel record describes an actual human beingan inventory record describes an existing car part or grocery itemand financial transaction record describessayan actual check written to pay the electric bill non-computer example of real-world data storage is stack of -by- index cards these cards can be used for variety of purposes if each card holds person' nameaddressand phone numberthe result is an address book if each card holds the namelocationand value of household possessionthe result is home inventory of courseindex cards are not exactly state-of-the-art almost anything that was once done with index cards can now be done with computer suppose you want to update your old index-card system to computer program you might find yourself with questions like thesehow would you store the data in your computer' memorywould your method work for hundred file cardsa thousanda millionwould your method permit quick insertion of new cards and deletion of old oneswould it allow for fast searching for specified cardsuppose you wanted to arrange the cards in alphabetical order how would you sort themin this bookwe will be discussing data structures that might be used in ways similar to stack of index cards
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 such complex systems requires the application of software engineering techniqueswhich we'll mention toward the end of this programmer' tools not all data storage structures are used to store real-world data typicallyreal-world data is accessed more or less directly by program' user some data storage structureshoweverare not meant to be accessed by the userbut by the program itself programmer uses such structures as tools to facilitate some other operation stacksqueuesand priority queues are often used in this way we'll see examples as we go along real-world modeling some data structures directly model real-world situations the most important data structure of this type is the graph you can use graphs to represent airline routes between cities or connections in an electric circuit or tasks in project we'll cover graphs in "graphs,and "weighted graphs other data structuressuch as stacks and queuesmay also be used in simulations queuefor examplecan model customers waiting in line at bank or cars waiting at toll booth overview of data structures another way to look at data structures is to focus on their strengths and weaknesses in this section we'll provide an overviewin the form of tableof the major data storage structures we'll be discussing in this book this is bird' -eye view of landscape that we'll be covering later at ground levelso don' be alarmed if the terms used are not familiar table shows the advantages and disadvantages of the various data structures described in this book table characteristics of data structures data structure advantages disadvantages array quick insertionvery fast access if index known quicker search than unsorted array slow searchslow deletionfixed size slow insertion and deletionfixed size ordered array
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 balanced similar trees good for disk storage very fast access if key known fast insertion slow access to other items slow access to other items slow search queue linked list binary tree red-black tree tree hash table heap graph fast insertiondeletionaccess to largest item models real-world situations deletion algorithm is complex complex complex slow deletionaccess slow if key not knowninefficient memory usage slow access to other items some algorithms are slow and complex the data structures shown in table except the arrayscan be thought of as abstract data typesor adts we'll describe what this means in "linked lists overview of algorithms many of the algorithms we'll discuss apply directly to specific data structures for most data structuresyou need to know how to insert new data item search for specified item delete specified item
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 concept of recursion is important in designing certain algorithms recursion involves method calling itself we'll look at recursion in "recursion (the term method is used in java in other languagesit is called functionprocedureor subroutine some definitions let' look at few of the terms that we'll be using throughout this book database we'll use the term database to refer to all the data that will be dealt with in particular situation we'll assume that each item in database has similar format as an exampleif you create an address book using index cardsthese cards constitute database the term file is sometimes used in this sense record records are the units into which database is divided they provide format for storing information in the index card analogyeach card represents record record includes all the information about some entityin situation in which there are many such entities record might correspond to person in personnel filea car part in an auto supply inventoryor recipe in cookbook file field record is usually divided into several fields field holds particular kind of data on an index card for an address booka person' nameaddressor telephone number is an individual field more sophisticated database programs use records with more fields figure shows such recordwhere each line represents distinct field in java (and other object-oriented languages)records are usually represented by objects of an appropriate class individual variables within an object represent data fields fields within class object are called fields in java (but members in some other languages such as ++
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 record with specific key for instancein an address book programyou might search in the name field of each record for the key "brown when you find the record with this keyyou can access all its fieldsnot just the key we might say that the key unlocks the entire record you could search through the same file using the phone number field or the address field as the key any of the fields in figure could be used as search key object-oriented programming this section is for those of you who haven' been exposed to object-oriented programming howevercaveat emptor we cannotin few pagesdo justice to all the innovative new ideas associated with oop our goal is merely to make it possible for you to understand the example programs in the text ifafter reading this section and examining some of the example code in the following you still find the whole oop business as alien as quantum physicsyou may need more thorough exposure to oop see the reading list in appendix "further reading,for suggestions problems with procedural languages oop was invented because procedural languagessuch as cpascaland early versions of basicwere found to be inadequate for large and complex programs why was this
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 informationbut most real-world objects do both of these things the thermostat on your furnacefor examplecarries out tasks (turning the furnace on and offbut also stores information (the current temperature and the desired temperatureif you wrote thermostat control program in procedural languageyou might end up with two methodsfurnace_on(and furnace_off()but also two global variablescurrenttemp (supplied by thermometerand desiredtemp (set by the userhoweverthese methods and variables wouldn' form any sort of programming unitthere would be no unit in the program you could call thermostat the only such concept would be in the programmer' mind for large programswhich might contain hundreds of entities like thermostatsthis procedural approach made things chaoticerror-proneand sometimes impossible to implement at all what was needed was better match between things in the program and things in the outside world crude organizational units more subtlebut relatedproblem had to do with program' internal organization procedural programs were organized by dividing the code into methods one difficulty with this kind of method-based organization was that it focused on methods at the expense of data there weren' many options when it came to data to simplify slightlydata could be local to particular methodor it could be global--accessible to all methods there was no way (at least not flexible wayto specify that some methods could access variable and others couldn' this inflexibility caused problems when several methods needed to access the same data to be available to more than one methodsuch variables needed to be globalbut global data could be accessed inadvertently by any method in the program this lead to frequent programming errors what was needed was way to fine-tune data accessibilityallowing data to be available to methods with need to access itbut hiding it from other methods objects in nutshell the idea of objects arose in the programming community as solution to the problems with procedural languages
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 new entitythe objectsolves several problems simultaneously not only does an object in program correspond more closely to an object in the real worldbut it also solves the problem engendered by global data in the procedural model the furnace_on(and furnace_off(methods can access currenttemp and desiredtemp these variables are hidden from methods that are not part of thermostathoweverso they are less likely to be accidentally changed by rogue method classes you might think that the idea of an object would be enough for one programming revolutionbut there' more early onit was realized that you might want to make several objects of the same type maybe you're writing furnace control program for an entire apartment buildingfor exampleand you need several dozen thermostat objects in your program it seems shame to go to the trouble of specifying each one separately thusthe idea of classes was born class is specification-- blueprint--for one or more objects here' how thermostat classfor examplemight look in javaclass thermostat private float currenttemp()private float desiredtemp()public void furnace_on(/method body goes here public void furnace_off(/method body goes here /end class thermostat the java keyword class introduces the class specificationfollowed by the name you want to give the classhere it' thermostat enclosed in curly brackets are the fields and methods that make up the class we've left out the bodies of the methodsnormallyeach would have many lines of program code
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 structure in doesn' create any variables to actually create objects in javayou must use the keyword new at the same time an object is createdyou need to store reference to it in variable of suitable type--that isthe same type as the class what' referencewe'll discuss references in more detail later in the meantimethink of reference as name for an object (it' actually the object' addressbut you don' need to know that here' how we would create two references to type thermostatcreate two new thermostat objectsand store references to them in these variablesthermostat therm therm /create two references therm new thermostat()therm new thermostat()/create two objects and /store references to them incidentallycreating an object is also called instantiating itand an object is often referred to as an instance of class accessing object methods after you specify class and create some objects of that classother parts of your program need to interact with these objects how do they do thattypicallyother parts of the program interact with an object' methodsnot with its data (fieldsfor exampleto tell the therm object to turn on the furnacewe would say therm furnace_on()the dot operator associates an object with one of its methods (or occasionally with one of its fieldsat this point we've covered (rather telegraphicallyseveral of the most important features of oop to summarizeobjects contain both methods and fields (dataa class is specification for any number of objects to create an objectyou use the keyword new in conjunction with the class name to invoke method for particular objectyou use the dot operator
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 generates actual output it features class called bankaccount that models checking account at bank the program creates an account with an opening balancedisplays the balancemakes deposit and withdrawaland then displays the new balance listing shows bank java listing the bank java program /bank java /demonstrates basic oop syntax /to run this programc>java bankapp ///////////////////////////////////////////////////////////////class bankaccount private double balance/account balance public bankaccount(double openingbalance/constructor balance openingbalancepublic void deposit(double amountbalance balance amount/makes deposit public void withdraw(double amountbalance balance amount/makes withdrawal public void display(/displays balance system out println("balance=balance)/end class bankaccount ///////////////////////////////////////////////////////////////
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 class bankapp here' the output from this programbefore transactionsbalance= after transactionsbalance= there are two classes in bank java the first onebankaccountcontains the fields and methods for our bank account we'll examine it in detail in moment the second classbankappplays special role the bankapp class to execute the program in listing from an ms-dos promptyou type java bankapp following the cpromptc:\>java bankapp this command tells the java interpreter to look in the bankapp class for the method called main(every java application must have main(methodexecution of the program starts at the beginning of main()as you can see in listing (you don' need to worry yet about the string[args argument in main(the main(method creates an object of class bankaccountinitialized to value of which is the opening balancewith this statementbankaccount ba new bankaccount( )/create acct
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 terminates the bankaccount class the only data field in the bankaccount class is the amount of money in the accountcalled balance there are three methods the deposit(method adds an amount to the balancewithdrawal(subtracts an amountand display(displays the balance constructors the bankaccount class also features constructorwhich is special method that' called automatically whenever new object is created constructor always has exactly the same name as the classso this one is called bankaccount(this constructor has one argumentwhich is used to set the opening balance when the account is created constructor allows new object to be initialized in convenient way without the constructor in this programyou would have needed an additional call to deposit(to put the opening balance in the account public and private notice the keywords public and private in the bankaccount class these keywords are access modifiers and determine which methods can access method or field the balance field is preceded by private field or method that is private can be accessed only by methods that are part of the same class thusbalance cannot be accessed by statements in main(because main(is not method in bankaccount all the methods in bankaccount have the access modifier publichoweverso they can be accessed by methods in other classes that' why statements in main(can call deposit()withdrawal()and display(data fields in class are typically made private and methods are made public this protects the datait can' be accidentally modified by methods of other classes any outside entity that needs to access data in class must do so using method of the same class data is like queen beekept hidden in the middle of the hivefed and cared for by worker-bee methods
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 additional features for examplea secretary class might be derived from more general employee class and include field called typingspeed that the employee class lacked in javainheritance is also called subclassing the base class may be called the superclassand the extended class may be called the subclass inheritance enables you to easily add features to an existing class and is an important aid in the design of programs with many related classes inheritance thus makes it easy to reuse classes for slightly different purposea key benefit of oop polymorphism involves treating objects of different classes in the same way for polymorphism to workthese different classes must be derived from the same base class in practicepolymorphism usually involves method call that actually executes different methods for objects of different classes for examplea call to display(for secretary object would invoke display method in the secretary classwhile the exact same call for manager object would invoke different display method in the manager class polymorphism simplifies and clarifies program design and coding for those not familiar with theminheritance and polymorphism involve significant additional complexity to keep the focus on data structures and algorithmswe have avoided these features in our example programs inheritance and polymorphism are important and powerful aspects of oop but are not necessary for the explanation of data structures and algorithms software engineering in recent yearsit has become fashionable to begin book on data structures and algorithms with on software engineering we don' follow that approachbut let' briefly examine software engineering and see how it fits into the topics we discuss in this book software engineering is the study of ways to create large and complex computer programsinvolving many programmers it focuses on the overall design of the programs and on the creation of that design from the needs of the end users software engineering is concerned with the life cycle of software projectwhich includes specificationdesignverificationcodingtestingproductionand maintenance
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 algorithmson the other handis nuts-and-bolts discipline concerned with the details of coding and data storage accordinglywe focus on the essentials of data structures and algorithms how do they really workwhat structure or algorithm is best in particular situationwhat do they look like translated into java codeas we notedour intent is to make the material as easy to understand as possible for further readingwe mention some books on software engineering in appendix java for +programmers if you're +programmer who has not yet encountered javayou might want to read this section we'll mention several ways that java differs from +this section is not intended to be primer on java we don' even cover all the differences between +and java we're interested in only few java features that might make it hard for +programmers to figure out what' going on in the example programs no pointers the biggest difference between +and java is that java doesn' use pointers to +programmernot using pointers may at first seem quite amazing how can you get along without pointersthroughout this book we'll use pointer-free code to build complex data structures you'll see that this approach is not only possiblebut actually easier than using +pointers actuallyjava only does away with explicit pointers pointersin the form of memory addressesare still thereunder the surface it' sometimes said thatin javaeverything is pointer this statement is not completely truebut it' close let' look at the details references java treats primitive data types (such as intfloatand doubledifferently than objects look at these two statementsint intvarbankaccount bc /an int variable called intvar /reference to bankaccount object
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 is reference to this objectit' not the object itself actuallybc won' hold reference if it has not been assigned an object at some prior point in the program before being assigned an objectit holds reference to special object called null in the same wayintvar won' hold numerical value if it' never been assigned one the compiler will complain if you try to use variable that has never been assigned value in ++the statement bankaccount bc actually creates an objectit sets aside enough memory to hold all the object' data in javaall this statement creates is place to put an object' memory address you can think of reference as pointer with the syntax of an ordinary variable ( +has reference variablesbut they must be explicitly specified with the symbol assignment it follows that the assignment operator (=operates differently with java objects than with +objects in ++the statement bc bc copies all the data from an object called bc into different object called bc following this statementthere are two objects with the same data in javaon the other handthis same assignment statement copies the memory address that bc refers to into bc both bc and bc now refer to exactly the same objectthey are references to it this can get you into trouble if you're not clear what the assignment operator does following the assignment statement shown abovethe statement bc withdraw( )and the statement bc withdraw( )both withdraw $ from the same bank account object suppose you actually want to copy data from one object to another in this case you must make sure you have two separate objects to begin with and then copy each field separately the equal sign won' do the job
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 actual address of ba so you can' accidentally corrupt it howeveryou probably don' need to know itunless you're planning something wicked how do you release memory that you've acquired from the system with new and no longer needin ++you use delete in javayou don' need to worry about releasing memory java periodically looks through each block of memory that was obtained with new to see if valid references to it still exist if there are no such referencesthe block is returned to the free memory store this process is called garbage collection in +almost every programmer at one time or another forgets to delete memory blockscausing "memory leaksthat consume system resourcesleading to bad performance and even crashing the system memory leaks can' happen in java (or at least hardly everarguments in ++pointers are often used to pass objects to functions to avoid the overhead of copying large object in javaobjects are always passed as references this approach also avoids copying the objectvoid method (bankaccount ba new bankaccount( )method (ba )void method (bankaccount acctin this codethe references ba and acct both refer to the same object in +acct would be separate objectcopied from ba primitive data typeson the other handare always passed by value that isa new variable is created in the method and the value of the argument is copied into it
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 referencesthey work differently with objects the equality operatorwhen applied to objectstells you whether two references are identical--that iswhether they refer to the same objectcarpart cp new carpart("fender")carpart cp cp if(cp =cp system out println("they're identical")in +this operator would tell you if two objects contained the same data if you want to see whether two objects contain the same data in javayou must use the equals(method of the object classcarpart cp new carpart("fender")carpart cp cp ifcp equals(cp system out println("they're equal")this technique works because all objects in java are implicitly derived from the object class overloaded operators this point is easythere are no overloaded operators in java in ++you can redefine +*=and most other operators so that they behave differently for objects of particular class no such redefinition is possible in java use named method insteadsuch as add(or whatever primitive variable types the primitive or built-in variable types in java are shown in table
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 integers for true/false valuesboolean is distinct type in java type char is unsignedand uses two bytes to accommodate the unicode character representation schemewhich can handle international characters the int type varies in size in and ++depending on the specific computer platformin java an int is always bits literals of type float use the suffix (for example )literals of type double need no suffix literals of type long use suffix (as in )literals of the other integer types need no suffix java is more strongly typed than and ++many conversions that were automatic in those languages require an explicit cast in java all types not shown in table such as stringare classes input/output there have been changes to input/output as java has evolved for the console-mode applications we'll be using as example programs in this booksome clunky-looking but effective constructions are available for input and output they're quite different from the workhorse cout and cin approaches in +and printf(and scanf(in older versions of the java software development kit (sdkrequired the line import java io *at the beginning of the source file for all input/output routines now this line is needed only for input
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 next line in older versions of the sdka system out print(statement did not actually write anything to the screen it had to be followed by system out println()or system out flush(statement to display the entire buffer now it displays immediately you can use several variablesseparated by plus signsin the argument suppose in this statement the value of ans is system out println("the answer is ans)then the output will be the answer is inputting string input is considerably more involved than output in generalyou want to read any input as string object if you're actually inputting something elsesay character or numberyou then convert the string object to the desired type as we notedany program that uses input must include the statement import java io *at the beginning of the program without this statementthe compiler will not recognize such entities as ioexception and inputstreamreader string input is fairly baroque here' method that returns string entered by the userpublic static string getstring(throws ioexception inputstreamreader isr new inputstreamreader(system in)bufferedreader br new bufferedreader(isr)string br readline()return
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 preceding code in factyou'll need to add throws ioexception to any methodsuch as main()that calls any of the input methods inputting character suppose you want your program' user to enter character (by enterwe mean typing something and pressing the enter key the user may enter single character or (incorrectlymore than one thereforethe safest way to read character involves reading string and picking off its first character with the charat(methodpublic static char getchar(throws ioexception string getstring()return charat( )the charat(method of the string class returns character at the specified position in the string objecthere we get the first characterwhich is number this approach prevents extraneous characters being left in the input buffer such characters can cause problems with subsequent input inputting integers to read numbersyou make string object as shown before and convert it to the type you want using conversion method here' methodgetint()that converts input into type int and returns itpublic int getint(throws ioexception string getstring()return integer parseint( )the parseint(method of class integer converts the string to type int similar routineparselong()can be used to convert type long in older versions of the sdkyou needed to use the line import java lang integerat the beginning of any program that used parseint()but this convention is no longer necessary
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 should also catch any exceptions and process them appropriately inputting floating-point numbers types float and double can be handled in somewhat the same way as integersbut the conversion process is more complex here' how you read number of type doublepublic int getdouble(throws ioexception string getstring()double adub double valueof( )return adub doublevalue()the string is first converted to an object of type double (uppercase )which is "wrapperclass for type double method of double called doublevalue(then converts the object to type double for type floatthere' an equivalent float classwhich has equivalent valueof(and floatvalue(methods java library data structures the java util package contains data structuressuch as vector (an extensible array)stackdictionaryand hashtable in this book we'll usually ignore these built-in classes we're interested in teaching fundamentalsnot the details of particular implementation howeveroccasionally we'll find some of these structures useful you must use the line import java util *before you can use objects of these classes although we don' focus on themsuch class librarieswhether those that come with java or others available from third-party developerscan offer rich source of versatiledebugged storage classes this book should equip you with the knowledge to know what sort of data structure you need and the fundamentals of how it works then you can decide whether you should write your own classes or use someone else'
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 is usually implemented by class method many of the data structures and algorithms described in this book are most often used to build databases some data structures are used as programmer' toolsthey help execute an algorithm other data structures model real-world situationssuch as telephone lines running between cities database is unit of data storage composed of many similar records record often represents real-world objectsuch as an employee or car part record is divided into fields each field stores one characteristic of the object described by the record key is field in record that' used to carry out some operation on the data for examplepersonnel records might be sorted by lastname field database can be searched for all records whose key field has certain value this value is called search key questions these questions are intended as self-test for readers answers to the questions may be found in appendix in many data structures you can single recorditand it rearranging the contents of data structure into certain order is called
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 real-world object will hold specific values in its fields specifies the type of method in javaa class specification creates objects requires the keyword new creates references none of the above when an object wants to do somethingit uses in javaaccessing an object' methods requires the operator in javaboolean and byte are (there are no experiments or programming projects for
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 introduce arrays in java and demonstrate home-made array class we'll also examine special kind of arraythe ordered arrayin which the data is stored in ascending (or descendingkey order this arrangement makes possible fast way of searching for data itemthe binary search we'll start the with java workshop applet that shows insertionsearchingand deletion in an array then we'll show some sample java code that carries out these same operations later we'll examine ordered arraysagain starting with workshop applet this applet will demonstrate binary search at the end of the we'll talk about big notationthe most widely used measure of algorithm efficiency the array workshop applet suppose you're coaching kids-league baseballand you want to keep track of which players are present at the practice field what you need is an attendance-monitoring program for your laptop-- program that maintains database of the players who have shown up for practice you can use simple data structure to hold this data there are several actions you would like to be able to performinsert player into the data structure when the player arrives at the field in this the basics of arrays in java dividing program into classes class interfaces java code for an ordered array logarithms storing objects big notation why not use arrays for everything
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 book we'll often begin the discussion of particular data structure by demonstrating it with workshop applet this approach will give you feeling for what the structure and its algorithms dobefore we launch into detailed explanation and demonstrate sample code the workshop applet called array shows how an array can be used to implement insertionsearchingand deletion now start up the array workshop appletas described in appendix "running the workshop applets and example programs,with :\>appletviewer array html figure shows the resulting array with elements of which have data items in them you can think of these items as representing your baseball players imagine that each player has been issued team shirt with the player' number on the back to make things visually interestingthe shirts come in variety of colors you can see each player' number and shirt color in the array figure the array workshop applet
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 you want using the fill button fill creates set of items and randomly assigns them numbers and colors the numbers are in the range to you can' create an array of more than cellsand you can'tof coursefill more data items than there are array cells alsowhen you create new arrayyou'll need to decide whether duplicate items will be allowedwe'll return to this question in moment the default value is no duplicatesso the no dups radio button is initially selected to indicate this setting insertion start with the default arrangement of cells and data itemsand the no dups button selected you insert baseball player' number into the array when the player arrives at the practice fieldhaving been dropped off by parent to insert new itempress the ins button once you'll be prompted to enter the value of the itementer key of item to insert type numbersay into the text field in the upper-right corner of the applet (yesit is hard to get three digits on the back of kid' shirt press ins again and the applet will confirm your choicewill insert item with key final press of the button will cause data itemconsisting of this value and random colorto appear in the first empty cell in the array the prompt will say something like inserted item with key at index each button press in workshop applet corresponds to step that an algorithm carries out the more steps requiredthe longer the algorithm takes in the array workshop applet the insertion process is very fastrequiring only single step this is true because new item is always inserted in the first vacant cell in the arrayand the algorithm knows this location because it knows how many items are already in the array the new item is simply inserted in the next available space searching and deletionhoweverare not so fast
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 number of the person you're looking for pick number that appears on an item somewhere in the middle of the array type in the number and repeatedly press the find button at each button pressone step in the algorithm is carried out you'll see the red arrow start at cell and move methodically down the cellsexamining new one each time you press the button the index number in the message checking next cellindex will change as you go along when you reach the specified itemyou'll see the message have found item with key or whatever key value you typed in assuming duplicates are not allowedthe search will terminate as soon as an item with the specified key value is found if you have selected key number that is not in the arraythe applet will examine every occupied cell in the array before telling you that it can' find that item notice that (again assuming duplicates are not allowedthe search algorithm must look through an average of half the data items to find specified item items close to the beginning of the array will be found soonerand those toward the end will be found later if is the number of itemsthe average number of steps needed to find an item is / in the worst-case scenariothe specified item is in the last occupied celland steps will be required to find it as we notedthe time an algorithm takes to execute is proportional to the number of stepsso searching takes much longer on the average ( / stepsthan insertion (one stepdeletion to delete an itemyou must first find it after you type in the number of the item to be deletedrepeated button presses will cause the arrow to movestep by stepdown the array until the item is located the next button press deletes the itemand the cell becomes empty (strictly speakingthis step isn' necessary because we're going to copy over this cell anywaybut deleting the item makes it clearer what' happening
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 contents alsothe algorithms become less efficient because they must waste time looking at unoccupied cells for these reasonsoccupied cells must be arranged contiguouslyno holes allowed thereforeafter locating the specified item and deleting itthe applet must shift the contents of each subsequent cell down one space to fill in the hole figure shows an example item to be deleted figure contents shifted down deleting an item if the item in cell ( in figure is deletedthe item in shifts into the item in shifts into and so on to the last occupied cell during the deletion processwhen the item is locatedthe applet shifts down the contents of the higher-indexed cells as you continue to press the del button deletion requires (assuming no duplicates are allowedsearching through an average of / elements and then moving the remaining elements (an average of / movesto fill up the resulting hole this is steps in all the duplicates issue when you design data storage structureyou need to decide whether items with duplicate keys will be allowed if you're working with personnel file and the key is an employee numberduplicates don' make much sensethere' no point in assigning the same number to two employees on the other handif the key value is last namesthen there' distinct possibility several employees will have the same key valueso duplicates should be allowed
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 permitted use the radio buttons dups ok or no dups to make this selection if you're writing data storage program in which duplicates are not allowedyou may need to guard against human error during an insertion by checking all the data items in the array to ensure that none of them already has the same key value as the item being inserted this check is inefficienthoweverand increases the number of steps required for an insertion from one to for this reasonour applet does not perform this check searching with duplicates allowing duplicates complicates the search algorithmas we noted even if it finds matchit must continue looking for possible additional matches until the last occupied cell at leastthis is one approachyou could also stop after the first match how you proceed depends on whether the question is "find me everyone with blue eyesor "find me someone with blue eyes when the dups ok button is selectedthe applet takes the first approachfinding all items matching the search key this approach always requires steps because the algorithm must go all the way to the last occupied cell insertion with duplicates insertion is the same with duplicates allowed as when they're nota single step inserts the new item but rememberif duplicates are not allowedand there' possibility the user will attempt to input the same key twiceyou may need to check every existing item before doing an insertion deletion with duplicates deletion may be more complicated when duplicates are alloweddepending on exactly how "deletionis defined if it means to delete only the first item with specified valuethenon the averageonly / comparisons and / moves are necessary this is the same as when no duplicates are allowed ifhoweverdeletion means to delete every item with specified key valuethe same operation may require multiple deletions such an operation will require checking cells and (probablymoving more than / cells the average depends on how the duplicates are distributed throughout the array the applet assumes this second meaning and deletes multiple items with the same key this is complicated because each time an item is deletedsubsequent items must be shifted farther for exampleif three items are deletedthen items beyond the last
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 allowed is the number of items in the array inserting new item counts as one move table duplicates ok versus no duplicates no duplicates duplicates ok search insertion / comparisons no comparisonsone move comparisons no comparisonsone move deletion / comparisonsn/ moves comparisonsmore than / moves you can explore these possibilities with the array workshop applet the difference between and / is not usually considered very significantexcept when you're fine-tuning program of more importanceas we'll discuss toward the end of this is whether an operation takes one stepn stepslog(nstepsor steps not too swift one of the significant things to notice when you're using the array applet is the slow and methodical nature of the algorithms with the exception of insertionthe algorithms involve stepping through some or all of the cells in the array different data structures offer much faster (but more complexalgorithms we'll see onethe binary search on an ordered arraylater in this and others throughout this book the basics of arrays in java the preceding section showed graphically the primary algorithms used for arrays now we'll see how to write programs to carry out these algorithmsbut we first want to cover few of the fundamentals of arrays in java if you're java expertyou can skip ahead to the next sectionbut even and +programmers should stick around arrays in java use syntax similar to that in and +(and not that different from other languages)but there are nevertheless some unique aspects to the java approach
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 an arrayint[intarrayintarray new int[ ]/defines reference to an array /creates the arrayand /sets intarray to refer to it or you can use the equivalent single-statement approachint[intarray new int[ ]the [operator is the sign to the compiler we're naming an array object and not an ordinary variable you can also use an alternative syntax for this operatorplacing it after the name instead of the typeint intarray[new int[ ]/alternative syntax howeverplacing the [after the int makes it clear that the [is part of the typenot the name because an array is an objectits name--intarray in the preceding code--is reference to an arrayit' not the array itself the array is stored at an address elsewhere in memoryand intarray holds only this address arrays have length fieldwhich you can use to find the size (the number of elementsof an arrayint arraylength intarray length/find array size as in most programming languagesyou can' change the size of an array after it' been created accessing array elements array elements are accessed using an index number in square brackets this is similar to how other languages worktemp intarray[ ]intarray[ /get contents of fourth element of array /insert into the eighth cell remember that in javaas in and ++the first element is numbered so that the indices in an array of elements run from to
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 you create an array of objects like thisautodata[cararray new autodata[ ]until the array elements are given explicit valuesthey contain the special null object if you attempt to access an array element that contains nullyou'll get the runtime error null pointer assignment the moral is to make sure you assign something to an element before attempting to access it you can initialize an array of primitive type to something besides using this syntaxint[intarray }perhaps surprisinglythis single statement takes the place of both the reference declaration and the use of new to create the array the numbers within the curly brackets are called the initialization list the size of the array is determined by the number of values in this list an array example let' look at some example programs that show how an array can be used we'll start with an old-fashioned procedural version and then show the equivalent objectoriented approach listing shows the old-fashioned versioncalled array java listing the array java program /array java /demonstrates java arrays /to run this programc>java arrayapp ///////////////////////////////////////////////////////////////class arrayapp public static void main(string[argslong[arr/reference to array arr new long[ ]/make array int nelems /number of items
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 elementif(arr[ =searchkey/found itembreak/yesexit before end if( =nelems/at the endsystem out println("can' find searchkey)/yes else system out println("found searchkey)/no //searchkey /delete item with key for( = <nelemsj++/look for it if(arr[ =searchkeybreakfor(int =jk<nelems- ++/move higher ones down arr[karr[ + ]nelems--/decrement size //for( = <nelemsj++/display items system out printarr[ ")system out println("")/end main(/end class arrayapp
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 in this array is type long we use long to make it clearer that this is datatype int is used for index values we've chosen primitive type to simplify the coding generallythe items stored in data structure consist of several fieldsso they are represented by objects rather than primitive types we'll see such an example toward the end of this insertion inserting an item into the array is easywe use the normal array syntaxarr[ we also keep track of how many items we've inserted into the array with the nelems variable searching the searchkey variable holds the value we're looking for to search for an itemwe step through the arraycomparing searchkey with each element if the loop variable reaches the last occupied cell with no match being foundthe value isn' in the array appropriate messages are displayedfound or can' find deletion deletion begins with search for the specified item for simplicitywe assume (perhaps rashlythat the item is present when we find itwe move all the items with higher index values down one element to fill in the "holeleft by the deleted elementand we decrement nelems in real programwe would also take appropriate action if the item to be deleted could not be found display displaying all the elements is straightforwardwe step through the arrayaccessing each one with arr[jand displaying it program organization the organization of array java leaves something to be desired the program has only one classarrayappand this class has only one methodmain(array java is essentially an old-fashioned procedural program let' see if we can make it easier to understand (among other benefitsby making it more object oriented
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 storage structure and its user dividing program into classes the array java program in listing essentially consists of one big method we can reap many benefits by dividing the program into classes what classesthe data storage structure itself is one candidateand the part of the program that uses this data structure is another by dividing the program into these two classeswe can clarify the functionality of the programmaking it easier to design and understand (and in real programs to modify and maintainin array java we used an array as data storage structurebut we treated it simply as language element now we'll encapsulate the array in classcalled lowarray we'll also provide class methods by which objects of other classes (the lowarrayapp class in this casecan access the array these methods allow communication between lowarray and lowarrayapp our first design of the lowarray class won' be entirely successfulbut it will demonstrate the need for better approach the lowarray java program in listing shows how it looks listing the lowarray java program /lowarray java /demonstrates array class with low-level interface /to run this programc>java lowarrayapp ///////////////////////////////////////////////////////////////class lowarray private long[ /ref to array //public lowarray(int size/constructor new long[size]/create array //public void setelem(int indexlong value/set value [indexvalue//public long getelem(int index/get value return [index]/
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( )arr setelem( )arr setelem( )arr setelem( )arr setelem( )arr setelem( )arr setelem( )arr setelem( )nelems /insert items /now items in array for( = <nelemsj++/display items system out print(arr getelem( ")system out println("")int searchkey /search for data item for( = <nelemsj++/for each elementif(arr getelem( =searchkey/found itembreakif( =nelems/no system out println("can' find searchkey)else /yes system out println("found searchkey)for( = <nelemsj++if(arr getelem( = breakfor(int =jk<nelemsk++/delete value /look for it /higher ones down
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 from array javaexcept that we try to find non-existent key value ( before deleting the item with the key value can' find classes lowarray and lowarrayapp in lowarray javawe essentially wrap the class lowarray around an ordinary java array the array is hidden from the outside world inside the classit' privateso only lowarray class methods can access it there are three lowarray methodssetelem(and getelem()which insert and retrieve an elementrespectivelyand constructorwhich creates an empty array of specified size another classlowarrayappcreates an object of the lowarray class and uses it to store and manipulate data think of lowarray as tool and lowarrayapp as user of the tool we've divided the program into two classes with clearly defined roles this is valuable first step in making program object oriented class used to store data objectsas is lowarray in the lowarray java programis sometimes called container class typicallya container class not only stores the data but also provides methods for accessing the data and perhaps also sorting it and performing other complex actions on it class interfaces we've seen how program can be divided into separate classes how do these classes interact with each othercommunication between classes and the division of responsibility between them are important aspects of object-oriented programming
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 task just as well as it can store the numbers of baseball players if class is used by many different programmersthe class should be designed so that it' easy to use the way that class user relates to the class is called the class interface because class fields are typically privatewhen we talk about the interfacewe usually mean the class methods--what they do and what their arguments are by calling these methodsa class user interacts with an object of the class one of the important advantages conferred by object-oriented programming is that class interface can be designed to be as convenient and efficient as possible figure is fanciful interpretation of the lowarray interface private data lem ete (te ge lem lowarra interface figure the lowarray interface not so convenient the interface to the lowarray class in lowarray java is not particularly convenient the methods setelem(and getelem(operate on low conceptual levelperforming exactly the same tasks as the [operator in an ordinary java array the class userrepresented by the main(method in the lowarrayapp classends up having to carry out the same low-level operations it did in the non-class version of an array in the
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(method for this purpose we could avoid repeated code by writing separate method for lowarrayapp that it could call to display the array contentsbut is it really the responsibility of the lowarrayapp class to provide this methodthuslowarray java demonstrates how to divide program into classesbut it really doesn' buy us too much in practical terms let' see how to redistribute responsibilities between the classes to obtain more of the advantages of oop who' responsible for whatin the lowarray java programthe main()routine in the lowarrayapp classthe user of the data storage structuremust keep track of the indices to the array for some users of an arraywho need random access to array elements and don' mind keeping track of the index numbersthis arrangement might make sense for examplesorting an arrayas we'll see in the next can make efficient use of this direct hands-on approach in typical programhoweverthe user of the data storage device won' find access to the array indices to be helpful or relevant the higharray java example out next example program shows an improved interface for the storage structure classcalled higharray using this interfacethe class user (the higharrayapp classno longer needs to think about index numbers the setelem(and getelem(methods are gonethey're replaced by insert()find()and delete(these new methods don' require an index number as an argument because the class takes responsibility for handling index numbers the user of the class (higharrayappis free to concentrate on the what instead of the how--what' going to be inserteddeletedand accessedinstead of exactly how these activities are carried out figure shows the higharray interfaceand listing shows the higharray java program
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[ /ref to array private int nelems/number of data items //public higharray(int max/constructor new long[max]/create the array nelems /no items yet //public boolean find(long searchkey/find specified value int jfor( = <nelemsj++/for each elementif( [ =searchkey/found item
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 = [jbreakif( ==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 higharray ///////////////////////////////////////////////////////////////class higharrayapp public static void main(string[args
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 item ifarr find(searchkeysystem out println("found searchkey)else system out println("can' find searchkey)arr delete( )arr delete( )arr delete( )/delete items arr display()/display items again /end main(/end class higharrayapp ///////////////////////////////////////////////////////////////the higharray class is now wrapped around the array in main()we create an array of this class and carry out almost the same operations as in the lowarray java programwe insert itemssearch for an item--one that isn' there--and display the array contents because deleting is so easywe delete items ( and instead of and finally display the contents again here' the output can' find
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 finds the item the insert(method places new data item in the next available space in the array field called nelems keeps track of the number of array cells that are actually filled with data items the main(method no longer needs to worry about how many items are in the array the delete(method searches for the element whose key value was passed to it as an argument andwhen it finds that elementshifts all the elements in higher index cells down one cellthus writing over the deleted valueit then decrements nelems we've also included display(methodwhich displays all the values stored in the array the user' life made easier in lowarray java (listing )the code in main(to search for an item required eight linesin higharray javait requires only one the class userthe higharrayapp classneed not worry about index numbers or any other array details amazinglythe class user doesn' even need to know what kind of data structure the higharray class is using to store the data the structure is hidden behind the interface in factin the next sectionwe'll see the same interface used with somewhat different data structure abstraction the process of separating the how from the what--how an operation is performed inside classas opposed to what' visible to the class user--is called abstraction abstraction is an important aspect of software engineering by abstracting class functionalitywe make it easier to design program because we don' need to think about implementation details at too early stage in the design process the ordered workshop applet imagine an array in which the data items are arranged in order of ascending key values--that iswith the smallest value at index and each cell holding value larger than the cell below such an array is called an ordered array when we insert an item into this arraythe correct location must be found for the insertionjust above smaller value and just below larger one then all the larger values must be moved up to make room
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 the ordered workshop applet in the ordered array we've chosen not to allow duplicates as we saw earlierthis decision speeds up searching somewhat but slows down insertion linear search two search algorithms are available for the ordered workshop appletlinear and binary linear search is the default linear searches operate in much the same way as the searches in the unordered array in the array appletthe red arrow steps alonglooking for match the difference is that in the ordered arraythe search quits if an item with larger key is found try out linear search make sure the linear radio button is selected then use the find button to search for non-existent value thatif it were presentwould fit somewhere in the middle of the array in figure this number might be you'll see that the search terminates when the first item larger than is reachedit' in the figure the algorithm knows there' no point looking further try out the ins and del buttons as well use ins to insert an item with key value that will go somewhere in the middle of the existing items you'll see that insertion requires moving all the items with key values larger than the item being inserted
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 itemjust as the search routine can binary search the payoff for using an ordered array comes when we use binary search this kind of search is much faster than linear searchespecially for large arrays the guess- -number game binary search uses the same approach you did as kid (if you were smartto guess number in the well-known children' guessing game in this gamea friend asks you to guess number she' thinking of between and when you guess numbershe'll tell you one of three thingsyour guess is larger than the number she' thinking ofit' smalleror you guessed correctly to find the number in the fewest guessesyou should always start by guessing if your friend says your guess is too lowyou deduce the number is between and so your next guess should be (halfway between and if she says it' too highyou deduce the number is between and so your next guess should be each guess allows you to divide the range of possible values in half finallythe range is only one number longand that' the answer notice how few guesses are required to find the number if you used linear searchguessing first then then and so onfinding the number would take youon the average guesses in binary search each guess divides the range of possible values in halfso the number of guesses required is far fewer table shows game session when the number to be guessed is table guessing number step number number guessed result too high too low too high too low too high too low correct range of possible values - - - - - - -
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 the ordered workshop appletyou must use the new button to create new array after the first pressyou'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 when the array is filledpick one of the values in the array and see how you can use the find button 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 figure initial range in the binary search at each press of the find buttonthe range is halved and new guess is chosen in the middle of the range figure shows the next step in the process
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 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 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 the method looks like thispublic int find(long searchkeyint lowerbound int upperbound nelems-
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 begins by setting the lowerbound and upperbound variables to the first and last occupied cells in the array setting these variables specifies the range where the item we're looking forsearchkeymay be found thenwithin the while loopthe current indexcurinis set to the middle of this range 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 itemso we return with its indexcurin each time through the loop we divide the range in half eventuallythe range will get so small that 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 upperboundthe 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 index because 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 enoughwe'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 largerwe know we should look in the upper half of the range accordinglywe move lowerbound up to curin actuallywe move it one cell beyond curin because we've already checked curin itself at the beginning of the loop
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< [curinfigure new range if searchkey> [curindividing the range in binary search the ordarray class in generalthe orderedarray java program is similar to higharray java (listing 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 operation 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 the ordarray class includes new size(methodwhich returns the number of data items currently in the array this information 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
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 long[max]/create array nelems //public int size(return nelems//public int find(long 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(/
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/can' find it return falseelse /found it for(int =jk<nelemsk++/move bigger 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
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 println("can' find searchkey)arr display()/display items arr delete( )arr delete( )arr delete( )/delete items arr display()/display items again /end main(/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 longer because all the data items with higher key value must be moved up to make room deletions are slow in both ordered and unordered arrays because 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
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 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 long hard look at table we've seen that binary search provides significant speed increase over linear search in the number-guessing gamewith range from to maximum of seven guesses is needed to identify any number using binary searchjust as in an array of recordsseven comparisons are needed 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 range 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 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
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 finding the number of comparisons you might wonder if you could also find the number using simple equation of coursethere is such an equationand 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 the numbers in table leave out some interesting data they don' answer such questions aswhat is the exact size of the maximum range that can be searched in five stepsto solve this problemwe 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 seven 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 steps don' produce range quite big enough ( )while steps cover it handily ( thusthe 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 power 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
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 that gives us the inverse of raising something to power is called logarithm here' the formula we wantexpressed with logarithms log (rthis equation 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 it 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 true 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 long in our data structures storing such variables simplifies the program examplesbut it' not representative 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 would store the name of the country that issued the stampits catalog numberconditioncurrent valueand so on
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 string firstnameprivate int age//public person(string laststring firstint /constructor lastname lastfirstname firstage //public void displayperson(system out print(last namelastname)system out print("first namefirstname)system out println("ageage)//public string getlast(/get last name return lastname/end class person 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 (listing that stored items of type long only few changes are necessary to adapt that program to handle person objects here are the major changes
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 creates new person object and inserts it in the arrayinstead of inserting long value the main(method has been modified slightlymostly to handle the increased quantity of output we still insert itemsdisplay themsearch for itemdelete itemsand display them all again listing shows the complete classdataarray java program listing the classdataarray java program /classdataarray java /data items as class objects /to run this programc>java classdataapp ///////////////////////////////////////////////////////////////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)/
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 array nelems /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 else return [ ]/nofound it /end find(///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
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 ///////////////////////////////////////////////////////////////class classdataapp public static void main(string[argsint maxsize /array size classdataarray arr/reference to array arr new classdataarray(maxsize)/create the array /insert items 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"person found/search for item
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(/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 last namestimsonfirst namehenryage last namevelasquezfirst namejoseage last namelamarquefirst namehenryage last namevangfirst nameminhage
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 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 onotation 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 tells how an algorithm' speed is 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 insertion 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 preceding equation 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= * /
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 have = * this equation says that average linear search times are proportional to the size of the array if an array is twice as bigsearching it will take twice as long 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 the formulas just describedbut it dispenses with the constant when comparing algorithmsyou 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 summarizes the running times of the algorithms we've discussed so far table running times in big notation algorithm running time in big notation linear search binary search insertion in unordered array insertion in ordered array deletion in unordered array deletion in ordered array (no(log no( (no(no(
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 ( number of steps ( (log ( number of items (nfigure graph of big times the idea in big notation isn' to give actual figures for running times but 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 everythingarrays seem to get the job doneso why not use them for all data storagewe've already seen some of their disadvantages in an unordered array you can insert items
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--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 they are first created with new usuallywhen the program first startsyou don' know exactly how many items will be placed in the array laterso 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 you might want to try creating your own vector class if the class user is about to overflow 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 this whole process 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 is composed of 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
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 may be found in appendix inserting an item into an unordered array takes time proportional to the size of the array requires multiple comparisons requires shifting other items to make room takes the same time no matter how many items there are true or falsewhen you delete an item from an unordered arrayin most cases you shift other items to fill in the gap in an unordered arrayallowing duplicates increases times for all operations increases search times in some situations always increases insertion times sometimes decreases insertion times true or falsein an unordered arrayit' generally faster to find out an item is not in the array than to find out it is creating an array in java requires using the keyword if class is going to use class for somethingthen class ' methods should be easy to understand it' preferable if class communicates with the program' user the more complex operations should be placed in class the more work that class can dothe better when class is using class for somethingthe methods and fields class can access in class are called class '
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 true or falsethe base logarithm of is big notation tells how the speed of an algorithm relates to the number of items the running time of an algorithm for given size data structure the running time of an algorithm for given number of items how the size of data structure relates to the number of items ( means process operates in time either variables of primitive types or can be placed in an array experiments carrying out these experiments will help to provide insights into the topics covered in the no programming is involved use the array workshop applet to insertsearch forand delete items make sure you can predict what it' going to do do this both when duplicates are allowed and when they're not make sure you can predict in advance what range the ordered workshop applet will select at each step
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 demonstrates how the concepts are applied (as noted in the introductionqualified instructors may obtain completed solutions to the programming projects on the publisher' web site to the higharray class in the higharray java program (listing )add method called getmax(that returns the value of the highest key in the arrayor - if the array is empty add some code in main(to exercise this method you can assume all the keys are positive numbers modify the method in programming project so that the item with the highest key is not only returned by the methodbut also removed from the array call the method removemax( the removemax(method in programming project suggests way to sort the contents of an array by key value implement sorting scheme that does not require modifying the higharray classbut only the code in main(you'll need second arraywhich will end up inversely sorted (this scheme is rather crude variant of the selection sort in "simple sorting " modify the orderedarray java program (listing so that the insert(and delete(routinesas well as find()use binary searchas suggested in the text add merge(method to the ordarray class in the orderedarray java program (listing so that you can merge two ordered source arrays into an ordered destination array write code in main(that inserts some random numbers into the two source arraysinvokes merge()and displays the contents of the resulting destination array the source arrays may hold different numbers of data items in your algorithm you will need to compare the keys of the source arrayspicking the smallest one to copy to the destination you'll also need to handle the situation when one source array exhausts its contents before the other write nodups(method for the higharray class of the higharray java program (listing this method should remove all duplicates from the array that isif three items with the key appear in the arraynodups(should remove two of them don' worry about maintaining the order of the items one approach is to first compare every item with all the other items and overwrite any duplicates with null (or distinctive value that isn' used for real keysthen remove all the nulls of coursethe array size will be reduced
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 populationcountries by gnpstars by magnitudeand so on sorting data may also be preliminary step to searching it as we saw in "arrays, binary searchwhich can be applied only to sorted datais much faster than linear search because sorting is so important and potentially so timeconsumingit 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 sortfor exampleis preferable to quicksort for small files and for almost-sorted files in factan insertion sort is commonly used as part of quicksort implementation the example programs in this build on the array classes we developed in the preceding the sorting algorithms are implemented as methods of similar array classes insertion sort sorting objects comparing the simple sorts
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 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 leftfor the team picture how would you go about this sorting processfigure the unordered baseball team as human beingyou have advantages over computer program you can see all the kids at onceand you can pick out the tallest kid almost instantly you 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 figure the ordered baseball team
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 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 itemsor copy one item howevereach algorithm handles the details in different way bubble sort the bubble sort is notoriously slowbut it' conceptually the simplest of the sorting algorithms and for that reason is good beginning for our exploration of sorting techniques bubble sort on the baseball players imagine that you're near-sighted (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 thisyou 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 sorting process 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
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 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 sorted figure bubble sortthe end of the 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 againyou 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 describing this process is much harder than demonstrating itso 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
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 bars will be sortedas shown in figure figure after the bubble sort
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 challenge for many sorting algorithms the step button the real payoff for using the bubblesort workshop applet comes when you singlestep through sort you can 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 appropriate these arrows correspond to the two players you comparedand possibly swappedin the baseball scenario message under the arrows tells you whether the contents of inner and inner+ will 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 barsunless 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 previously 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