id
int64
0
25.6k
text
stringlengths
0
4.59k
20,600
chap patterns of algorithms there is no such thing as random number sequenceonly "random enoughsequences sequence is pseudorandom if no future term can be predicted in polynomial timegiven all past terms most computer systems use deterministic algorithm to select pseudorandom numbers the most commonly used approach his...
20,601
sec numerical algorithms the fast fourier transform as noted at the beginning of this sectionmultiplication is considerably more difficult than additionbecause the cost to multiply two -bit numbers directly is ( )while addition of two -bit numbers is (nrecall from section that one property of logarithms is log nm log l...
20,602
chap patterns of algorithms polynomial ab nowwe see what happens when we multiply the evaluations of and at points and - ab(- ( )( ab( ( )( ab( ( )( these results are the same as when we evaluate polynomial ab at these points note that evaluating any polynomial at is easy if we evaluate at and - we can share lot of the...
20,603
sec numerical algorithms - - - - figure examples of the th and th roots of unity advantage of symmetriessuch as the one we see for evaluating and - but we need to find even more symmetries between points if we want to do more than cut the work in half we have to find symmetries betweensaypairs of values and then furthe...
20,604
chap patterns of algorithms at the nth roots of unity by multiplying the az matrix by the coefficient vector the resulting vector fz is called the discrete fourier transform for the polynomial fz az bi - ak ik = when then sothe corresponding matrix is as follows - - - - - - - - - - az - - - - - - - - - - - - - - we sti...
20,605
sec numerical algorithms bottom half with suitable sign changes on some rows and columns likewise for the left and right halves an efficient divide and conquer algorithm exists to perform both the evaluation and the interpolation in th( log ntime this is called the discrete fourier transform (dftit is recursive functio...
20,606
chap patterns of algorithms further reading for further information on skip listssee "skip listsa probabilistic alternative to balanced treesby william pugh [pug exercises solve towers of hanoi using dynamic programming algorithm there are six permutations of the lines for (int = < () ++for (int = < () ++for (int = < (...
20,607
what is the expected (averagenumber of pointers for skip list node write function to remove node with given value from skip list write function to find the ith node on skip list projects complete the implementation of the skip list-based dictionary begun in section implement both standard th( matrix multiplication algo...
20,608
limits to computation this book describes many data structures that can be used in wide variety of problems there are also many examples of efficient algorithms in generalour search algorithms strive to be at worst in (log nto find recordwhile our sorting algorithms strive to be in ( log na few algorithms have higher a...
20,609
chap limits to computation slowbut perhaps there are better ones waiting to be discovered of coursewhile having problem with high running time is badit is even worse to have problem that cannot be solved at allproblems of the later type do existand some are presented in section this presents brief introduction to the t...
20,610
sec reductions figure an illustration of pairing the two lists of numbers are paired up so that the least values from each list make pairthe next smallest values from each list make pairand so on known in software engineering as software reuse to illustrate thislet us consider another problem pairinginputtwo sequences ...
20,611
chap limits to computation find one method to convert the inputs to pairing into inputs to sorting "fast enough,and second method to convert the result of sorting back to the correct result for pairing "fast enough,then the asymptotic cost of pairing cannot be more than the cost of sorting in this casethere is little w...
20,612
the records in the array using the corresponding value in the array as the sort key and running simple th(nbinsort the conversion of sorting to pairing can be done in (ntimeand likewise the conversion of the output of pairing can be converted to the correct output for sorting in (ntime thusthe cost of this "sorting alg...
20,613
chap limits to computation problem ai transform iproblem slntransform sln figure the general process for reduction shown as "blackboxdiagram asymptotically faster (but more complicatedalgorithms are knownbut none is so fast as to be in (nnext we ask the questionis squaring an -digit number as difficult as multiplying t...
20,614
sec reductions sortinginteger array transform integers to integer array pairing array of pairs transform sorted integer array figure the reduction of sorting to pairing shown as "blackboxdiagram our next example of reduction concerns the multiplication of two matrices for this problemwe will assume that the values stor...
20,615
chap limits to computation at here stands for an matrix composed of zero valuesa is the original matrixand at stands for the transpose of matrix note that the resulting matrix is now symmetric we can convert matrix to symmetric matrix in similar manner if symmetric matrices could be multiplied "quickly(in particularif ...
20,616
the towers of hanoi problem takes exponential timethat isits running time is th( this is radically different from an algorithm that takes th( log ntime or th( time it is even radically different from problem that takes th( time these are all examples of polynomial running timebecause the exponents for all terms of thes...
20,617
chap limits to computation the theory of -completeness imagine magical computer that works by guessing the correct solution from among all of the possible solutions to problem another way to look at this is to imagine super parallel computer that could test all possible solutions simultaneously certainly this magical (...
20,618
sec hard problems figure an illustration of the traveling salesman problem five vertices are shownwith edges between each pair of cities the problem is to visit all of the cities exactly oncereturning to the start citywith the least total cost route would be abdceawith cost the best route for this particular graph woul...
20,619
chap limits to computation lar computer nor does anybody in the world know of any other polynomial time algorithm to solve traveling salesman on regular computerdespite the fact that the problem has been studied extensively by many computer scientists for many years it turns out that there is large collection of proble...
20,620
there is practical advantage to knowing that problem is -complete it relates to knowing that if polynomial time solution can be found for any problem that is -completethen polynomial solution can be found for all such problems the implication is that because no one has yet found such solutionit must be difficult or imp...
20,621
chap limits to computation exponential time problems toh problems -complete problems traveling salesman problems sorting figure our knowledge regarding the world of problems requiring exponential time or less some of these problems are solvable in polynomial time by non-deterministic computer of thesesome are known to ...
20,622
sec hard problems satisfiability (satinputa boolean expression over variables in conjunctive normal form outputyes if there is an assignment to the variables that makes trueno otherwise cook proved that sat is -hard explaining this proof is beyond the scope of this book but we can briefly summarize it as follows any de...
20,623
chap limits to computation -satisfiability ( satinputa boolean expression in cnf such that each clause contains exactly literals outputyes if the expression can be satisfiedno otherwise example sat is special case of sat is sat easier than satnot if we can prove it to be -complete theorem sat is -complete proofprove th...
20,624
for the first two cases it is fairly easy to see that the original clause is satisfiable if and only if the resulting clauses are satisfiable for the case were we replaced clause with more than three literalsconsider the following if is satisfiablethen is satisfiableassume xm is assigned true then assign zt as false th...
20,625
chap limits to computation asking if has vertex cover of size or smaller if yesthen there is clique in of size kif no then there is not example so farour -completeness proofs have involved transformations between inputs of the same "type,such as from boolean expression to boolean expression or from graph to graph somet...
20,626
sec hard problems figure the graph generated from boolean expression ( + )*( ( literals from the first clause are labeled and literals from the second clause are labeled there is an edge between every two pairs of vertices except when both vertices represent instances of literals from the same clauseor negation of the ...
20,627
chap limits to computation this dynamic programming algorithm is tractable if the numbers are "reasonable that iswe can successfully find solutions to the problem when nk is in the thousands such an algorithm is called pseudo-polynomial time algorithm this is different from traveling salesman which cannot possibly be s...
20,628
tree in some cases we avoid processing many potential solutionsor find solution quickly in otherswe end up visiting large portion of the possible solutions banch-and-bounds is an extension of backtracking that applies to optimization problems such as traveling salesman where we are trying to find the shortest tour thro...
20,629
chap limits to computation bin packinginputnumbers xn between and and an unlimited supply of bins of size (no bin can hold numbers whose sum exceeds outputan assignment of numbers to bins that requires the fewest possible bins bin packing in its decision form ( asking if the items can be packed in less than binsis know...
20,630
impossible problems even the best programmer sometimes writes program that goes into an infinite loop of coursewhen you run program that has not stoppedyou do not know for sure if it is just slow program or program in an infinite loop after "enough time,you shut it down wouldn' it be great if your compiler could look a...
20,631
chap limits to computation uncountability before proving that the halting problem is unsolvablewe first prove that not all functions can be implemented as computer program this is so because the number of programs is much smaller than the number of possible functions set is said to be countable (or countably infinite i...
20,632
are likewise assigned to binsthen strings of length fourand so on in this waya string of any given length can be assigned to some bin by this processany string of finite length is assigned to some bin so any programwhich is merely string of finite lengthis assigned to some bin because all programs are assigned to some ...
20,633
chap limits to computation ( ( ( ( figure an illustration of assigning functions to bins can we assign every function to binthe answer is nobecause there is always way to create new function that is not in any of the bins suppose that somebody presents way of assigning functions to bins that they claim includes all of ...
20,634
sec impossible problems ( ( ( ( fnew ( figure illustration for the argument that the number of integer functions is uncountable that the halting problem cannot be computed by any computer program the proof is by contradiction we begin by assuming that there is function named halt that can solve the halting problem obvi...
20,635
chap limits to computation /return true if "proghalts when given itself as input bool selfhalt(string progif (halt(progprog)return trueelse return false/return the reverse of what selfhalt returns on "progvoid contrary(string progif (selfhalt(prog)while (true)/go into an infinite loop what happens if we make program wh...
20,636
another function combine that takes program and an input string as parameters function combine modifies to store as static variable and further modifies all calls to input functions within to instead get their input from call the resulting program it should take no stretch of the imagination to believe that any decent ...
20,637
chap limits to computation this does not mean that computer program cannot be written that works on special casespossibly even on most programs that we would be interested in checking for examplesome compilers will check if the control expression for while loop is constant expression that evaluates to false if it isthe...
20,638
sec exercises use reduction to prove that multiplying two upper triangular matrices is just as expensive (asymptoticallyas multiplying two arbitrary matrices (aexplain why computing the factorial of by multiplying all values from to together is an exponential time algorithm (bexplain why computing an approximation to t...
20,639
chap limits to computation independent set inputa graph and an integer outputyes if there is subset of the vertices in of size or greater such that no edge connects any two vertices in sand no otherwise assuming that -clique is -completeprove that independent set is -complete define the problem partition as followspart...
20,640
the last paragraph of section discusses strategy for developing solution to new problem by alternating between finding polynomial time solution and proving the problem -complete refine the "algorithm for designing algorithmsfrom section to incorporate identifying and dealing with -complete problems prove that the set o...
20,641
chap limits to computation the problem in the sense of finding the smallest set of vertices that forms vertex cover implement knapsack (see section measure its running time on number of inputs what is the largest practical input size for this problem implement an approximation of traveling salesmanthat isgiven graph wi...
20,642
[ag [aha [ahu [ahu [bb [ben [ben [ben [ben [ben [ben [ben ken arnold and james gosling the java programming language addison-wesleyreadingmausafourth edition dan aharoni cogitoergo sumcognitive processes of students dealing with data structures in proceedings of sigcse' pages - acm pressmarch alfred ahojohn hopcroftand...
20,643
[bg bibliography sara baase and allen van gelder computer algorithmsintroduction to design analysis addison-wesleyreadingmausathird edition [bm john louis bentley and catherine mcgeoch amortized analysis of self-organizing sequential search heuristics communications of the acm ( ): - april [bro frederick brooks the myt...
20,644
[gi [gj [gkp [gle [gut [hay [hei [jay [kaf [knu [knu [knu [koz [kp [lag [lev zvi galil and giuseppe italiano data structures and algorithms for disjoint set union problems computing surveys ( ): - september michael garey and david johnson computers and intractabilitya guide to the theory of np-completeness freemannew y...
20,645
bibliography [llks lawlerj lenstraa rinnooy kanand shmoyseditors the traveling salesman problema guided tour of combinatorial optimization john wiley sonsnew york [man udi manber introduction to algorithmsa creative approach addision-wesleyreadingma [pol george polya how to solve it princeton university pressprincetonn...
20,646
[ski [sm [sol [st [sta [sta [ste [sto [su [sw [swh [tan [tar [tre [wel [wl steven skiena the algorithm design manual springer verlagnew york gerard salton and michael mcgill introduction to modern information retrieval mcgraw-hillnew york daniel solow how to read and do proofs john wiley sonsnew yorksecond edition slea...
20,647
bibliography [wmb wittena moffatand bell managing gigabytes morgan kaufmannsecond edition [zei paul zeitz the art and craft of problem solving john wiley sonsnew yorksecond edition
20,648
javaxiv-xvii - genericxvi file access - inheritancexvi new java generic new private members abstract data type (adt)xiv - - - - - - abstraction accounting ackermann' function activation recordsee compileractivation record aggregate type algorithm definition of - algorithm analysisxiii - amortizedsee amortized analysis ...
20,649
best fitsee memory managementbest fit best-case analysis - big-oh notationsee notation bin packing - binary searchsee searchbinary binary search treesee bst binary tree - bstsee bst complete full - implementation node - - null pointers overhead parent pointer space requirements - terminology - threaded traversalsee tra...
20,650
compositesee design patterncomposite composite type computability computer graphics connected componentsee graphconnected component contradictionproof bysee proofcontradiction cylindersee disk drivecylinder data item data member data structure costs and benefitsxiii - definition philosophy - physical vs logical formxvi...
20,651
relation estimating - - exact-match querysee searchexact-match query exponential growth ratesee growth rateexponential expression tree - extent external sortingsee sortingexternal factorial function stirling' approximation fibonacci sequence - fifo list file manager file processing file structure first fitsee memory ma...
20,652
constant exponential linear - quadratic - halting problem - hamiltonian cycle handle harmonic series hashing - analysis of - bucket - closed - collision resolution - deletion - double dynamic hash function - home position insert linear probing - load factor open - perfect primary clustering - probe function - probe seq...
20,653
integer representation - inversion inverted listsee indexinverted list isam - - tree - -ary tree - key - kilobyte knapsack problem - kruskal' algorithmxv - largest common factor latency least frequently used (lfu) least recently used (lru) lifo list linear growthsee growth ratelinear linear indexsee indexlinear linear ...
20,654
additional java source code slides in powerpoint and pdf (one-per-pageformat self-contained special-topic supplementsincluding discussions on convex hullsrange treesand orthogonal segment intersection the slides are fully editableso as to allow an instructor using this book full freedom in customizing his or her presen...
20,655
and sections pf fundamental programming constructs pf algorithms and problem-solving sections pf fundamental data structures sections pf recursion section se software design and sections se using apis sections al basic algorithmic analysis al algorithmic strategies sections al fundamental computing algorithms sections ...
20,656
sections ds graphs and trees ds discrete probability appendix and sections listing the for this course are organized to provide pedagogical path that starts with the basics of java programming and object-oriented designmoves to concrete structures like arrays and linked listsadds foundational techniques like recursion ...
20,657
memory useful mathematical facts prerequisites we have written this book assuming that the reader comes to it with certain knowledge that iswe assume that the reader is at least vaguely familiar with high-level programming languagesuch as cc++or javaand that he or she understands the main constructs from such high-leve...
20,658
technology researchwith special emphasis on algorithm visualization systems michael goodrich received his ph in computer science from purdue university in he is currently professor in the department of computer science at university of californiairvine previouslyhe was professor at johns hopkins university he is an edi...
20,659
zamore lubomir bourdevmike demmermark handymichael hornand scott speigler developed basic java tutorialwhich ultimately led to java programming special thanks go to eric zamorewho contributed to the development of the java code examples in this book and to the initial designimplementationand testing of the net datastru...
20,660
visio(rfor the figures finallywe would like to warmly thank isabel cruzkaren goodrichgiuseppe di battistafranco preparataioannis tollisand our parents for providing adviceencouragementand support at various stages of the preparation of this book we also thank them for reminding us that there are things in life beyond w...
20,661
base types objects enum types methods expressions literals operators
20,662
expressions control flow the if and switch statements loops explicit control-flow statements arrays declaring arrays arrays are objects simple input and output
20,663
an example program nested classes and packages writing java program design pseudocode coding testing and debugging exercises java datastructures net
20,664
getting startedclassestypesand objects building data structures and algorithms requires that we communicate detailed instructions to computerand an excellent way to perform such communication is using high-level computer languagesuch as java in this we give brief overview of the java programming languageassuming the re...
20,665
methods for accessing and modifying this data every object is an instance of classwhich defines the type of the objectas well as the kinds of operations that it performs the critical members of class in java are the following (classes can also contain inner class definitionsbut let us defer discussing this concept for ...
20,666
begins with "{and ends with "in javaany set of statements between the braces "{and "}define program block as with the universe classthe counter class is publicwhich means that any other class can create and use counter object the counter has one instance variable-an integer called count this variable is initialized to ...
20,667
interface switch boolean extends long synchronized break false native this byte final new throw case finally null throws catch float package transient char for
20,668
true class goto protected try const if public void continue implements return volatile default import short while do instanceof static double int super class modifiers
20,669
already seen examples that use the public keyword in generalthe different class modifiers and their meaning is as followsthe abstract class modifier describes class that has abstract methods abstract methods are declared with the abstract keyword and are empty (that isthey have no block defining body of code for this m...
20,670
-bit signed two' complement integer long -bit signed two' complement integer float -bit floating-point number (ieee - double -bit floating-point number (ieee - variable declared to have one of these types simply stores value of that typerather than reference to some object integer constantslike or are of type intunless...
20,671
note the use of comments in this and other examples these comments are annotations provided for human readers and are not processed by java compiler java allows for two kinds of comments-block comments and inline commentswhich define text ignored by the compiler java uses /to begin block comment and *to close it of par...
20,672
output from the base class output from an execution of the base class (main methodis shown in figure figure output from the base class even though they themselves do not refer to objectsbase-type variables are useful in the context of objectsfor they often make up the instance variables (or fieldsinside an object for e...
20,673
new object is dynamically allocated in memoryand all instance variables are initialized to standard default values the default values are null for object variables and for all base types except boolean variables (which are false by defaultthe constructor for the new object is called with the parameters specified the co...
20,674
assign the value of corresponding number object to base number type table java number classes each class is given with its corresponding base type and example expressions for creating and accessing such objects for each rowwe assume the variable is declared with the corresponding class name base type class name creatio...
20,675
float float new float( ) floatvaluedouble double new double( ) doublevaluestring objects string is sequence of characters that comes from some alphabet (the set of all possible characterseach character that makes up string can be referenced by its index in the stringwhich is equal to the number of characters that come ...
20,676
usefulin java to write an assignment statement like strings "kilo"meters"this statement defines variable that references objects of the string classand assigns it the string "kilometers(we will discuss assignment statements and expressions such as that above in more detail later in this every object in java is assumed ...
20,677
every object reference variable must refer to some objectunless it is nullin which case it points to nothing using the remote control analogya null reference is remote control holder that is empty initiallyunless we assign an object variable to point to somethingit is null there canin factbe many references to the same...
20,678
consider the following examplesoven cookdinner()oven cookdinner(food)oven cookdinner(foodseasoning)each of these method calls is actually referring to different method with the same name defined in the class that oven belongs to notehoweverthat the signature of method in java does not include the type that the method r...
20,679
variablesvariable modifiers in some caseswe may not be allowed to directly access some of the instance variables for an object for examplean instance variable declared as private in some class is only accessible by the methods defined inside that class such instance variables are similar to device parameters that canno...
20,680
the following variable modifierspublicanyone can access public instance variables protectedonly methods of the same package or of its subclasses can access protected instance variables privateonly methods of the same class (not methods of subclasscan access private instance variables if none of the above modifiers are ...
20,681
magicaland height are base typesthe variable name is reference to an instance of the built-in class stringand the variable gnomebuddy is reference to an object of the class we are now defining our declaration of the instance variable max_height in the gnome class is taking advantage of these two modifiers to
20,682
associated with class should always be declared to be both static and final enum types since java supports enumerated typescalled enums these are types that are only allowed to take on values that come from specified set of names they are declared inside of class as followsmodifier enum name value_name value_name value...
20,683
methods methods in java are conceptually similar to functions and procedures in other highlevel languages in generalthey are "chunksof code that can be called on particular object (from some classmethods can accept parameters as argumentsand their behavior depends on the object they belong to and the values of any para...
20,684
detail in this section the modifiers part includes the same kinds of scope modifiers that can be used for variablessuch as publicprotectedand staticwith similar meanings the type part of the declaration defines the return type of the method the name is the name of the methodwhich can be any valid java identifier the li...
20,685
usefulness of this construct in section finalthis is method that cannot be overridden by subclass staticthis is method that is associated with the class itselfand not with particular instance of the class static methods can also be used to change the state of static variables associated with class (provided these varia...
20,686
for exampleif we pass gnome reference to method that calls this parameter hthen this method can change the reference to point to different objectbut will still refer to the same object as before of coursethe method can use the reference to change the internal state of the objectand this will change ' object as well (si...
20,687
that they may be in stable initial state when first created constructors are invoked in unique waythey must be called using the new operator soupon invocationa new instance of this class is automatically created and its constructor is then called to initialize its instance variables and perform other setup tasks for ex...
20,688
program to take an optional argument that specifies the number of fish in the aquarium we could then invoke the program by typing the following in shell windowjava aquarium to specify that we want an aquarium with fish in it in this caseargs[ would refer to the string " one nice feature of the main method in class defi...
20,689
double expressions variables and constants are used in expressions to define new values and to modify variables in this sectionwe discuss how expressions work in java in more detail expressions involve the use of literalsvariablesand operators since we have already discussed variableslet us briefly focus on literals an...
20,690
'\\(backslash'\'(single quote'\"(double quotestring lierala string literal is sequence of characters enclosed in double quotesfor examplethe following is string literal"dogs cannot climb treesoperators java expressions involve composing literals and variables with operators we survey the operators in java in this secti...
20,691
this last operatormodulois also known as the "remainderoperatorbecause it is the remainder left after an integer division we often use "modto denote the modulo operatorand we define it formally as mod rsuch that mq rfor an integer and < java also provides unary minus (-)which can be placed in front of an arithm etic ex...
20,692
=equal to !not equal to >greater than or equal to greater than the operators =and !can also be used for object references the type of the result of comparison is boolean operators that operate on boolean values are the following&not (prefixconditional and conditional or the boolean operators &and will not evaluate the ...
20,693
zeros operational assignment operators besides the standard assignment operator (=)java also provides number of other assignment operators that have operational side effects these other kinds of operators are of the following formvariable op expression where op is any binary operator the above expression is equivalent ...
20,694
operators in java are given preferencesor precedencethat determine the order in which operations are performed when the absence of parentheses brings up evaluation ambiguities for examplewe need way of deciding if the expression" + * ,has value or (java says it is we show the precedence of the operators in java (whichi...
20,695
add /subt + shift comparison >instanceof equality =! bitwise-and bitwise-xor bitwise-or and &
20,696
conditional boolean_expressionvalue_if_truevalue_if_false assignment +-*/%>>>>=&^we have now discussed almost all of the operators listed in table notable exception is the conditional operatorwhich involves evaluating boolean expression and then taking on the appropriate value depending on whether this boolean expressi...
20,697
double int (int) / has value int (int) / has value double (double) / has value casting with operators certain binary operatorslike divisionwill have different results depending on the variable types they are used with we must take care to make sure operations perform their computations on values of the intended type wh...
20,698
/loss of precision -this is compilation error iresult (inti dfractional part is lost /iresult is since the note that since java will not perform implicit casts where precision is lostthe explicit cast in the last line above is required since java there is new kind of implicit castfor going between number objectslike in...
20,699
poor style /correctbut string "value /this is good string integer tostring( )/this is good control flow control flow in java is similar to that of other high-level languages we review the basic structure and syntax of control flow in java in this sectionincluding method returnsif statementsswitch statementsloopsand res...