Algorithms
F O U R T H E D I T I O N
Algorithms
Robert Sedgewick
and
Kevin Wayne
Princeton University
Upper Saddle River, NJ
•
Boston • Indianapolis • San Francisco New York • Toronto • Montreal • London • Munich • Paris • MadridCapetown • Sydney • Tokyo • Singapore • Mexico City
F O U R T H E D I T I O N
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and the publisher was aware of a trademark claim, the designations have been printed with initial capital letters or in all capitals.
The authors and publisher have taken care in the preparation of this book, but make no expressed or im-plied warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for incidental or consequential damages in connection with or arising out of the use of the information or programs contained herein.
For information about buying this title in bulk quantities, or for special sales opportunities (which may include electronic versions; custom cover designs; and content particular to your business, training goals, marketing focus, or branding interests), please contact our corporate sales department at (800) 382-3419 or corpsales@pearsoned.com.
For government sales inquiries, please contact governmentsales@pearsoned.com.
For questions about sales outside the United States, please contact international@pearsoned.com.
Visit us on the Web: informit.com/aw Copyright © 2014 Pearson Education, Inc.
All rights reserved. Printed in the United States of America. This publication is protected by copyright, and permission must be obtained from the publisher prior to any prohibited reproduction, storage in a retriev-al system, or transmission in any form or by any means, electronic, mechanicretriev-al, photocopying, recording, or likewise. To obtain permission to use material from this work, please submit a written request to Pearson Education, Inc., Permissions Department, One Lake Street, Upper Saddle River, New Jersey 07458, or you may fax your request to (201) 236-3290.
ISBN-13: 978-0-13-379869-2 ISBN-10: 0-13-379869-0
______________________________
To Adam, Andrew, Brett, Robbie
and especially Linda
______________________________
___________________
Note: This is an online edition of Chapters 1 through 3 of Algorithms, Fourth Edition, which con-tains the content covered in our online course Algorithms, Part I.
Preface . . . ix
1. Fundamentals . . . . 3
1.1 Basic Programming Model 8
Primitive data types • Loops and conditionals • Arrays • Static methods • Recursion • APIs • Strings • Input and output • Binary search
1.2 Data Abstraction 64
Objects • Abstract data types • Implementing ADTs • Designing ADTs
1.3 Bags, Queues, and Stacks 120
APIs • Arithmetic expression evaluation • Resizing arrays • Generics • Iterators • Linked lists
1.4 Analysis of Algorithms 172
Running time • Computational experiments • Tilde notation • Order-of-growth classifications • Amortized analysis • Memory usage
1.5 Case Study: Union-Find 216
2. Sorting . . . . 243
2.1 Elementary Sorts 244
Rules of the game • Selection sort • Insertion sort • Shellsort
2.2 Mergesort 270
Abstract in-place merge • Top-down mergesort • Bottom-up mergesort • N lg N lower bound for sorting
2.3 Quicksort 288
In-place partitioning • Randomized quicksort • 3-way partitioning
2.4 Priority Queues 308
Priority queue API • Elementary implementations • Binary heap • Heapsort
2.5 Applications 336
Comparators • Stability • Median and order statistics
3. Searching . . . . 361
3.1 Symbol Tables 362
Symbol table API • Ordered symbol table API • Dedup • Frequency counter • Sequential search • Binary search
3.2 Binary Search Trees 396
Basic implementation • Order-based methods • Deletion
3.3 Balanced Search Trees 424
2-3 search trees • Red-black BSTs • Deletion
3.4 Hash Tables 458
Hash functions • Separate chaining • Linear probing
3.5 Applications 486
Set data type • Whitelist and blacklist filters • Dictionary lookup • Inverted index • File indexing • Sparse matrix-vector multiplication
Chapters 4 through 6, which correspond to our online course Algorithms, Part II, are available as Algorithms, Fourth Edition, Part II.
ix
T
his book is intended to survey the most important computer algorithms in use today, and to teach fundamental techniques to the growing number of people in need of knowing them. It is intended for use as a textbook for a second course in computer science, after students have acquired basic programming skills and familiarity with computer systems. The book also may be useful for self-study or as a reference for people engaged in the development of computer systems or applications programs, since it contains implemen-tations of useful algorithms and detailed information on performance characteristics and clients. The broad perspective taken makes the book an appropriate introduction to the field.T H E S T U DY O F A LG O R I T H M S A N D DATA S T RU C T U R E S is fundamental to any computer-science
curriculum, but it is not just for programmers and computer-science students. Everyone who uses a computer wants it to run faster or to solve larger problems. The algorithms in this book represent a body of knowledge developed over the last 50 years that has become indispens-able. From N-body simulation problems in physics to genetic-sequencing problems in mo-lecular biology, the basic methods described here have become essential in scientific research; from architectural modeling systems to aircraft simulation, they have become essential tools in engineering; and from database systems to internet search engines, they have become es-sential parts of modern software systems. And these are but a few examples—as the scope of computer applications continues to grow, so grows the impact of the basic methods covered here.
In Chapter 1, we develop our fundamental approach to studying algorithms, includ-ing coverage of data types for stacks, queues, and other low-level abstractions that we use throughout the book. In Chapters 2 and 3, we survey fundamental algorithms for sorting and searching; and in Chapters 4 and 5, we cover algorithms for processing graphs and strings. Chapter 6 is an overview placing the rest of the material in the book in a larger context.
x
Distinctive features
The orientation of the book is to study algorithms likely to be of practical use. The book teaches a broad variety of algorithms and data structures and pro-vides sufficient information about them that readers can confidently implement, debug, and put them to work in any computational environment. The approach involves:Algorithms. Our descriptions of algorithms are based on complete implementations and on
a discussion of the operations of these programs on a consistent set of examples. Instead of presenting pseudo-code, we work with real code, so that the programs can quickly be put to practical use. Our programs are written in Java, but in a style such that most of our code can be reused to develop implementations in other modern programming languages.
Data types. We use a modern programming style based on data abstraction, so that
algo-rithms and their data structures are encapsulated together.
Applications. Each chapter has a detailed description of applications where the algorithms
described play a critical role. These range from applications in physics and molecular biology, to engineering computers and systems, to familiar tasks such as data compression and search-ing on the web.
A scientific approach. We emphasize developing mathematical models for describing the
performance of algorithms, using the models to develop hypotheses about performance, and then testing the hypotheses by running the algorithms in realistic contexts.
Breadth of coverage. We cover basic abstract data types, sorting algorithms, searching
al-gorithms, graph processing, and string processing. We keep the material in algorithmic con-text, describing data structures, algorithm design paradigms, reduction, and problem-solving models. We cover classic methods that have been taught since the 1960s and new methods that have been invented in recent years.
xi
Booksite
An important feature of the book is its relationship to the online booksite algs4.cs.princeton.edu. This site is freely available and contains an extensive amount of material about algorithms and data structures, for teachers, students, and practitioners, in-cluding:An online synopsis. The text is summarized in the booksite to give it the same overall
struc-ture as the book, but linked so as to provide easy navigation through the material.
Full implementations. All code in the book is available on the booksite, in a form suitable for
program development. Many other implementations are also available, including advanced implementations and improvements described in the book, answers to selected exercises, and client code for various applications. The emphasis is on testing algorithms in the context of meaningful applications.
Exercises and answers. The booksite expands on the exercises in the book by adding drill
exercises (with answers available with a click), a wide variety of examples illustrating the reach of the material, programming exercises with code solutions, and challenging problems.
Dynamic visualizations. Dynamic simulations are impossible in a printed book, but the
website is replete with implementations that use a graphics class to present compelling visual demonstrations of algorithm applications.
Course materials. A complete set of lecture slides is tied directly to the material in the book
and on the booksite. A full selection of programming assignments, with check lists, test data, and preparatory material, is also included.
Online course. A full set of lecture videos and self-assessment materials provide
opportuni-ties for students to learn or review the material on their own and for instructors to replace or supplement their lectures.
Links to related material. Hundreds of links lead students to background information about
applications and to resources for studying algorithms.
xii
Use in the curriculum
The book is intended as a textbook in a second course in com-puter science. It provides full coverage of core material and is an excellent vehicle for stu-dents to gain experience and maturity in programming, quantitative reasoning, and problem-solving. Typically, one course in computer science will suffice as a prerequisite—the book is intended for anyone conversant with a modern programming language and with the basic features of modern computer systems.The algorithms and data structures are expressed in Java, but in a style accessible to people fluent in other modern languages. We embrace modern Java abstractions (including generics) but resist dependence upon esoteric features of the language.
Most of the mathematical material supporting the analytic results is self-contained (or is labeled as beyond the scope of this book), so little specific preparation in mathematics is required for the bulk of the book, although mathematical maturity is definitely helpful. Ap-plications are drawn from introductory material in the sciences, again self-contained.
The material covered is a fundamental background for any student intending to major in computer science, electrical engineering, or operations research, and is valuable for any student with interests in science, mathematics, or engineering.
Context
The book is intended to follow our introductory text, An Introduction to Pro-gramming in Java: An Interdisciplinary Approach, which is a broad introduction to the field. Together, these two books can support a two- or three-semester introduction to computer sci-ence that will give any student the requisite background to successfully address computation in any chosen field of study in science, engineering, or the social sciences.xiii
Acknowledgments
This book has been nearly 40 years in the making, so full recogni-tion of all the people who have made it possible is simply not feasible. Earlier edirecogni-tions of this book list dozens of names, including (in alphabetical order) Andrew Appel, Trina Avery, Marc Brown, Lyn Dupré, Philippe Flajolet, Tom Freeman, Dave Hanson, Janet Incerpi, Mike Schid-lowsky, Steve Summit, and Chris Van Wyk. All of these people deserve acknowledgement, even though some of their contributions may have happened decades ago. For this fourth edition, we are grateful to the hundreds of students at Princeton and several other institutions who have suffered through preliminary versions of the work, and to readers around the world for sending in comments and corrections through the booksite.We are grateful for the support of Princeton University in its unwavering commitment to excellence in teaching and learning, which has provided the basis for the development of this work.
Peter Gordon has provided wise counsel throughout the evolution of this work almost from the beginning, including a gentle introduction of the “back to the basics” idea that is the foundation of this edition. For this fourth edition, we are grateful to Barbara Wood for her careful and professional copyediting, to Julie Nahil for managing the production, and to many others at Pearson for their roles in producing and marketing the book. All were ex-tremely responsive to the demands of a rather tight schedule without the slightest sacrifice to the quality of the result.
Robert Sedgewick Kevin Wayne
1.1 Basic Programming Model 8
1.2 Data Abstraction 64
1.3 Bags, Queues, and Stacks 120
1.4 Analysis of Algorithms 172
1.5 Case Study: Union-Find 216
one
T
heobjectiveofthisbookistostudyabroadvarietyofimportantanduseful algorithms—methodsforsolvingproblemsthataresuitedforcomputerimple -mentation.Algorithmsgohandinhandwithdata structures—schemesforor -ganizingdatathatleavethemamenabletoefficientprocessingbyanalgorithm.This chapterintroducesthebasictoolsthatweneedtostudyalgorithmsanddatastructures. First,weintroduceourbasic programming model.Allofourprogramsareimple -mentedusingasmallsubsetoftheJavaprogramminglanguageplusafewofourown librariesforinput/outputandforstatisticalcalculations.Section 1.1isasummaryof languageconstructs,features,andlibrariesthatweuseinthisbook.Next,weemphasizedata abstraction,wherewedefineabstract data types(ADTs)in theserviceofmodularprogramming.InSection 1.2weintroducetheprocessofim -plementinganADTinJava,byspecifyinganapplications programming interface(API) andthenusingtheJavaclassmechanismtodevelopanimplementationforuseinclient code.
Asimportantandusefulexamples,wenextconsiderthreefundamentalADTs:the bag,thequeue,andthestack.Section 1.3describesAPIsandimplementationsofbags, queues,andstacksusingarrays,resizingarrays,andlinkedliststhatserveasmodelsand startingpointsforalgorithmimplementationsthroughoutthebook.
Performanceisacentralconsiderationinthestudyofalgorithms.Section 1.4 de-scribesourapproachtoanalyzingalgorithmperformance.Thebasisofourapproachis thescientificmethod:wedevelophypothesesaboutperformance,createmathematical models,andrunexperimentstotestthem,repeatingtheprocessasnecessary.
Algorithms
Whenwewriteacomputerprogram,wearegenerallyimplementinga methodthathasbeendevisedpreviouslytosolvesomeproblem.Thismethodisoften independent of the particular programming language being used—it is likely to be equallyappropriateformanycomputersandmanyprogramminglanguages.Itisthe method,ratherthanthecomputerprogramitself,thatspecifiesthestepsthatwecan taketosolvetheproblem.Thetermalgorithmisusedincomputersciencetodescribe afinite,deterministic,andeffectiveproblem-solvingmethodsuitableforimplementa -tion as a computer program.Algorithms are the stuff of computer science: they are centralobjectsofstudyinthefield.Wecandefineanalgorithmbydescribingaprocedureforsolvingaproblemina naturallanguage,orbywritingacomputerprogramthatimplementstheprocedure, as shown at right forEuclid’s algorithm for finding the greatest common divisor of twonumbers,avariantofwhichwasdevised
over2,300yearsago.Ifyouarenotfamiliar with Euclid’s algorithm, you are encour -aged to work Exercise 1.1.24 and Exercise 1.1.25,perhapsafterreadingSection 1.1.In thisbook,weusecomputerprogramstode -scribealgorithms.Oneimportantreasonfor doing so is that it makes easier the task of checkingwhethertheyarefinite,determin -istic,andeffective,asrequired.Butitisalso importanttorecognizethataprogramina particularlanguageisjustonewaytoexpress analgorithm.Thefactthatmanyoftheal -gorithms in this book have been expressed inmultipleprogramminglanguagesoverthe
pastseveraldecadesreinforcestheideathateachalgorithmisamethodsuitablefor implementationonanycomputerinanyprogramminglanguage.
Mostalgorithmsofinterestinvolveorganizingthedatainvolvedinthecomputa -tion.Suchorganizationleadstodata structures,whichalsoarecentralobjectsofstudy incomputerscience.Algorithmsanddatastructuresgohandinhand.Inthisbookwe
Compute the greatest common divisor of two nonnegative integers p and q as follows: If q is 0, the answer is p. If not, divide p by q and take the remainder r. The answer is the greatest common divisor of q and r.
public static int gcd(int p, int q) {
Whenweuseacomputertohelpussolveaproblem,wetypicallyarefacedwitha numberofpossibleapproaches.Forsmallproblems,ithardlymatterswhichapproach weuse,aslongaswehaveonethatcorrectlysolvestheproblem.Forhugeproblems(or applicationswhereweneedtosolvehugenumbersofsmallproblems),however,we quicklybecomemotivatedtodevisemethodsthatusetimeandspaceefficiently.
The primary reason to learn about algorithms is that this discipline gives us the potentialtoreaphugesavings,eventothepointofenablingustodotasksthatwould otherwisebeimpossible.Inanapplicationwhereweareprocessingmillionsofobjects, itisnotunusualtobeabletomakeaprogrammillionsoftimesfasterbyusingawell-designedalgorithm.Weshallseesuchexamplesonnumerousoccasionsthroughout the book. By contrast, investing additional money or time to buy and install a new computerholdsthepotentialforspeedingupaprogrambyperhapsafactorofonly10 or100.Carefulalgorithmdesignisanextremelyeffectivepartoftheprocessofsolving ahugeproblem,whatevertheapplicationsarea.
Whendevelopingahugeorcomplexcomputerprogram,agreatdealofeffortmust gointounderstandinganddefiningtheproblemtobesolved,managingitscomplex -ity,anddecomposingitintosmallersubtasksthatcanbeimplementedeasily.Often, manyofthealgorithmsrequiredafterthedecompositionaretrivialtoimplement.In mostcases,however,thereareafewalgorithmswhosechoiceiscriticalbecausemost ofthesystemresourceswillbespentrunningthosealgorithms.Thesearethetypesof algorithmsonwhichweconcentrateinthisbook.Westudyfundamentalalgorithms thatareusefulforsolvingchallengingproblemsinabroadvarietyofapplicationsareas.
The sharing of programs in computer systems is becoming more widespread, so althoughwemightexpecttobeusingalargefractionofthealgorithmsinthisbook,we alsomightexpecttohavetoimplementonlyasmallfractionofthem.Forexample,the Javalibrariescontainimplementationsofahostoffundamentalalgorithms.However, implementingsimpleversionsofbasicalgorithmshelpsustounderstandthembet -terandthustomoreeffectivelyuseandtuneadvancedversionsfromalibrary.More important,theopportunitytoreimplementbasicalgorithmsarisesfrequently.Thepri -maryreasontodosoisthatwearefaced,alltoooften,withcompletelynewcomputing environments (hardware and software) with new features that old implementations maynotusetobestadvantage.Inthisbook,weconcentrateonthesimplestreasonable implementationsofthebestalgorithms.Wedopaycarefulattentiontocodingthecriti -calpartsofthealgorithms,andtakepainstonotewherelow-leveloptimizationeffort couldbemostbeneficial.
Choosingthebestalgorithmforaparticulartaskcanbeacomplicatedprocess,per -hapsinvolvingsophisticatedmathematicalanalysis.Thebranchofcomputerscience thatcomprisesthestudyofsuchquestionsiscalledanalysisofalgorithms.Manyofthe
5
algorithmsthatwestudyhavebeenshownthroughanalysistohaveexcellenttheoreti -calperformance;othersaresimplyknowntoworkwellthroughexperience.Ourpri -marygoalistolearnreasonablealgorithmsforimportanttasks,yetweshallalsopay carefulattentiontocomparativeperformanceofthemethods.Weshouldnotusean algorithmwithouthavinganideaofwhatresourcesitmightconsume,sowestriveto beawareofhowouralgorithmsmightbeexpectedtoperform.
Summary of topics
Asanoverview,wedescribethemajorpartsofthebook,giv -ing specific topics covered and an indication of our general orientation toward the material.Thissetoftopicsisintendedtotouchonasmanyfundamentalalgorithmsas possible.Someoftheareascoveredarecorecomputer-scienceareasthatwestudyin depthtolearnbasicalgorithmsofwideapplicability.Otheralgorithmsthatwediscuss arefromadvancedfieldsofstudywithincomputerscienceandrelatedfields.Thealgo -rithmsthatweconsideraretheproductsofdecadesofresearchanddevelopmentand continuetoplayanessentialroleintheever-expandingapplicationsofcomputation.Fundamentals (Chapter 1)inthecontextofthisbookarethebasicprinciplesand
methodologythatweusetoimplement,analyze,andcomparealgorithms.Weconsider our Java programming model, data abstraction, basic data structures, abstract data typesforcollections,methodsofanalyzingalgorithmperformance,andacasestudy.
Sorting algorithms(Chapter 2)forrearrangingarraysinorderareoffundamental
importance.Weconsideravarietyofalgorithmsinconsiderabledepth,includingin -sertionsort,selectionsort,shellsort,quicksort,mergesort,andheapsort.Wealsoen -counteralgorithmsforseveralrelatedproblems,includingpriorityqueues,selection, andmerging.Manyofthesealgorithmswillfindapplicationasthebasisforotheralgo -rithmslaterinthebook.
Searching algorithms(Chapter 3)forfindingspecificitemsamonglargecollections
ofitemsarealsooffundamentalimportance.Wediscussbasicandadvancedmethods for searching, including binary search trees, balanced search trees, and hashing. We noterelationshipsamongthesemethodsandcompareperformance.
Graphs (Chapter 4)aresetsofobjectsandconnections,possiblywithweightsand
orientation. Graphs are useful models for a vast number of difficult and important problems,andthedesignofalgorithmsforprocessinggraphsisamajorfieldofstudy. Weconsiderdepth-firstsearch,breadth-firstsearch,connectivityproblems,andsev -eralalgorithmsandapplications,includingKruskal’sandPrim’salgorithmsforfinding minimumspanningtreeandDijkstra’sandtheBellman-Fordalgorithmsforsolving shortest-pathsproblems.
Strings (Chapter 5) are an essential data type in modern computing applications. Weconsiderarangeofmethodsforprocessingsequencesofcharacters.Webeginwith fasteralgorithmsforsortingandsearchingwhenkeysarestrings.Thenweconsider substring search, regular expression pattern matching, and data-compression algo -rithms.Again,anintroductiontoadvancedtopicsisgiventhroughtreatmentofsome elementaryproblemsthatareimportantintheirownright.
Context (Chapter 6)helpsusrelatethematerialinthebooktoseveralotheradvanced
fieldsofstudy,includingscientificcomputing,operationsresearch,andthetheoryof computing.Wesurveyevent-drivensimulation,B-trees,suffixarrays,maximumflow, andotheradvancedtopicsfromanintroductoryviewpointtodevelopappreciationfor theinterestingadvancedfieldsofstudywherealgorithmsplayacriticalrole.Finally,we describesearchproblems,reduction,andNP-completenesstointroducethetheoretical underpinningsofthestudyofalgorithmsandrelationshipstomaterialinthisbook.
The study of algorithms is interesting and excitingbecauseitisanewfield (almostallthealgorithmsthatwestudyarelessthan50yearsold,andsomewerejust recentlydiscovered)witharichtradition(afewalgorithmshavebeenknownforhun -dreds of years). New discoveries are constantly being made, but few algorithms are completelyunderstood.Inthisbookweshallconsiderintricate,complicated,anddiffi -cultalgorithmsaswellaselegant,simple,andeasyones.Ourchallengeistounderstand theformerandtoappreciatethelatterinthecontextofscientificandcommercialap -plications.Indoingso,weshallexploreavarietyofusefultoolsanddevelopastyleof algorithmicthinkingthatwillserveuswellincomputationalchallengestocome.
7
1.1
BASiC ProgrAMMing MoDel
Our study of algorithmsisbaseduponimplementingthemasprograms written in theJavaprogramminglanguage.Wedosoforseveralreasons:
n Ourprogramsareconcise,elegant,andcompletedescriptionsofalgorithms.
n Youcanruntheprogramstostudypropertiesofthealgorithms.
n Youcanputthealgorithmsimmediatelytogooduseinapplications.
Theseareimportantandsignificantadvantagesoverthealternativesofworkingwith English-languagedescriptionsofalgorithms.
Apotentialdownsidetothisapproachisthatwehavetoworkwithaspecificpro -gramminglanguage,possiblymakingitdifficulttoseparatetheideaofthealgorithm fromthedetailsofitsimplementation.Ourimplementationsaredesignedtomitigate thisdifficulty,byusingprogrammingconstructsthatarebothfoundinmanymodern languagesandneededtoadequatelydescribethealgorithms.
We use only a small subset of Java.While we stop short of formally defining the subsetthatweuse,youwillseethatwemakeuseofrelativelyfewJavaconstructs,and thatweemphasizethosethatarefoundinmanymodernprogramminglanguages.The codethatwepresentiscomplete,andourexpectationisthatyouwilldownloaditand executeit,onourtestdataortestdataofyourownchoosing.
Werefertotheprogrammingconstructs,softwarelibraries,andoperatingsystem featuresthatweusetoimplementanddescribealgorithmsasour programming model. InthissectionandSection 1.2,wefullydescribethisprogrammingmodel.Thetreat -mentisself-containedandprimarilyintendedfordocumentationandforyourrefer -enceinunderstandinganycodeinthebook.Themodelwedescribeisthesamemodel introducedinourbookAnIntroductiontoProgramminginJava:AnInterdisciplinary Approach,whichprovidesaslower-pacedintroductiontothematerial.
import java.util.Arrays;
public class BinarySearch
{
public static void main(String[] args) {
expression (see page 11)
call a method in our standard library; need to download code (see page 27) call a method in a Java library (see page 27)
call a local method (see page 27) import a Java library (see page 27)
code must be in file BinarySearch.java (see page 26)
initializing declaration statement
(see page 16)
command line (see page 36)
static method (see page 22)
unit test client (see page 26) loop statement
(see page 15)
conditional statement (see page 15)
system calls main()
system passes argument value "largeW.txt" to main()
anatomy of a Java program and its invocation from the command line parameter
variables
return type parameter type
return statement
no return value; just side effects (see page 24)
% java BinarySearch largeW.txt < largeT.txt 499569
984875 ...
file name (args[0])
file redirected from StdIn (see page 40) StdOut
(see page 37)
9
Basic structure of a Java program
AJavaprogram(class)iseitheralibrary ofstaticmethods(functions)oradatatypedefinition.Tocreatelibrariesofstaticmethods anddata-typedefinitions,weusethefollowingsevencomponents,thebasisofpro -gramminginJavaandmanyothermodernlanguages:
n Primitive data typespreciselydefinethemeaningoftermslikeinteger, real num-ber, and boolean valuewithinacomputerprogram.Theirdefinitionincludesthe setofpossiblevaluesandoperationsonthosevalues,whichcanbecombined into expressionslikemathematicalexpressionsthatdefinevalues.
n Statementsallowustodefineacomputationbycreatingandassigningvaluesto variables,controllingexecutionflow,orcausingsideeffects.Weusesixtypesof statements:declarations, assignments, conditionals, loops, calls, and returns. n Arrays allowustoworkwithmultiplevaluesofthesametype.
n Staticmethodsallowustoencapsulateandreusecodeandtodevelopprograms asasetofindependentmodules.
n Stringsaresequencesofcharacters.SomeoperationsonthemarebuiltintoJava.
n Input/outputsetsupcommunicationbetweenprogramsandtheoutsideworld.
n Data abstraction extendsencapsulationandreusetoallowustodefinenon-primitivedatatypes,thussupportingobject-orientedprogramming.
Inthissection,wewillconsiderthefirstfiveoftheseinturn.Dataabstractionisthe topicofthenextsection.
RunningaJavaprograminvolvesinteractingwithanoperatingsystemoraprogram developmentenvironment.Forclarityandeconomy,wedescribesuchactionsinterms of avirtual terminal, where we interact with programs by typing commands to the system.Seethebooksitefordetailsonusingavirtualterminalonyoursystem,orfor informationonusingoneofthemanymoreadvancedprogramdevelopmentenviron -mentsthatareavailableonmodernsystems.
For example,BinarySearch is two static methods,rank() and main(). The first staticmethod,rank(),isfourstatements:twodeclarations,aloop(whichisitselfanas -signmentandtwoconditionals),andareturn.Thesecond,main(),isthreestatements: adeclaration,acall,andaloop(whichisitselfanassignmentandaconditional).
ToinvokeaJavaprogram,wefirstcompileitusingthejavaccommand,thenrun it usingthejavacommand.Forexample,torunBinarySearch,wefirsttypethecom -mandjavac BinarySearch.java (which creates a fileBinarySearch.class that contains a lower-level version of the program in Java bytecode). Then we typejava BinarySearch(followedbyawhitelistfilename)totransfercontroltothebytecode versionoftheprogram.Todevelopabasisforunderstandingtheeffectoftheseactions, wenextconsiderindetailprimitivedatatypesandexpressions,thevariouskindsof Javastatements,arrays,staticmethods,strings,andinput/output.
Primitive data types and expressions
A data typeisasetofvaluesandasetof operationsonthosevalues.Webeginbyconsideringthefollowingfourprimitive data typesthatarethebasisoftheJavalanguage:n Integers,witharithmeticoperations(int)
n Real numbers,againwitharithmeticoperations(double)
n Booleans,thesetofvalues{true, false}withlogicaloperations(boolean) n Characters,thealphanumericcharactersandsymbolsthatyoutype(char) Nextweconsidermechanismsforspecifyingvaluesandoperationsforthesetypes.
AJavaprogrammanipulatesvariables thatarenamedwithidentifiers.Eachvariable isassociatedwithadatatypeandstoresoneofthepermissibledata-typevalues.InJava code,weuseexpressionslikefamiliarmathematicalexpressionstoapplytheoperations associatedwitheachtype.Forprimitivetypes,weuseidentifierstorefertovariables, operatorsymbolssuchas+ - * /tospecifyoperations,literalssuchas1 or 3.14 to specifyvalues,andexpressionssuchas(x + 2.236)/2tospecifyoperationsonvalues. Thepurposeofanexpressionistodefineoneofthedata-typevalues.
term examples definition
primitive
data type int double boolean char
asetofvaluesandasetof operationsonthosevalues (builtintotheJavalanguage)
identifier a abc Ab$ a_b ab123 lo hi
asequenceofletters,digits, _, and $,thefirstofwhichis
not a digit
variable [any identifier] namesadata-typevalue
operator + - * / namesadata-typeoperation
literal source-coderepresentation
ofavalue
int 1 0 -42
double 2.0 1.0e-15 3.14 boolean true false
char 'a' '+' '9' '\n'
expression
a literal, a variable, or a sequenceofoperationson literalsand/orvariablesthat
producesavalue int lo + (hi - lo)/2
double 1.0e-15 * t boolean lo <= hi
Basic building blocks for Java programs
11
To define a data type, we need only specify the values and the set of operations on thosevalues.ThisinformationissummarizedinthetablebelowforJava’sint, double, boolean, and chardatatypes.Thesedatatypesaresimilartothebasicdatatypesfound in many programming languages. Forint and double, the operations are familiar arithmeticoperations;forboolean,theyarefamiliarlogicaloperations.Itisimportant tonotethat+, -, *, and / are overloaded—thesamesymbolspecifiesoperationsinmul -tipledifferenttypes,dependingoncontext.Thekeypropertyoftheseprimitiveopera -tionsisthatanoperationinvolvingvaluesofagiventypehasavalueofthattype.Thisrule highlightstheideathatweareoftenworkingwithapproximatevalues,sinceitisoften thecasethattheexactvaluethatwouldseemtobedefinedbytheexpressionisnota valueofthetype.Forexample,5/3hasthevalue1 and 5.0/3.0hasavalueveryclose to 1.66666666666667butneitheroftheseisexactlyequalto5/3.Thistableisfarfrom complete;wediscusssomeadditionaloperatorsandvariousexceptionalsituationsthat weoccasionallyneedtoconsiderintheQ&Aattheendofthissection.
type set of values operators typical expressions expression value
int
integers between 231 and231 1 % (remainder)
5 + 3
boolean true or false
&& (and) || (or) ! (not) ^(xor)
true && false false || true
(16-bit) [arithmetic operations, rarely used]
primitive data types in Java
Expressions. Asillustratedinthetableatthebottomofthepreviouspage,typicalex -pressions are infix:aliteral(oranexpression),followedbyanoperator,followedby anotherliteral(oranotherexpression). Whenanexpressioncontainsmorethanone operator,theorderinwhichtheyareappliedisoftensignificant,sothefollowing pre-cedenceconventionsarepartoftheJavalanguagespecification:Theoperators* and / (and %)havehigherprecedencethan(areappliedbefore)the+ and -operators;among logical operators, !isthehighestprecedence,followedby&&andthen||.Generally, operatorsofthesameprecedenceareappliedlefttoright.Asinstandardarithmeticex -pressions,youcanuseparenthesestooverridetheserules.Sinceprecedencerulesvary slightlyfromlanguagetolanguage,weuseparenthesesandotherwisestrivetoavoid dependenceonprecedencerulesinourcode.
Type conversion. Numbersareautomaticallypromotedtoamoreinclusivetypeifno
informationislost.Forexample,intheexpression1 + 2.5,the1ispromotedtothe doublevalue1.0andtheexpressionevaluatestothedoublevalue3.5.A cast is a type nameinparentheseswithinanexpression,adirectivetoconvertthefollowingvalue intoavalueofthattype.Forexample(int) 3.7 is 3 and (double) 3 is 3.0.Notethat casting to an intistruncationinsteadofrounding—rulesforcastingwithincompli -catedexpressionscanbeintricate,andcastsshouldbeusedsparinglyandwithcare.A bestpracticeistouseexpressionsthatinvolveliteralsorvariablesofasingletype.
Comparisons. The following operators compare two values of the same type and
produceabooleanvalue:equal (==), notequal(!=), lessthan (<), lessthanorequal (<=), greater than (>), and greater than or equal (>=). These operators are known as mixed-typeoperatorsbecausetheirvalueisboolean,notthetypeofthevaluesbeing compared.Anexpressionwithabooleanvalueisknownasaboolean expression.Such expressionsareessentialcomponentsinconditionalandloopstatements,aswewillsee.
Other primitive types. Java’sinthas232differentvaluesbydesign,soitcanberepre
-sentedina32-bitmachineword(manymachineshave64-bitwordsnowadays,butthe 32-bit intpersists).Similarly,thedoublestandardspecifiesa64-bitrepresentation. Thesedata-typesizesareadequatefortypicalapplicationsthatuseintegersandreal numbers.Toprovideflexibility,Javahasfiveadditionalprimitivedatatypes:
n 64-bitintegers,witharithmeticoperations(long) n 16-bitintegers,witharithmeticoperations(short)
n 16-bitcharacters,witharithmeticoperations(char)
n 8-bitintegers,witharithmeticoperations(byte)
n 32-bitsingle-precisionrealnumbers,againwitharithmeticoperations(float) Wemostoftenuseint and doublearithmeticoperationsinthisbook,sowedonot considertheothers(whichareverysimilar)infurtherdetailhere.
13
Statements
AJavaprogramiscomposedofstatements,whichdefinethecomputa -tionbycreatingandmanipulatingvariables,assigningdata-typevaluestothem,and controllingtheflowofexecutionofsuchoperations.Statementsareoftenorganizedin blocks,sequencesofstatementswithincurlybraces.n Declarationscreatevariablesofaspecifiedtypeandnamethemwithidentifiers. n Assignmentsassociateadata-typevalue(definedbyanexpression)withavari
-able.Javaalsohasseveral implicit assignmentidiomsforchangingthevalueofa data-typevaluerelativetoitscurrentvalue,suchasincrementingthevalueofan integervariable.
n Conditionalsprovideforasimplechangeintheflowofexecution—executethe statementsinoneoftwoblocks,dependingonaspecifiedcondition.
n Loopsprovideforamoreprofoundchangeintheflowofexecution—executethe statementsinablockaslongasagivenconditionistrue.
n Calls and returnsrelatetostaticmethods(seepage22),whichprovideanotherway tochangetheflowofexecutionandtoorganizecode.
Aprogramisasequenceofstatements,withdeclarations,assignments,conditionals, loops,calls,andreturns.Programstypicallyhaveanestedstructure:astatementamong thestatementsinablockwithinaconditionaloraloopmayitselfbeaconditionalora loop.Forexample,thewhile loop in rank() contains an ifstatement.Next,wecon -sidereachofthesetypesofstatementsinturn.
Declarations. A declarationstatementassociatesavariablenamewithatypeatcom
-piletime.Javarequiresustousedeclarationstospecifythenamesandtypesofvari -ables.Bydoingso,wearebeingexplicitaboutanycomputationthatwearespecify -ing.Javaissaidtobeastrongly typedlanguage,becausetheJavacompilerchecksfor consistency(forexample,itdoesnotpermitustomultiplyaboolean and a double). Declarationscanappearanywherebeforeavariableisfirstused—mostoften,weput thematthepointoffirstuse.Thescopeofavariableisthepartoftheprogramwhereit isdefined.Generallythescopeofavariableiscomposedofthestatementsthatfollow thedeclarationinthesameblockasthedeclaration.
Assignments. An assignmentstatementassociatesadata-typevalue(definedbyanex
-pression)withavariable.Whenwewritec = a + binJava,wearenotexpressing mathematicalequality,butareinsteadexpressinganaction:setthevalueofthevari -able ctobethevalueofaplusthevalueofb.Itistruethatcismathematicallyequal to a + bimmediatelyaftertheassignmentstatementhasbeenexecuted,butthepoint ofthestatementistochangethevalueofc(ifnecessary).Theleft-handsideofanas -signmentstatementmustbeasinglevariable;theright-handsidecanbeanarbitrary expressionthatproducesavalueofthetype.
Conditionals. Mostcomputationsrequiredifferentactionsfordifferentinputs.One waytoexpressthesedifferencesinJavaistheifstatement:
if (<boolean expression>) { <block statements> }
Thisdescriptionintroducesaformalnotationknownasatemplatethatweuseocca -sionallytospecifytheformatofJavaconstructs.Weputwithinanglebrackets(< >) aconstructthatwehavealreadydefined,toindicatethatwecanuseanyinstanceof that construct where specified. In this case,<boolean expression> represents an expression that has a boolean value, such as one involving a comparison operation, and <block statements> representsasequenceofJavastatements.Itispossibleto makeformaldefinitionsof<boolean expression> and <block statements>,but werefrainfromgoingintothatlevelofdetail.Themeaningofanifstatementisself-explanatory:thestatement(s)intheblockaretobeexecutedifandonlyiftheboolean expressionistrue.Theif-elsestatement:
if (<boolean expression>) { <block statements> } else { <block statements> } allowsforchoosingbetweentwoalternativeblocksofstatements.
Loops. Manycomputationsareinherentlyrepetitive.ThebasicJavaconstructforhan
-dlingsuchcomputationshasthefollowingformat:
while (<boolean expression>) { <block statements> }
Thewhilestatementhasthesameformastheifstatement(theonlydifferencebeing theuseofthekeywordwhileinsteadofif),butthemeaningisquitedifferent.Itisan instructiontothecomputertobehaveasfollows:ifthebooleanexpressionisfalse, donothing;ifthebooleanexpressionistrue,executethesequenceofstatementsin theblock(justaswithif)butthencheckthebooleanexpressionagain,executethese -quenceofstatementsintheblockagainifthebooleanexpressionistrue,andcontinue aslongasthebooleanexpressionistrue.Werefertothestatementsintheblockina loopasthebodyoftheloop.
Break and continue. Somesituationscallforslightlymorecomplicatedcontrolflow
thanprovidedbythebasicif and whilestatements.Accordingly,Javasupportstwo additionalstatementsforusewithinwhileloops:
n Thebreakstatement,whichimmediatelyexitstheloop
n Thecontinuestatement,whichimmediatelybeginsthenextiterationofthe loop
Werarelyusethesestatementsinthecodeinthisbook(andmanyprogrammersnever usethem),buttheydoconsiderablysimplifycodeincertaininstances.
15
Shortcut notations
There are several ways to express a given computation; we seekclear,elegant,andefficientcode.Suchcodeoftentakesadvantageofthefollowing widelyusedshortcuts(thatarefoundinmanylanguages,notjustJava).Initializing declarations. Wecancombineadeclarationwithanassignmenttoini
-tializeavariableatthesametimethatitisdeclared(created).Forexample,thecode int i = 1; creates an intvariablenamediandassignsittheinitialvalue1.Abest practiceistousethismechanismclosetofirstuseofthevariable(tolimitscope).
Implicit assignments. Thefollowingshortcutsareavailablewhenourpurposeisto
modifyavariable’svaluerelativetoitscurrentvalue:
n Increment/decrementoperators:++iisthesameasi = i + 1;bothhavethe valueiinanexpression.Similarly,--iisthesameasi = i - 1.Thecodei++ and i--arethesameexceptthattheexpressionvalueisthevaluebeforethe increment/decrement,notafter.
n Othercompoundoperators:Prependingabinaryoperatortothe= in an assign-mentisequivalenttousingthevariableontheleftasthefirstoperand.Forex -ample,thecodei/=2; isequivalenttothecode i = i/2; Notethati += 1; hasthesameeffectasi = i+1; (and i++).
Single-statement blocks. Ifablockofstatementsinaconditionaloraloophasonlya
singlestatement,thecurlybracesmaybeomitted.
For notation. Manyloopsfollowthisscheme:initializeanindexvariabletosomeval
-ueandthenuseawhilelooptotestaloopcontinuationconditioninvolvingtheindex variable,wherethelaststatementinthewhileloopincrementstheindexvariable.You canexpresssuchloopscompactlywithJava’sfornotation:
for (<initialize>; <boolean expression>; <increment>) {
<block statements> }
Thiscodeis,withonlyafewexceptions,equivalentto
<initialize>;
while (<boolean expression>) {
<block statements> <increment>; }
Weuseforloopstosupportthisinitialize-and-incrementprogrammingidiom.
statement examples definition
declaration int i; double c;
createavariableofaspecifiedtype, namedwithagivenidentifier
assignment a = b + 3;
discriminant = b*b - 4.0*c; assignadata-typevaluetoavariable
initializing declaration
int i = 1;
double c = 3.141592625;
declarationthatalsoassignsan initialvalue
implicit assignment
i++;
i += 1; i = i + 1;
conditional (if) if (x < 0) x = -x; executeastatement,
dependingonbooleanexpression
conditional
(if-else)
if (x > y) max = x; else max = y;
executeoneortheotherstatement, dependingonbooleanexpression
loop (while)
int v = 1;
while (v <= N) v = 2*v;
double t = c;
while (Math.abs(t - c/t) > 1e-15*t) t = (c/t + t) / 2.0;
executestatement untilbooleanexpressionisfalse
loop (for)
for (int i = 1; i <= N; i++) sum += 1.0/i;
for (int i = 0; i <= N; i++) StdOut.println(2*Math.PI*i/N);
compactversionofwhilestatement
call int key = StdIn.readInt(); invokeothermethods(seepage22)
return return false; returnfromamethod(seepage24)
Java statements
17
Arrays
An arraystoresasequenceofvaluesthatareallofthesametype.Wewant notonlytostorevaluesbutalsotoaccesseachindividualvalue.Themethodthatwe usetorefertoindividualvaluesinanarrayisnumberingandthenindexingthem.If wehaveNvalues,wethinkofthemasbeingnumberedfrom0toN1.Then,wecan unambiguouslyspecifyoneoftheminJavacodebyusingthenotationa[i]toreferto theithvalueforanyvalueofifrom0 to N-1.ThisJavaconstructisknownasa one-dimensional array.Creating and initializing an array. MakinganarrayinaJavaprograminvolvesthree
distinctsteps:
n Declarethearraynameandtype.
n Createthearray.
n Initializethearrayvalues.
Todeclarethearray,youneedtospecifyanameandthetypeofdataitwillcontain. Tocreateit,youneedtospecifyitslength(thenumberofvalues).Forexample,the “long form” code shown at right makes
anarrayofNnumbersoftypedouble, all initialized to0.0. The first statement is thearraydeclaration.Itisjustlikeadec -larationofavariableofthecorrespond -ing primitive type except for the square bracketsfollowingthetypename,which specify that we are declaring an array. The keywordnew in the second state -mentisaJavadirectivetocreatethear
-Default array initialization. Foreconomyincode,weoftentakeadvantageofJava’s
defaultarrayinitializationconventionandcombineallthreestepsintoasinglestate -ment,asinthe“shortform”codeinourexample.Thecodetotheleftoftheequalsign constitutesthedeclaration;thecodetotherightconstitutesthecreation.Thefor loop isunnecessaryinthiscasebecausethedefaultinitialvalueofvariablesoftypedouble
double[] a = new double[N]; initialization
Declaring, creating, and initializing an array
short form
int[] a = { 1, 1, 2, 3, 5, 8 }; initializing declaration
long form
in a Java array is 0.0,butitwouldberequiredifanonzerovalueweredesired.Thede -faultinitialvalueiszerofornumerictypesandfalsefortypeboolean.
Initializing declaration. The third option shown for our example is to specify the
initializationvaluesatcompiletime,bylistingliteralvaluesbetweencurlybraces,sepa -ratedbycommas.
Using an array. Typicalarray-processingcodeisshownonpage21.Afterdeclaring
andcreatinganarray,youcanrefertoanyindividualvalueanywhereyouwoulduse avariablenameinaprogrambyenclosinganintegerindexinsquarebracketsafter thearrayname.Oncewecreateanarray,itssizeisfixed.Aprogramcanrefertothe lengthofanarraya[]withthecodea.length.Thelastelementofanarraya[] is always a[a.length-1].Javadoesautomaticboundschecking—ifyouhavecreatedan arrayofsizeNanduseanindexwhosevalueislessthan0orgreaterthanN-1,yourpro -gramwillterminatewithanArrayOutOfBoundsExceptionruntimeexception.
Aliasing. Notecarefullythatan array name refers to the whole array—ifweassignone
arraynametoanother,thenbothrefertothesamearray,asillustratedinthefollowing codefragment.
int[] a = new int[N]; ...
a[i] = 1234; ...
int[] b = a;
...
b[i] = 5678; // a[i] is now 5678.
Thissituationisknownasaliasingandcanleadtosubtlebugs.Ifyourintentistomake acopyofanarray,thenyouneedtodeclare,create,andinitializeanewarrayandthen copyalloftheentriesintheoriginalarraytothenewarray,asinthethirdexampleon page21.
Two-dimensional arrays. A two-dimensional arrayinJavaisanarrayofone-dimen
-sionalarrays.Atwo-dimensionalarraymayberagged(itsarraysmayallbeofdiffering lengths),butwemostoftenworkwith(forappropriateparametersM and N) M-by-N two-dimensionalarraysthatarearraysofM rows,eachanarrayoflengthN (so it also makessensetorefertothearrayashavingNcolumns).ExtendingJavaarrayconstructs tohandletwo-dimensionalarraysisstraightforward.Torefertotheentryinrowi and columnjofatwo-dimensionalarraya[][],weusethenotationa[i][j];todeclarea two-dimensionalarray,weaddanotherpairofsquarebrackets;andtocreatethearray,
19
wespecifythenumberofrowsfollowedbythenumberofcolumnsafterthetypename (bothwithinsquarebrackets),asfollows:
double[][] a = new double[M][N];
WerefertosuchanarrayasanM-by-Narray.Byconvention,thefirstdimensionisthe numberofrowsandthesecondisthenumberofcolumns.Aswithone-dimensional arrays, Java initializes all entries in arrays of numeric types to zero and in arrays of boolean values tofalse. Default initialization of two-dimensional arrays is useful becauseitmasksmorecodethanforone-dimensionalarrays.Thefollowingcodeis equivalenttothesingle-linecreate-and-initializeidiomthatwejustconsidered:
double[][] a;
a = new double[M][N]; for (int i = 0; i < M; i++) for (int j = 0; j < N; j++) a[i][j] = 0.0;
Thiscodeissuperfluouswheninitializingtozero,butthenestedfor loops are needed toinitializetoothervalue(s).
task implementation (code fragment)
findthemaximumof thearrayvalues
double max = a[0];
for (int i = 1; i < a.length; i++) if (a[i] > max) max = a[i];
computetheaverageof thearrayvalues
int N = a.length; double sum = 0.0;
for (int i = 0; i < N; i++) sum += a[i];
double average = sum / N;
copytoanotherarray
int N = a.length;
double[] b = new double[N]; for (int i = 0; i < N; i++) b[i] = a[i];
reversetheelements withinanarray
int N = a.length;
for (int i = 0; i < N/2; i++) {
double temp = a[i]; a[i] = a[N-i-1]; a[N-i-1] = temp; }
matrix-matrix multiplication (squarematrices)
a[][]*b[][] = c[][]
int N = a.length;
double[][] c = new double[N][N]; for (int i = 0; i < N; i++) for (int j = 0; j < N; j++)
{ // Compute dot product of row i and column j. for (int k = 0; k < N; k++)
c[i][j] += a[i][k]*b[k][j]; }
typical array-processing code
21
Static methods
Every Java program in this book is either adata-type definition (whichwedescribeindetailinSection 1.2) or a libraryofstaticmethods(whichwede -scribehere).Staticmethodsarecalledfunctionsinmanyprogramminglanguages,since theycanbehavelikemathematicalfunctions,asdescribednext.Eachstaticmethodis asequenceofstatementsthatareexecuted,oneaftertheother,whenthestaticmethod is called,inthemannerdescribedbelow.Themodifierstaticdistinguishesthesemeth -odsfrominstancemethods,whichwediscussinSection 1.2.Weusethewordmethod withoutamodifierwhendescribingcharacteristicssharedbybothkindsofmethods.Defining a static method. A methodencapsulatesacomputationthatisdefinedasa
sequence of statements.A method takesarguments (values of given data types) and computes areturn value of some data type that depends upon the arguments (such asavaluedefinedbyamathematicalfunction)orcausesaside effectthatdependson thearguments(suchasprintingavalue).Thestaticmethodrank() in BinarySearch
isanexampleofthefirst;main()isanex -ample of the second. Each static method is composed of asignature (the keywords public staticfollowedbyareturntype, the method name, and a sequence of ar -guments, each with a declared type) and a body (a statement block: a sequence of statements, enclosed in curly braces). Ex -amplesofstaticmethodsareshowninthe tableonthefacingpage.
Invoking a static method. A call on a static
methodisitsnamefollowedbyexpressions that specify argument values in parenthe -ses,separatedbycommas.Whenthemethodcallispartofanexpression,themethod computesavalueandthatvalueisusedinplaceofthecallintheexpression.Forex -ample the call onrank() in BinarySearch() returns anint value. A method call followedbyasemicolonisastatementthatgenerallycausessideeffects.Forexample, thecallArrays.sort() in main() in BinarySearchisacallonthesystemmethod Arrays.sort() that has the side effect of putting the entries in the array in sorted order.Whenamethodiscalled,itsargumentvariablesareinitializedwiththevalues
call on another method public static double sqrt ( double c ) {
anatomy of a static method
task implementation
absolute value of an
int value
public static int abs(int x) {
if (x < 0) return -x; else return x; }
absolute value of a
double value
public static double abs(double x) {
if (x < 0.0) return -x; else return x; }
primality test
public static boolean isPrime(int N) {
public static double sqrt(double c) {
public static double hypotenuse(double a, double b) { return Math.sqrt(a*a + b*b); }
Harmonicnumber (seepage185)
public static double H(int N) {
typical implementations of static methods
23