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 historically is known as the linear congruential method (lcmthe lcm method is quite simple we begin by picking seed that we will call ( thenwe can compute successive terms as follows ( ( ( bmod where and are constants by definition of the mod functionall generated numbers must be in the range to nowconsider what happens when (ir(jfor values and of course then ( ( which means that we have repeating cycle since the values coming out of the random number generator are between and the longest cycle that we can hope for has length in factsince ( it cannot even be quite this long it turns out that to get good resultit is crucial to pick good values for both and to see whyconsider the following example example given value of we can get very different results depending on the value that we pickin ways that are hard to predict ( ( mod ( ( mod ( ( mod clearlya value of is far inferior to values of or in this example if you would like to write simple lcm random number generator of your ownan effective one can be made with the following formula ( ( mod
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 log thusif taking logarithms and anti-logarithms were cheapthen we could reduce multiplication to addition by taking the log of the two operandsaddingand then taking the anti-log of the sum under normal circumstancestaking logarithms and anti-logarithms is expensiveand so this reduction would not be considered practical howeverthis reduction is precisely the basis for the slide rule the slide rule uses logarithmic scale to measure the lengths of two numbersin effect doing the conversion to logarithms automatically these two lengths are then added togetherand the inverse logarithm of the sum is read off another logarithmic scale the part normally considered expensive (taking logarithms and anti-logarithmsis cheap because it is physical part of the slide rule thusthe entire multiplication process can be done cheaply via reduction to addition in the days before electronic calculatorsslide rules were routinely used by scientists and engineers to do basic calculations of this nature now consider the problem of multiplying polynomials vector of values can uniquely represent polynomial of degree expressed as pa (xn- xi = alternativelya polynomial can be uniquely represented by list of its values at distinct points finding the value for polynomial at given point is called evaluation finding the coefficients for the polynomial given the values at points is called interpolation to multiply two -degree polynomials and normally takes th( coefficient multiplications howeverif we evaluate both polynomials (at the same points)we can simply multiply the corresponding pairs of values to get the corresponding values for polynomial ab example polynomial ax polynomial
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 work between the two evaluations but we need five points to nail down polynomial ab fortunatelywe can speed processing for any pair of values and - this seems to indicate some promising ways to speed up the process of evaluating polynomials butevaluating two points in roughly the same time as evaluating one point only speeds the process by constant factor is there some way to generalized these observations to speed things up furtherand even if we do find way to evaluate many points quicklywe will also need to interpolate the five values to get the coefficients of ab back so we see that we could multiply two polynomials in less than th( operations if fast way could be found to do evaluation/interpolation of points before considering further how this might be donefirst observe again the relationship between evaluating polynomial at values and - in generalwe can write pa (xea (xoa (xwhere ea is the even powers and oa is the odd powers son/ - / - pa (xa + + = = the significance is that when evaluating the pair of values and -xwe get ea (xoa (xea (xoa (-xoa ( -oa (-xthuswe only need to compute the es and os once instead of twice to get both evaluations the key to fast polynomial multiplication is finding the right points to use for evaluation/interpolation to make the process efficient in particularwe want to take
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 further symmetries between pairs of pairsand so on recall that complex number has real component and an imaginary component we can consider the position of on number line if we use the dimension for the imaginary component nowwe will define primitive nth root of unity if and for - are the nth roots of unity for examplewhen then or - in generalwe have the identities eip - and pij/ - / the significance is that we can find as many points on unit circle as we would need (see figure but these points are special in that they will allow us to do just the right computation necessary to get the needed symmetries to speed up the overall process of evaluating many points at once the next step is to define how the computation is done define an matrix az with row and column as az ( ij the idea is that there is row for each root (row for while the columns correspond to the power of the exponent of the value in the polynomial for examplewhen we have thusthe az array appears as follows - - az - - - - let [ an- ] be vector that stores the coefficients for the polynomial being evaluated we can then do the calculations to evaluate the polynomial
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 still have two problems we need to be able to multiply this matrix times the vector faster than just by performing standard matrix-vector multiplicationotherwise the cost is still multiplies to do the evaluation theneven if we can multiply the two cheaplywe still need to be able to reverse the process that isafter transforming the two input polynomials by evaluating themand then pairwise multiplying the evaluated pointswe must interpolate those points to get the resulting polynomial back that corresponds to multiplying the original input polynomials the interpolation step is nearly identical to the evaluation step fz- - = we need to find - this turns out to be simple to computeand is defined as follows - / in other wordsinterpolation (the inverse transformationrequires the same computation as evaluationexcept that we substitute / for (and multiply by / at the endsoif we can do one fastwe can do the other fast if you examine the example az matrix for you should see that there are symmetries within the matrix for examplethe top half is identical to the
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 function that decomposes the matrix multiplicationstaking advantage of the symmetries made available by doing evaluation at the nth roots of unity the algorithm is as follows fourier_transform(double *polynomialint /compute the fourier transform of polynomial /with degree polynomial is list of /coefficients indexed from to - is /assumed to be power of double even[ / ]odd[ / ]list [ / ]list [ / ]if ( == return polynomial[ ]for ( = <= / - ++even[jpolynomial[ ]odd[jpolynomial[ + ]list fourier_transform(evenn/ )list fourier_transform(oddn/ )for ( = <= - ++imaginary pow( * *pi* / ) ( / )polynomial[jlist [kz*list [ ]return polynomialthusthe full process for multiplying polynomials and using the fourier transform is as follows represent an -degree polynomial as coefficients[ an- perform fourier_transform on the representations for and pairwise multiply the results to get values perform the inverse fourier_transform to get the degree polynomial ab
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 = < () ++in floyd' algorithm which ones give correct algorithm show the result of running floyd' all-pairs shortest-paths algorithm on the graph of figure the implementation for floyd' algorithm given in section is inefficient for adjacency lists because the edges are visited in bad order when initializing array what is the cost of of this initialization step for the adjacency listhow can this initialization step be revised so that it costs th(| | in the worst case state the greatest possible lower bound that you can for the all-pairs shortestpaths problemand justify your answer show the skip list that results from inserting the following values draw the skip list after each insert with each valueassume the depth of its corresponding node is as given in the list value depth if we had linked list that would never be modifiedwe can use simpler approach than the skip list to speed access the concept would remain the same in that we add additional pointers to list nodes for efficient access to the ith element how can we add second pointer to each element of singly linked list to allow access to an arbitrary element in (log ntime
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 algorithm and strassen' matrix multiplication algorithm (see exercise using empirical testingtry to estimate the constant factors for the runtime equations of the two algorithms how big must be before strassen' algorithm becomes more efficient than the standard algorithm
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 asymptotic complexitysuch as floyd' all-pairs shortest-paths algorithmwhose running time is th( we can solve many problems efficiently because we have available (and choose to useefficient algorithms given any problem for which you know some algorithmit is always possible to write an inefficient algorithm to "solvethe problem for exampleconsider sorting algorithm that tests every possible permutation of its input until it finds the correct permutation that provides sorted list the running time for this algorithm would be unacceptably highbecause it is proportional to the number of permutations which is nfor inputs when solving the minimumcost spanning tree problemif we were to test every possible subset of edges to see which forms the shortest minimum spanning treethe amount of work would be proportional to |efor graph with |eedges fortunatelyfor both of these problems we have more clever algorithms that allow us to find answers (relativelyquickly without explicitly testing every possible solution unfortunatelythere are many computing problems for which the best possible algorithm takes long time to run simple example is the towers of hanoi problemwhich requires moves to "solvea tower with disks it is not possible for any computer program that solves the towers of hanoi problem to run in less than ohm( timebecause that many moves must be printed out besides those problems whose solutions must take long time to runthere are also many problems for which we simply do not know if there are efficient algorithms or not the best algorithms that we know for such problems are very
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 theory of expensive and impossible problems section presents the concept of reductionwhich is the central tool used for analyzing the difficulty of problem (as opposed to analyzing the cost of an algorithmreductions allow us to relate the difficulty of various problemswhich is often much easier than doing the analysis for problem from first principles section discusses "hardproblemsby which we mean problems that requireor at least appear to requiretime exponential on the input size finallysection considers various problems thatwhile often simple to define and comprehendare in fact impossible to solve using computer program the classic example of such problem is deciding whether an arbitrary computer program will go into an infinite loop when processing specified input this is known as the halting problem reductions we begin with an important concept for understanding the relationships between problemscalled reduction reduction allows us to solve one problem in terms of another equally importantlywhen we wish to understand the difficulty of problemreduction allows us to make relative statements about upper and lower bounds on the cost of problem (as opposed to an algorithm or programbecause the concept of problem is discussed extensively in this we want notation to simplify problem descriptions throughout this problem will be defined in terms of mapping between inputs and outputsand the name of the problem will be given in all capital letters thusa complete definition of the sorting problem could appear as followssortinginputa sequence of integers xn- outputa permutation yn- of the sequence such that yi <yj whenever once you have bought or written program to solve one problemsuch as sortingyou might be able to use it as tool to solve different problem this is
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 of integers ( xn- and ( yn- outputa pairing of the elements in the two sequences such that the least value in is paired with the least value in ythe next least value in is paired with the next least value in yand so on figure illustrates pairing one way to solve pairing is to use an existing sorting program by sorting each of the two sequencesand then pairing-off items based on their position in sorted order technicallywe say that pairing is reduced to sortingbecause sorting is used to solve pairing notice that reduction is three-step process the first step is to convert an instance of pairing into two instances of sorting the conversion step is not very interestingit simply takes each sequence and assigns it to an array to be passed to sorting the second step is to sort the two arrays ( apply sorting to each arraythe third step is to convert the output of sorting to the output for pairing this is done by pairing the first elements in the sorted arraysthe second elementsand so on the reduction of pairing to sorting helps to establish an upper bound on the cost of pairing in terms of asymptotic notationassuming that we can
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 work to be done to convert from pairing to sortingor to convert the answer from sorting back to the answer for pairingso the dominant cost of this solution is performing the sort operation thusan upper bound for pairing is in ( log nit is important to note that the pairing problem does not require that elements of the two sequences be sorted this is merely one possible way to solve the problem pairing only requires that the elements of the sequences be paired correctly perhaps there is another way to do itcertainly if we use sorting to solve pairingthe algorithms will require ohm( log ntime butanother approach might conceivably be faster there is another use of reductions aside from applying an old algorithm to solve new problem (and thereby establishing an upper bound for the new problemthat is to prove lower bound on the cost of new problem by showing that it could be used as solution for an old problem with known lower bound assume we can go the other way and convert sorting to pairing "fast enough what does this say about the minimum cost of pairingwe know from section that the cost of sorting in the worst and average cases is in ohm( log nin other wordsthe best possible algorithm for sorting requires at least log time assume that pairing could be done in (ntime thenone way to create sorting algorithm would be to convert sorting into pairingrun the algorithm for pairingand finally convert the answer back to the answer for sorting provided that we can convert sorting to/from pairing "fast enough,this process would yield an (nalgorithm for sortingbecause this contradicts what we know about the lower bound for sortingand the only flaw in the reasoning is the initial assumption that pairing can be done in (ntimewe can conclude that there is no (ntime algorithm for pairing this reduction process tells us that pairing must be at least as expensive as sorting and so must itself have lower bound in ohm( log nto complete this proof regarding the lower bound for pairingwe need now to find way to reduce sorting to pairing this is easily done take an instance of sorting ( an array of elementsa second array is generated that simply stores in position for < pass the two arrays to pairing take the resulting set of pairsand use the value from the half of the pair to tell which position in the sorted array the half should takethat iswe can now reorder
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 algorithmis dominated by the cost for pairing consider any two problems for which suitable reduction from one to the other can be found the first problem takes an arbitrary instance of its inputwhich we will call iand transforms to solutionwhich we will call sln the second problem takes an arbitrary instance of its inputwhich we will call and transforms to solutionwhich we will call sln we can define reduction more formally as three-step process transform an arbitrary instance of the first problem to an instance of the second problem in other wordsthere must be transformation from any instance of the first problem to an instance of the second problem apply an algorithm for the second problem to the instance yielding solution sln transform sln to the solution of iknown as sln note that sln must in fact be the correct solution for for the reduction to be acceptable figure shows graphical representation of the general reduction processshowing the role of the two problemsand the two transformations figure shows similar diagram for the reduction of sorting to pairing it is important to note that the reduction process does not give us an algorithm for solving either problem by itself it merely gives us method for solving the first problem given that we already have solution to the second more importantly for the topics to be discussed in the remainder of this reduction gives us way to understand the bounds of one problem in terms of another specificallygiven efficient transformationsthe upper bound of the first problem is at most the upper bound of the second converselythe lower bound of the second problem is at least the lower bound of the first as second example of reductionconsider the simple problem of multiplying two -digit numbers the standard long-hand method for multiplication is to multiply the last digit of the first number by the second number (taking th(ntime)multiply the second digit of the first number by the second number (again taking th(ntime)and so on for each of the digits of the first number finallythe intermediate results are added together note that adding two numbers of length and can easily be done in th( + time because each digit of the first number is multiplied against each digit of the secondthis algorithm requires th( time
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 two -digit numberswe might hope that something about this special case will allow for faster algorithm than is required by the more general multiplication problem howevera simple reduction proof serves to show that squaring is "as hardas multiplying the key to the reduction is the following formulax xy ( ) ( ) the significance of this formula is that it allows us to convert an arbitrary instance of multiplication to series of operations involving three addition/subtractions (each of which can be done in linear time)two squaringsand division by note that the division by can be done in linear time (simply convert to binaryshift right by two digitsand convert backthis reduction shows that if linear time algorithm for squaring can be foundit can be used to construct linear time algorithm for multiplication
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 stored in the matrices are simple integers and that multiplying two simple integers takes constant time (because multiplication of two int variables takes fixed number of machine instructionsthe standard algorithm for multiplying two matrices is to multiply each element of the first matrix' first row by the corresponding element of the second matrix' first columnthen adding the numbers this takes th(ntime each of the elements of the solution are computed in similar fashionrequiring total of th( time faster algorithms are known (see the discussion of strassen' algorithm in section )but none are so fast as to be in ( nowconsider the case of multiplying two symmetric matrices symmetric matrix is one in which entry ij is equal to entry jithat isthe upper-right triangle of the matrix is mirror image of the lower-left triangle is there something about this restricted case that allows us to multiply two symmetric matrices faster than in the general casethe answer is noas can be seen by the following reduction assume that we have been given two matrices and we can construct symmetric matrix from an arbitrary matrix as follows
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 they could be multiplied together in th( time)then we could find the result of multiplying two arbitrary matrices in th( time by taking advantage of the following observationab bt at bt at in the above formulaab is the result of multiplying matrices and together hard problems there are several ways that problem could be considered hard for examplewe might have trouble understanding the definition of the problem itself at the beginning of large data collection and analysis projectdevelopers and their clients might have only hazy notion of what their goals actually areand need to work that out over time for other types of problemswe might have trouble finding or understanding an algorithm to solve the problem understanding spoken english and translating it to written text is an example of problem whose goals are easy to definebut whose solution is not easy to discover but even though natural language processing algorithm might be difficult to writethe program' running time might be fairly fast there are many practical systems today that solve aspects of this problem in reasonable time none of these is what is commonly meant when computer theoretician uses the word "hard throughout this section"hardmeans that the best-known algorithm for the problem is expensive in its running time one example of hard problem is towers of hanoi it is easy to understand this problem and its solution it is also easy to write program to solve this problem butit takes an extremely long time to run for any "reasonablylarge value of try running program to solve towers of hanoi for only disks the transpose operation takes position ij of the original matrix and places it in position ji of the transpose matrix this can easily be done in time for an matrix
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 these equations are constants recall from that if we buy new computer that runs twice as fastthe size of problem with complexity th( that we can solve in certain amount of time is increased by the fourth root of two in other wordsthere is multiplicative factor increaseeven if it is rather small one this is true for any algorithm whose running time can be represented by polynomial consider what happens if you buy computer that is twice as fast and try to solve bigger towers of hanoi problem in given amount of time because its complexity is th( )we can solve problem only one disk biggerthere is no multiplicative factorand this is true for any exponential algorithma constant factor increase in processing power results in only fixed addition in problemsolving power there are number of other fundamental differences between polynomial running times and exponential running times that argues for treating them as qualitatively different polynomials are closed under composition and addition thusrunning polynomial-time programs in sequenceor having one program with polynomial running time call another polynomial number of times yields polynomial time alsoall computers known are polynomially related that isany program that runs in polynomial time on any computer todaywhen transferred to any other computerwill still run in polynomial time there is practical reason for recognizing distinction in practicemost polynomial time algorithms are "feasiblein that they can run reasonably large inputs in reasonable time in contrastmost algorithms requiring exponential time are not practical to run even for fairly modest sizes of input one could argue that program with high polynomial degree (such as is not practicalwhile an exponential-time program with cost is practical but the reality is that we know of almost no problems where the best polynomial-time algorithm has high degree (they nearly all have degree four or less)while almost no exponential-time algorithms (whose cost is ( (cn )have their constant close to one so there is not much gray area between polynomial and exponential time algorithms in practice for the rest of this we define hard algorithm to be one that runs in exponential timethat isin ohm(cn for some constant definition for hard problem will be presented in the next section
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 (or highly parallelcomputer can do anything normal computer can do it might also solve some problems more quickly than normal computer can consider some problem wheregiven guess for solutionchecking the solution to see if it is correct can be done in polynomial time even if the number of possible solutions is exponentialany given guess can be checked in polynomial time (equivalentlyall possible solutions are checked simultaneously in polynomial time)and thus the problem can be solved in polynomial time by our hypothetical magical computer another view of this concept is that if you cannot get the answer to problem in polynomial time by guessing the right answer and then checking itthen you cannot do it in polynomial time in any other way the idea of "guessingthe right answer to problem -or checking all possible solutions in parallel to determine which is correct -is called non-determinism an algorithm that works in this manner is called non-deterministic algorithmand any problem with an algorithm that runs on non-deterministic machine in polynomial time is given special nameit is said to be problem in thusproblems in are those problems that can be solved in polynomial time on non-deterministic machine not all problems requiring exponential time on regular computer are in for exampletowers of hanoi is not in pbecause it must print out ( moves for disks non-deterministic machine cannot "guessand print the correct answer in less time on the other handconsider what is commonly known as the traveling salesman problem traveling salesman ( inputa completedirected graph with positive distances assigned to each edge in the graph outputthe shortest simple cycle that includes every vertex figure illustrates this problem five vertices are shownwith edges and associated costs between each pair of edges (for simplicitywe assume that the cost is the same in both directionsthough this need not be the case if the salesman visits the cities in the order abcdeahe will travel total distance of better
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 would be abedcawith cost we cannot solve this problem in polynomial time with guess-and-test nondeterministic computer the problem is thatgiven candidate cyclewhile we can quickly check that the answer is indeed cycle of the appropriate formand while we can quickly calculate the length of the cyclewe have no easy way of knowing if it is in fact the shortest such cycle howeverwe can solve variant of this problem cast in the form of decision problem decision problem is simply one whose answer is either yes or no the decision problem form of traveling salesman is as followstraveling salesman ( inputa completedirected graph with positive distances assigned to each edge in the graphand an integer outputyes if there is simple cycle with total distance < containing every vertex in gand no otherwise we can solve this version of the problem in polynomial time with non-deterministic computer the non-deterministic algorithm simply checks all of the possible subsets of edges in the graphin parallel if any subset of the edges is an appropriate cycle of total length less than or equal to kthe answer is yesotherwise the answer is no note that it is only necessary that some subset meet the requirementit does not matter how many subsets fail checking particular subset is done in polynomial time by adding the distances of the edges and verifying that the edges form cycle that visits each vertex exactly once thusthe checking algorithm runs in polynomial time unfortunatelythere are |esubsets to checkso this algorithm cannot be converted to polynomial time algorithm on regu
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 problems with this propertywe know efficient non-deterministic algorithmsbut we do not know if there are efficient deterministic algorithms at the same timewe have not been able to prove that any of these problems do not have efficient deterministic algorithms this class of problems is called -complete what is truly strange and fascinating about -complete problems is that if anybody ever finds the solution to any one of them that runs in polynomial time on regular computerthen by series of reductionsevery other problem that is in can also be solved in polynomial time on regular computerdefine problem to be -hard if any problem in can be reduced to in polynomial time thusx is as hard as any problem in problem is defined to be -complete if is in pand is -hard the requirement that problem be -hard might seem to be impossiblebut in fact there are hundreds of such problemsincluding traveling salesman another such problem is called -clique -clique inputan arbitrary undirected graph and an integer outputyes if there is complete subgraph of at least verticesand no otherwise nobody knows whether there is polynomial time solution for -cliquebut if such an algorithm is found for -clique or for traveling salesmanthen that solution can be modified to solve the otheror any other problem in pin polynomial time the primary theoretical advantage of knowing that problem is -complete is that it can be used to show that another problem is -complete this is done by finding polynomial time reduction of to because we already know that all problems in can be reduced to in polynomial time (by the definition of -complete)we now know that all problems can be reduced to as well by the simple algorithm of reducing to and then from there reducing to
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 impossible to doand effort to find polynomial time solution for one -complete problem can be considered to have been expended for all -complete problems how is -completeness of practical significance for typical programmerswellif your boss demands that you provide fast algorithm to solve problemshe will not be happy if you come back saying that the best you could do was an exponential time algorithm butif you can prove that the problem is pcompletewhile she still won' be happyat least she should not be mad at youby showing that her problem is -completeyou are in effect saying that the most brilliant computer scientists for the last years have been trying and failing to find polynomial time algorithm for her problem problems that are solvable in polynomial time on regular computer are said to be in class clearlyall problems in are solvable in polynomial time on non-deterministic computer simply by neglecting to use the non-deterministic capability some problems in are -complete we can consider all problems solvable in exponential time or better as an even bigger class of problems because all problems solvable in polynomial time are solvable in exponential time thuswe can view the world of exponential-time-or-better problems in terms of figure the most important unanswered question in theoretical computer science is whether if they are equalthen there is polynomial time algorithm for traveling salesman and all related problems because traveling salesman is known to be -completeif polynomial time algorithm were to be found for this problemthen all problems in would also be solvable in polynomial time converselyif we were able to prove that traveling salesman has an exponential time lower boundthen we would know that -completeness proofs to start the process of being able to prove problems are -completewe need to prove just one problem is -complete after thatto show that any problem is -hardwe just need to reduce to when doing -completeness proofsit is very important not to get this reduction backwardsif we reduce candidate problem to known hard problem hthis means that we use as step to solving all that means is that we have found (knownhard way to solve
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 be -completeand some are known to be solvable in polynomial time on regular computer howeverwhen we reduce known hard problem to candidate problem xthat means we are using as step to solve and if we know that is hardthat means must also be hard so crucial first step to getting this whole theory off the ground is finding one problem that is -hard the first proof that problem is -hard (and because it is in ptherefore -completewas done by stephen cook for this featcook won the first turing awardwhich is the closest computer science equivalent to the nobel prize the "grand-daddyn -complete problem that cook used is call satisfiability (or sat for shorta boolean expression includes boolean variables combined using the operators and (*)or (+)and not (to negate boolean variable we write xa literal is boolean variable or its negation clause is one or more literals or'ed together let be boolean expression over variables xn then we define conjunctive normal form (cnfto be boolean expression written as series of clauses that are and'ed together for examplee ( ( ( is in cnfand has three clauses now we can define the problem sat
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 decision problem can be recast as some language acceptance problem lf (iyes ( accept that isif decision problem yields yes on input ithen there is language containing string where is some suitable transformation of input converselyif would give answer no for input ithen ' transformed version is not in the language turing machines are simple model of computation for writing programs that are language acceptors there is "universalturing machine that can take as input description for turing machineand an input stringand return the execution of that machine on that string this turing machine in turn can be cast as boolean expression such that the expression is satisfiable if and only if the turing machine yields accept for that string cook used turing machines in his proof because they are simple enough that he could develop this transformation of turing machines to boolean expressionsbut rich enough to be able to compute any function that regular computer can compute the significance of this transformation is that any decision problem that is performable by the turing machine is transformable to sat thussat is -hard as explained aboveto show that decision problem is -completewe prove that is in (normally easyand normally done by giving suitable polynomial-timenondeterministic algorithmand then prove that is -hard to prove that is -hardwe choose known -complete problemsay we describe polynomial-time transformation that takes an arbitrary instance of to an instance of we then describe polynomial-time transformation from to such that is the solution for the following example provides model for how an -completeness proof is done
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 that sat is in pguess (nondeterministicallytruth values for the variables the correctness of the guess can be verified in polynomial time prove that sat is -hardwe need polynomial-time reduction from sat to sat let ck be any instance of sat our strategy is to replace any clause ci that does not have exactly three literals with set of clauses each having exactly three literals (recall that literal can be variable such as xor the negation of variable such as let ci xj where xj are literals so ci replace ci with ci ( ( ( ( zwhere and are variables not appearing in clearlyci is satisfiable if and only if ( is satisfiablemeaning that is true so ci ( replace ci with ( ( zwhere is new variable not appearing in this new pair of clauses is satisfiable if and only if ( is satisfiablethat iseither or must be true replace ci ( xj with ( ( ( *(xj- zj- zj- (xj- xj zj- where zj- are new variables after appropriate replacements have been made for each ci boolean expression results that is an instance of sat each replacement is satisfiable if and only if the original clause is satisfiable the reduction is clearly polynomial time
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 then all clauses in case ( are satisfied if xj are all falsethen zj- are all true but then (xj- xj- zj- is false next we define the problem vertex cover for use in further examples vertex coverinputa graph and an integer outputyes if there is subset of the vertices in of size or less such that every edge of has at least one of its endpoints in sand no otherwise example in this examplewe make use of simple conversion between two graph problems theorem vertex cover is -complete proofprove that vertex cover is in psimply guess subset of the graph and determine in polynomial time whether that subset is in fact vertex cover of size or less prove that vertex cover is -hardwe will assume that kclique is already known to be -complete (we will see this proof in the next example for nowjust accept that it is true given that -clique is -completewe need to find polynomialtime transformation from the input to -clique to the input to vertex coverand another polynomial-time transformation from the output for vertex cover to the output for -clique this turns out to be simple mattergiven the following observation consider graph and vertex cover on denote by the set of vertices in but not in there can be no edge connecting any two vertices in becauseif there werethen would not be vertex cover denote by the inverse graph for gthat isthe graph formed from the edges not in if is of size kthen forms clique of size in graph thuswe can reduce -clique to vertex cover simply by converting graph to and
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 sometimes an -completeness proof involves transformation between types of inputsas shown next theorem -clique is -complete proofk-clique is in pbecause we can just guess collection of vertices and test in polynomial time if it is clique now we show that kclique is -hard by using reduction from sat an instance of sat is boolean expression cm whose clauses we will describe by the notation ci [ [ [iki where ki is the number of literals in clause ci we will transform this to an instance of -clique as follows we build graph { [ij]| < < < <ki }that isthere is vertex in corresponding to every literal in boolean expression we will draw an edge between each pair of vertices [ and [ unless ( they are two literals within the same clause ( or ( they are opposite values for the same variable ( one is negated and the other is notset figure shows an example of this transformation is satisfiable if and only if has clique of size or greater being satisfiable implies that there is truth assignment such that at least one literal [iji is true for each if sothen these literals must correspond to vertices in clique of size converselyif has clique of size or greaterthen the clique must have size exactly (because no two vertices corresponding to literals in the same clause can be in the cliqueand there is one vertex [iji in the clique for each there is truth assignment making each [iji true that truth assignment satisfies we conclude that -clique is -hardtherefore -complete
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 same variable thusthe vertex labeled does not connect to the vertex labeled (because they are literals in the same clauseor the vertex labeled (because they are opposite values for the same variablecoping with -complete problems finding that your problem is -complete might not mean that you can just forget about it traveling salesmen need to find reasonable sales routes regardless of the complexity of the problem what do you do when faced with an -complete problem that you must solvethere are several techniques to try one approach is to run only small instances of the problem for some problemsthis is not acceptable for exampletraveling salesman grows so quickly that it cannot be run on modern computers for problem sizes much over citieswhich is not an unreasonable problem size for real-life situations howeversome other problems in pwhile requiring exponential timestill grow slowly enough that they allow solutions for problems of useful size consider the knapsack problem from section we have dynamic programming algorithm whose cost is th(nkfor objects being fit into knapsack of size but it turns out that knapsack is -complete isn' this contradictionnot when we consider the relationship between and how big is kinput size is typically ( lg kbecause the item sizes are smaller than thusth(nkis exponential on input size
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 solved when given current algorithms second approach to handling -complete problems is to solve special instance of the problem that is not so hard for examplemany problems on graphs are -completebut the same problem on certain restricted types of graphs is not as difficult for examplewhile the vertex cover and -clique problems are -complete in generalthere are polynomial time solutions for bipartite graphs ( graphs whose vertices can be separated into two subsets such that no pair of vertices within one of the subsets has an edge between them satisfiability (where every clause in boolean expression has at most two literalshas polynomial time solution several geometric problems require only polynomial time in two dimensionsbut are -complete in three dimensions or more knapsack is considered to run in polynomial time if the numbers (and kare "small small here means that they are polynomial on nthe number of items in generalif we want to guarantee that we get the correct answer for an pcomplete problemwe potentially need to examine all of the (exponential number ofpossible solutions howeverwith some organizationwe might be able to either examine them quicklyor avoid examining great many of the possible answers in some cases for exampledynamic programming (section attempts to organize the processing of all the subproblems to problem so that the work is done efficiently if we need to do brute-force search of the entire solution spacewe can use backtracking to visit all of the possible solutions organized in solution tree for examplesatisfiability has possible ways to assign truth values to the variables contained in the boolean expression being satisfied we can view this as tree of solutions by considering that we have choice of making the first variable true or false thuswe can put all solutions where the first variable is true on one side of the treeand the remaining solutions on the other we then examine the solutions by moving down one branch of the treeuntil we reach point where we know the solution cannot be correct (such as if the current partial collection of assignments yields an unsatisfiable expressionat this point we backtrack and move back up node in the treeand then follow down the alternate branch if this failswe know to back up further in the tree as necessary and follow alternate branchesuntil finally we either find solution that satisfies the expression or exhaust the
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 through the cities we traverse the solution tree as with backtracking howeverwe remember the best value found so far proceeding down given branch is equivalent to deciding which order to visit cities so any node in the solution tree represents some collection of cities visited so far if the sum of these distances exceeds the best tour found so farthen we know to stop pursuing this branch of the tree at this point we can immediately back up and take another branch if we have quick method for finding good (but not necessarilybest solutionwe can use this as an initial bound value to effectively prune portions of the tree third approach is to find an approximate solution to the problem there are many approaches to finding approximate solutions one way is to use heuristic to solve the problemthat isan algorithm based on "rule of thumbthat does not always give the best answer for examplethe traveling salesman problem can be solved approximately by using the heuristic that we start at an arbitrary city and then always proceed to the next unvisited city that is closest this rarely gives the shortest pathbut the solution might be good enough there are many other heuristics for traveling salesman that do better job some approximation algorithms have guaranteed performancesuch that the answer will be within certain percentage of the best possible answer for exampleconsider this simple heuristic for the vertex cover problemlet be maximal (not necessarily maximummatching in matching pairs vertices (with connecting edgesso that no vertex is paired with more than one partner maximal means to pick as many pairs as possibleselecting them in some order until there are no more available pairs to select maximum means the matching that gives the most pairs possible for given graph if opt is the size of minimum vertex coverthen | < opt because at least one endpoint of every matched edge must be in any vertex cover better example of guaranteed bound on solution comes from simple heuristics to solve the bin packing problem
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 known to be -complete one simple heuristic for solving this problem is to use "first fitapproach we put the first number in the first bin we then put the second number in the first bin if it fitsotherwise we put it in the second bin for each subsequent numberwe simply go through the bins in the order we generated them and place the number in the first bin that fits the number of bins used is no more than twice the sum of the numbersbecause every bin (except perhaps onemust be at least half full howeverthis "first fitheuristic can give us result that is much worse than optimal consider the following collection of numbers of /  of / and of / where is smallpositive number properly organizedthis requires bins but if done wronglywe might end up putting the numbers into bins better heuristic is to use decreasing first fit this is the same as first fitexcept that we keep the bins sorted from most full to least full then when deciding where to put the next itemwe place it in the fullest bin that can hold it this is similar to the "best fitheuristic for memory management discussed in section the significant thing about this heuristic is not just that it tends to give better performance than simple first fit this decreasing first fit heuristic can be proven to require no more than / the optimal number of bins thuswe have guarantee on how much inefficiency can result when using the heuristic the theory of -completeness gives technique for separating tractable from (probablyintractable problems recalling the algorithm for generating algorithms in section we can refine it for problems that we suspect are -complete when faced with new problemwe might alternate between checking if it is tractable (that iswe try to find polynomial-time solutionand checking if it is intractable (we try to prove the problem is -completewhile proving that some problem is -complete does not actually make our upper bound for our algorithm match the lower bound for the problem with certaintyit is nearly as good once we realize that problem is -completethen we know that our next step must either be to redefine the problem to make it easieror else use one of the "copingstrategies discussed in this section
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 at your program and tell you before you run it that it might get into an infinite loopalternativelygiven program and particular inputit would be useful to know if executing the program on that input will result in an infinite loop without actually running the program unfortunatelythe halting problemas this is calledcannot be solved there will never be computer program that can positively determinefor an arbitrary program pif will halt for all input nor will there even be computer program that can positively determine if arbitrary program will halt for specified input how can this beprogrammers look at programs regularly to determine if they will halt surely this can be automated as warning to those who believe any program can be analyzed in this waycarefully examine the following code fragment before reading on while ( if (odd( ) else this is famous piece of code the sequence of values that is assigned to by this code is sometimes called the collatz sequence for input value does this code fragment halt for all values of nnobody knows the answer every input that has been tried halts but does it always haltnote that for this code fragmentbecause we do not know if it haltswe also do not know an upper bound for its running time as for the lower boundwe can easily show ohm(log )(see exercise personallyi have faith that someday some smart person will completely analyze the collatz function and prove once and for all that the code fragment halts for all values of doing so may well give us techniques that advance our ability to do algorithm analysis in general unfortunatelyproofs from computability -the branch of computer science that studies what is impossible to do with computer -compel us to believe that there will always be another bit of program code that we cannot analyze this comes as result of the fact that the halting problem is unsolvable
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 if it is set with infinite membersif every member of the set can be uniquely assigned to positive integer set is said to be uncountable (or uncountably infiniteif it is not possible to assign every member of the set to positive integer to understand what is meant when we say "assigned to positive integer,imagine that there is an infinite row of binslabeled and so on take set and start placing members of the set into binswith at most one member per bin if we can find way to assign all of the members to binsthen the set is countable for exampleconsider the set of positive even integers and so on we can assign an integer to bin / (orif we don' mind skipping some binsthen we can assign even number to bin ithusthe set of even integers is countable this should be no surprisebecause intuitively there are "fewerpositive even integers than there are positive integerseven though both are infinite sets but there are not really any more positive integers than there are positive even integersbecause we can uniquely assign every positive integer to some positive even integer by simply assigning positive integer to positive even integer on the other handthe set of all integers is also countableeven though this set appears to be "biggerthan the set of positive integers this is true because we can assign to positive integer to positive integer - to positive integer to positive integer - to positive integer and so on in generalassign positive integer value to positive integer value iand assign negative integer value - to positive integer value we will never run out of positive integers to assignand we know exactly which positive integer every integer is assigned to because every integer gets an assignmentthe set of integers is countably infinite are the number of programs countable or uncountablea program can be viewed as simply string of characters (including special punctuationspacesand line breakslet us assume that the number of different characters that can appear in program is (using the ascii character setp must be less than but the actual number does not matterif the number of strings is countablethen surely the number of programs is also countable we can assign strings to the bins as follows assign the null string to the first bin nowtake all strings of one characterand assign them to the next bins in "alphabeticor ascii code order nexttake all strings of two charactersand assign them to the next binsagain in ascii code order working from left to right strings of three characters
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 binthe set of all programs is countable naturally most of the strings in the bins are not legal programsbut this is irrelevant all that matters is that the strings that do correspond to programs are also in the bins now we consider the number of possible functions to keep things simpleassume that all functions take single positive integer as input and yield single positive integer as output we will call such functions integer functions function is simply mapping from input values to output values of coursenot all computer programs literally take integers as input and yield integers as output howevereverything that computers read and write is essentially series of numberswhich may be interpreted as letters or something else any useful computer program' input and output can be coded as integer valuesso our simple model of computer input and output is sufficiently general to cover all possible computer programs we now wish to see if it is possible to assign all of the integer functions to the infinite set of bins if sothen the number of functions is countableand it might then be possible to assign every integer function to program if the set of integer functions cannot be assigned to binsthen there will be integer functions that must have no corresponding program imagine each integer function as table with two columns and an infinite number of rows the first column lists the positive integers starting at the second column lists the output of the function when given the value in the first column as input thusthe table explicitly describes the mapping from input to output for each function call this function table next we will try to assign function tables to bins to do so we must order the functionsbut it does not matter what order we choose for examplebin could store the function that always returns regardless of the input value bin could store the function that returns its input bin could store the function that doubles its input and adds bin could store function for which we can see no simple relationship between input and output these four functions as assigned to the first four bins are shown in figure there is no requirement for function to have any discernible relationship between input and output function is simply mapping of inputs to outputswith no constraint on how the mapping is determined
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 the functions we can build new function that has not been assigned to any binas follows take the output value for input from the function in the first bin call this value ( add to itand assign the result as the output of new function for input value regardless of the remaining values assigned to our new functionit must be different from the first function in the tablebecause the two give different outputs for input now take the output value for from the second function in the table (known as ( )add to this value and assign it as the output for in our new function thusour new function must be different from the function of bin because they will differ at least at the second value continue in this mannerassigning fnew (ifi ( for all values thusthe new function must be different from any function fi at least at position this procedure for constructing new function not already in the table is called diagonalization because the new function is different from every other functionit must not be in the table this is true no matter how we try to assign functions to binsand so the number of integer functions is uncountable the significance of this is that not all functions can possibly be assigned to programsso there must be functions with no corresponding program figure illustrates this argument the halting problem is unsolvable while there might be intellectual appeal to knowing that there exists some function that cannot be computed by computer programdoes this mean that there is any such useful functionafter alldoes it really matter if no program can compute "nonsensefunction such as shown in bin of figure now we will prove
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 obviouslyit is not possible to write out something that does not existbut here is plausible sketch of what function to solve the halting problem might look like if it did exist function halt takes two inputsa string representing the source code for program or functionand another string representing the input that we wish to determine if the input program or function halts on function halt does some work to make decision (which is encapsulated into some fictitious function named program haltsfunction halt then returns true if the input program or function does halt on the given inputand false otherwise bool halt(string progstring inputif (program halts(proginput)return trueelse return falsewe now will examine two simple functions that clearly can exist because the complete code for them is presented here
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 whose sole purpose is to execute the function contrary and run that program with itself as inputone possibility is that the call to selfhalt returns truethat isselfhalt claims that contrary will halt when run on itself in that casecontrary goes into an infinite loop (and thus does not halton the other handif selfhalt returns falsethen halt is proclaiming that contrary does not halt on itselfand contrary then returnsthat isit halts thuscontrary does the contrary of what halt says that it will do the action of contrary is logically inconsistent with the assumption that halt solves the halting problem correctly there are no other assumptions we made that might cause this inconsistency thusby contradictionwe have proved that halt cannot solve the halting problem correctlyand thus there is no program that can solve the halting problem now that we have proved that the halting problem is unsolvablewe can use reduction arguments to prove that other problems are also unsolvable the strategy is to assume the existence of computer program that solves the problem in question and use that program to solve another problem that is already known to be unsolvable example consider the following variation on the halting problem given computer programwill it halt when its input is the empty string ( will it halt when it is given no input)to prove that this problem is unsolvablewe will employ standard technique for computability proofsuse computer program to modify another computer program proofassume that there is function ehalt that determines whether given program halts when given no input recall that our proof for the halting problem involved functions that took as parameters string representing program and another string representing an input consider
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 compiler could be modified to take computer programs and input strings and produce new computer program that has been modified in this way nowtake and feed it to ehalt if ehalt says that will haltthen we know that would halt on input in other wordswe now have procedure for solving the original halting problem the only assumption that we made was the existence of ehalt thusthe problem of determining if program will halt on no input must be unsolvable example for arbitrary program pdoes there exist any input for which haltsproofthis problem is also uncomputable assume that we had function ahalt thatwhen given program as input would determine if there is some input for which halts we could modify our compiler (or write function as part of programto take and some input string wand modify it so that is hardcoded inside pwith reading no input call this modified program nowp always behaves the same way regardless of its inputbecause it ignores all input howeverbecause is now hardwired inside of the behavior we get is that of when given as input sop will halt on any arbitrary input if and only if would halt on input we now feed to function ahalt if ahalt could determine that halts on some inputthen that is the same as determining that halts on input but we know that that is impossible thereforeahalt cannot exist there are many things that we would like to have computer do that are unsolvable many of these have to do with program behavior for exampleproving that an arbitrary program is "correct,that isproving that program computes particular functionis proof regarding program behavior as suchwhat can be accomplished is severely limited some other unsolvable problems includedoes program halt on every inputdoes program compute particular functiondo two programs compute the same functiondoes particular line in program get executed
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 compiler will issue warning that the while loop code will never be executed howeverit is not possible to write computer program that can check for all input programs whether specified line of code will be executed when the program is given some specified input another unsolvable problem is whether program contains computer virus the property "contains computer virusis matter of behavior thusit is not possible to determine positively whether an arbitrary program contains computer virus fortunatelythere are many good heuristics for determining if program is likely to contain virusand it is usually possible to determine if program contains particular virusat least for the ones that are now known real virus checkers do pretty good jobbutit will always be possible for malicious people to invent new viruses that no existing virus checker can recognize further reading the classic text on the theory of -completeness is computers and intractabilitya guide to the theory of -completeness by garey and johnston [gj the traveling salesman problemedited by lawler et al [llks ]discusses many approaches to finding an acceptable solution to this particular -complete problem in reasonable amount of time for more information about the collatz function see "on the ups and downs of hailstone numbersby hayes [hay ]and "the problem and its generalizationsby lagarias [lag for an introduction to the field of computability and impossible problemssee discrete structureslogicand computability by james hein [hei exercises consider this algorithm for finding the maximum element in an arrayfirst sort the array and then select the last (maximumelement what (if anythingdoes this reduction tell us about the upper and lower bounds to the problem of finding the maximum element in sequencewhy can we not reduce sorting to finding the maximum element use reduction to prove that squaring an matrix is just as expensive (asymptoticallyas multiplying two matrices
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 the factorial of by making use of stirling' formula (see section is polynomial time algorithm consider this algorithm for solving the -clique problem firstgenerate all subsets of the vertices containing exactly vertices there are (nk such subsets altogether thencheck whether any subgraphs induced by these subsets is complete if this algorithm ran in polynomial timewhat would be its significancewhy is this not polynomial-time algorithm for the kclique problem write the sat expression obtained from the reduction of sat to sat described in section for the expression ( ( ( ( ( (bis this expression satisfiable draw the graph obtained by the reduction of sat to the -clique problem given in section for the expression ( ( ( ( cis this expression satisfiable hamiltonian cycle in graph is cycle that visits every vertex in the graph exactly once before returning to the start vertex the problem hamiltonian cycle asks whether graph does in fact contain hamiltonian cycle assuming that hamiltonian cycle is -completeprove that the decision-problem form of traveling salesman is -complete use the assumption that vertex cover is -complete to prove that kclique is also -complete by finding polynomial time reduction from vertex cover to -clique we define the problem independent set as follows
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 followspartition inputa collection of integers outputyes if the collection can be split into two such that the sum of the integers in each partition sums to the same amount no otherwise (aassuming that partition is -completeprove that the decision form of bin packing is -complete (bassuming that partition is -completeprove that knapsack is -complete imagine that you have problem that you know is -complete for this problem you have two algorithms to solve it for each algorithmsome problem instances of run in polynomial time and others run in exponential time (there are lots of heuristic-based algorithms for real -complete problems with this behavioryou can' tell beforehand for any given problem instance whether it will run in polynomial or exponential time on either algorithm howeveryou do know that for every problem instanceat least one of the two algorithms will solve it in polynomial time (awhat should you do(bwhat is the running time of your solution(cwhat does it say about the question of if the conditions described in this problem existed here is another version of the knapsack problemwhich we will call exact knapsack given set of items each with given integer sizeand knapsack of size integer kis there subset of the items which fits exactly within the knapsackassuming that exact knapsack is -completeuse reduction argument to prove that knapsack is -complete
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 of real numbers is uncountable use proof similar to the proof in section that the set of integer functions is uncountable proveusing reduction argument such as given in section that the problem of determining if an arbitrary program will print any output is unsolvable proveusing reduction argument such as given in section that the problem of determining if an arbitrary program executes particular statement within that program is unsolvable proveusing reduction argument such as given in section that the problem of determining if two arbitrary programs halt on exactly the same inputs is unsolvable proveusing reduction argument such as given in section that the problem of determining whether there is some input on which two arbitrary programs will both halt is unsolvable proveusing reduction argument such as given in section that the problem of determining whether an arbitrary program halts on all inputs is unsolvable proveusing reduction argument such as given in section that the problem of determining whether an arbitrary program computes specified function is unsolvable consider program named comp that takes two strings as input it returns true if the strings are the same it returns false if the strings are different why doesn' the argument that we used to prove that program to solve the halting problem does not exist work to prove that comp does not exist projects implement vertex coverthat isgiven graph and integer kanswer the question of whether or not there is vertex cover of size or less begin by using brute-force algorithm that checks all possible sets of vertices of size to find an acceptable vertex coverand measure the running time on number of input graphs then try to reduce the running time through the use of any heuristics you can think of nexttry to find approximate solutions to
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 with costs for all edgesfind the cheapest cycle that visits all vertices in try various heuristics to find the best approximations for wide variety of input graphs write program thatgiven positive integer as inputprints out the collatz sequence for that number what can you say about the types of integers that have long collatz sequenceswhat can you say about the length of the collatz sequence for various types of integers
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 jeffrey ullman the design and analysis of computer algorithms addison-wesleyreadingma alfred ahojohn hopcroftand jeffrey ullman data structures and algorithms addison-wesleyreadingma brassard and bratley fundamentals of algorithmics prentice hallupper saddle rivernj john louis bentley multidimensional binary search trees used for associative searching communications of the acm ( ): - september issn - john louis bentley writing efficient programs prentice hallupper saddle rivernj john louis bentley programming pearlsthe back of the envelope communications of the acm ( ): - march john louis bentley programming pearlsthanksheaps communications of the acm ( ): - march john louis bentley programming pearlsthe envelope is back communications of the acm ( ): - march john bentley more programming pearlsconfessions of coder addison-wesleyreadingma john bentley programming pearls addison-wesleyreadingmasecond edition
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 mythical man-monthessays on software engineering th anniversary edition addison-wesleyreadingma [bstw john louis bentleydaniel sleatorrobert tarjanand victor wei locally adaptive data compression scheme communications of the acm ( ): - april [clrs thomas cormencharles leisersonronald rivestand clifford stein introduction to algorithms the mit presscambridgemasecond edition [com douglas comer the ubiquitous -tree computing surveys ( ): - june [ecw vladimir estivill-castro and derick wood survey of adaptive sorting algorithms computing surveys ( ): - december [ed enbody and du dynamic hashing schemes computing surveys ( ): - june [epp susanna epp discrete mathematics with applications brooks/cole publishing companypacific grovecathird edition [fby frakes and baeza-yateseditors information retrievaldata structures algorithms prentice hallupper saddle rivernj [ff daniel friedman and matthias felleisen the little lisper macmillan publishing companynew york [fhcd edward foxlenwood heathq chenand amjad daoud practical minimal perfect hash functions for large databases communications of the acm ( ): - january [fl scott folger and steven leblanc strategies for creative problem solving prentice hallupper saddle rivernj [fla david flanagan java in nutshell 'reilly associatesinc sebatopolca th edition [fz folk and zoellick file structuresan object-oriented approach with +addison-wesleyreadingmathird edition [ghjv erich gammarichard helmralph johnsonand john vlissides design patternselements of reusable object-oriented software addison-wesleyreadingma
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 york ronald grahamdonald knuthand oren patashnik concrete mathematicsa foundation for computer science addison-wesleyreadingmasecond edition james gleick geniusthe life and science of richard feynman vintagenew york antonin guttman -treesa dynamic index structure for spatial searching in yormarkeditorannual meeting acm sigmodpages - bostonmajune hayes computer recreationson the ups and downs of hailstone numbers scientific american ( ): - january james hein discrete structureslogicand computability jones and bartlettsudburymasecond edition julian jaynes the origin of consciousness in the breakdown of the bicameral mind houghton mifflinbostonma dennis kafura object-oriented software design and construction with +prentice hallupper saddle rivernj donald knuth the stanford graphbase addison-wesleyreadingma donald knuth the art of computer programmingfundamental algorithmsvolume addison-wesleyreadingmathird edition donald knuth the art of computer programmingsorting and searchingvolume addison-wesleyreadingmasecond edition charles kozierok the pc guide www pcguide com brian kernighan and rob pike the practice of programming addison-wesleyreadingma lagarias the + problem and its generalizations the american mathematical monthly ( ): - january marvin levine effective problem solving prentice hallupper saddle rivernjsecond edition
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 pressprincetonnjsecond edition [pug pugh skip listsa probabilistic alternative to balanced trees communications of the acm ( ): - june [raw gregory rawlins compared to whatan introduction to the analysis of algorithms computer science pressnew york [rie arthur riel object-oriented design heuristics addison-wesleyreadingma [rob fred roberts applied combinatorics prentice hallupper saddle rivernj [rob eric roberts thinking recursively john wiley sonsnew york [rw chris ruemmler and john wilkes an introduction to disk drive modeling ieee computer ( ): - march [sal betty salzberg file structuresan analytic approach prentice hallupper saddle rivernj [sam hanan samet foundations of multidimensional and metric data structures morgan kaufmannsan franciscoca [sb clifford shaffer and patrick brown paging scheme for pointer-based quadtrees in abel and - ooieditorsadvances in spatial databasespages - springer verlagberlinjune [sed robert sedgewick quicksort garland publishinginc new york [sed robert sedgewick algorithms addison-wesleyreadingmathird edition [sel kevin self technically speaking ieee spectrum ( ): february [sh clifford shaffer and gregory herb real-time robot arm collision avoidance system ieee transactions on robotics ( ): - [sjh clifford shafferramana juvvadiand lenwood heath generalized comparison of quadtree and bintree storage requirements image and vision computing ( ): - september
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 sleator and robert tarjan self-adjusting binary search trees journal of the acm : - william stallings operating systemsinternals and design principles prentice hallupper saddle rivernjfifth edition richard stallman gnu emacs manual free software foundationcambridgemasixteenth edition guy steele common lispthe language digital pressbedfordma james storer data compressionmethods and theory computer science pressrockvillemd clifford shaffer and mahesh ursekar large scale editing and vector to raster conversion via quadtree spatial indexing in proceedings of the th international symposium on spatial data handlingpages - august murali sitaraman and bruce weide special featurecomponentbased software using resolve software engineering notes ( ): october murali sitaramanlonnie welchand douglas harms on specification of reusable software components international journal of software engineering and knowledge engineering ( ): - june andrew tanenbaum structured computer organization prentice hallupper saddle rivernjfifth edition robert tarjan on the efficiency of good but not linear set merging algorithm journal of the acm ( ): - april pete thomashugh robinsonand judy emms abstract data typestheir specificationrepresentationand use clarendon pressoxford dominic welsh codes and cryptography oxford university pressoxford arthur whimbey and jack lochhead problem solving comprehension lawrence erlbaum associatesmahwahnjsixth edition
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 asymptotic - empirical comparison - for program statements - multiple parameters - running time measures space requirements - all-pairs shortest paths - amortized analysis - approximation array dynamic implementation artificial intelligence assertxvii assertxvii asymptotic analysissee algorithm analysisasymptotic atm machine average-case analysis - avl tree - back of the envelopenapkinsee estimating backtracking bag bank - basic operation
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 traversalbinary tree binsort - bintree birthday problem block boolean expression clause conjunctive normal form literal boolean variable branch and bounds breadth-first search - bstxv - - - - index efficiency insert - remove - search - search tree property traversalsee traversal -tree - analysis - -tree - -tree bubble sort - buffer poolxv - - adt - replacement schemes - - cache - cd-rom cd-rom ceiling function city database class see object-oriented programmingclass clique cluster problem clusterfile code tuning - - - collatz sequence comparatorxiv compiler activation record efficiency optimization complexity
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 - selecting - spatialsee spatial data structure data type decision problem decision tree - decomposition image space key space object space depth-first search - deque dequeuesee queuedequeue design patternxiv - composite - flyweight - - strategy visitor - deutsch-schorr-waite algorithm dictionary - adt - dijkstra' algorithm - diminishing increment sortsee shellsort directed acyclic graph (dag) discrete mathematicsxv disjoint setsee equivalence class disk drive - access cost - cylinder organization - disk processingsee file processing divide and conquer - document retrieval double buffering dynamic arraysee arraydynamic dynamic memory allocation dynamic programming efficiencyxiii - / rule element homogeneity implementation - emacs text editor encapsulation enqueuesee queueenqueue entry-sequenced file enumerationsee traversal equationrepresentation equivalence - class - -
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 managementfirst fit floor function floppy disk drive floyd' algorithm - flyweightsee design patternflyweight fragmentation - external internal free list free store free tree freelist full binary tree theorem - functionmathematical garbage collection general tree - index adt - converting to binary tree dynamic implementations implementation - left-child/right-sibling list of children - parent pointer implementation - terminology - traversalsee traversal geographic information system geometric distribution gigabyte graphxv - adjacency matrix adjacency list adjacency matrix adt connected component edge implementation - modeling of problems representation - terminology - traversalsee traversalgraph undirected vertex greatest common divisorsee largest common factor greedy algorithm growth rate - asymptotic -
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 sequence - pseudo-random probing quadratic probing search table tombstone header node heap - - building - for memory management insert max-heap min-heap partial ordering property remove siftdown - heapsort heapsort - heuristic - hidden obligationssee obligationshidden huffman coding tree - - prefix property independent set index - file inverted list linear - tree - induction - - - inductionproof bysee proofinduction inheritance see object-oriented programminginheritance inorder traversalsee traversalinorder input size insertion sort - - - - double
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 searchsee searchsequential linksee listlink class linked listsee listlinked lisp list - adt - append array-based - - basic operations circular comparison of space requirements current position - index doubly linked - space - element - freelist - - head implementations compared - initialization insert - link class - linked - - node - notation ordered by frequency - orthogonal remove - search - self-organizingxv - - singly linked sorted - space requirements - tail terminology unsorted locality of reference logarithm - log
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 presentations resource for teaching data structures and algorithms this book contains many java-code and pseudo-code fragmentsand over exerciseswhich are divided into roughly reinforcement exercises creativity exercisesand programming projects this book can be used for courses cs ( / / versions)cs ( / / versions)cs ( version)and/or cs ( / / / / versionsin the ieee/acm computing curriculumwith instructional units as outlined in table table material for units in the ieee/acm computing curriculum instructional unit relevant material pl overview of programming languages pl virtual machines sections pl introduction to language translation section pl declarations and types sections pl abstraction mechanisms sections
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 and ds functionsrelationsand sets sections ds proof techniques 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 and algorithm analysisand then presents the fundamental data structures and algorithmsconcluding with discussion of memory management (that isthe architectural underpinnings of data structuresspecificallythe for this book are organized as follows java programming basics object-oriented design arrayslinked listsand recursion analysis tools stacks and queues lists and iterators trees priority queues maps and dictionaries search trees sortingsetsand selection text processing graphs
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-level languageincludingvariables and expressions methods (also known as functions or proceduresdecision structures (such as if-statements and switch-statementsiteration structures (for-loops and while-loopsfor readers who are familiar with these conceptsbut not with how they are expressed in javawe provide primer on the java language in stillthis book is primarily data structures booknot java bookhenceit does not provide comprehensive treatment of java neverthelesswe do not assume that the reader is necessarily familiar with object-oriented design or with linked structuressuch as linked listsfor these topics are covered in the core of this book in terms of mathematical backgroundwe assume the reader is somewhat familiar with topics from high-school mathematics even soin we discuss the seven most-important functions for algorithm analysis in factsections that use something other than one of these seven functions are considered optionaland are indicated with star we give summary of other useful mathematical factsincluding elementary probabilityin appendix about the authors professors goodrich and tamassia are well-recognized researchers in algorithms and data structureshaving published many papers in this fieldwith applications to internet computinginformation visualizationcomputer securityand geometric computing they have served as principal investigators in several joint projects sponsored by the national science foundationthe army research officeand the
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 editor for the international journal of computational geometry applications and journal of graph algorithms and applications roberto tamassia received his ph in electrical and computer engineering from the university of illinois at urbana-champaign in he is currently professor in the department of computer science at brown university he is editor-in-chief for the journal of graph algorithms and applications and an editor for computational geometrytheory and applications he previously served on the editorial board of ieee transactions on computers in addition to their research accomplishmentsthe authors also have extensive experience in the classroom for exampledr goodrich has taught data structures and algorithms coursesincluding data structures as freshman-sophomore level course and introduction to algorithms as an upper level course he has earned several teaching awards in this capacity his teaching style is to involve the students in lively interactive classroom sessions that bring out the intuition and insights behind data structuring and algorithmic techniques dr tamassia has taught data structures and algorithms as an introductory freshman-level course since one thing that has set his teaching style apart is his effective use of interactive hypermedia presentations integrated with the web the instructional web sitesdatastructures net and algorithmdesign netsupported by drs goodrich and tamassiaare used as reference material by studentsteachersand professionals worldwide acknowledgments there are number of individuals who have made contributions to this book we are grateful to all our research collaborators and teaching assistantswho provided feedback on early drafts of and have helped us in developing exercisesprogramming assignmentsand algorithm animation systems in particularwe would like to thank jeff achtervesselin arnaudovjames bakerryan baker,benjamin boermike boilendevin borlandlubomir bourdevstina bridgemanbryan cantrillyi-jen chiangrobert cohendavid ellisdavid emoryjody fantoben finkelashim gargnatasha gelfandmark handymichael hornbeno^it hudsonjovanna ignatowiczseth padowitzjames piechotadan polivyseth proctorsusannah raubharu sakaiandy schwerinmichael shapiromikeshimmichael shingalina shubinachristian straubye
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 datastructures library of data structures and algorithms in java we are also grateful to vesselin arnaudov and ike shim for testing the current version of net datastructures many students and instructors have used the two previous editions of this book and their experiences and responses have helped shape this fourth edition there have been number of friends and colleagues whose comments have lead to improvements in the text we are particularly thankful to karen goodrichart moorsheaddavid mountscott smithand ioannis tollis for their insightful comments in additioncontributions by david mount to section and to several figures are gratefully acknowledged we are also truly indebted to the outside reviewers and readers for their copious commentsemailsand constructive criticismwhich were extremely useful in writing the fourth edition we specifically thank the following reviewers for their comments and suggestionsdivy agarwaluniversity of californiasanta barbaraterry andresuniversity of manitobabobby blumofeuniversity of texasaustinmichael clancyuniversity of californiaberkeleylarry davisuniversity of marylandscott drysdaledartmouth collegearup guhauniversity of central floridachris ingramuniversity of waterloostan kwasnywashington universitycalvin linuniversity of texas at austinjohn mark mercermcgill universitylaurent micheluniversity of connecticutleonard myerscalifornia polytechnic state universitysan luis obispodavid naumannstevens institute of technologyrobert pastelmichigan technological universitybina ramamurthysuny buffaloken slonnegeruniversity of iowac ravishankaruniversity of michiganval tannenuniversity of pennsylvaniapaul van arragonmessiah collegeand christopher wilsonuniversity of oregon the team at wiley has been great many thanks go to lilian bradypaul crockettsimon durkinlisa geefrank lymanmadelyn lesurehope millerbridget morriseyken santordan sayrebruce spatzdawn stanleyjeri warnerand bill zobrist the computing systems and excellent technical support staff in the departments of computer science at brown university and university of californiairvine gave us reliable working environments this manuscript was prepared primarily with the
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 writing books michael goodrich roberto tamassia java programming basics contents
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 reader is somewhat familiar with an existing high-level language this book does not provide complete description of the java languagehowever there are major aspects of the language that are not directly relevant to data structure designwhich are not included heresuch as threads and sockets for the reader interested in learning more about javaplease see the notes at the end of this we begin with program that prints "hello universe!on the screenwhich is shown in dissected form in figure figure "hello universe!program
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 now)data of java objects are stored in instance variables (also called fieldsthereforeif an object from some class is to store dataits class must specify the instance variables for such objects instance variables can either come from base types (such as integersfloating-point numbersor booleansor they can refer to objects of other classes the operations that can act on dataexpressing the "messagesobjects respond toare called methodsand these consist of constructorsproceduresand functions they define the behavior of objects from that class how classes are declared in shortan object is specific combination of data and the methods that can process and communicate that data classes define the types for objectshenceobjects are sometimes referred to as instances of their defining classbecause they take on the name of that class as their type an example definition of java class is shown in code fragment code fragment counter class for simple counterwhich can be accessedincrementedand decremented
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 in the constructor methodcounterwhich is called when we wish to create new counter object (this method always has the same name as the class it belongs tothis class also has one accessor methodgetcountwhich returns the current value of the counter finallythis class has two update methods-- methodincrementcountwhich increments the counterand methoddecrementcountwhich decrements the counter admittedlythis is pretty boring classbut at least it shows us the syntax and structure of java class it also shows us that java class does not have to have main method (but such class can do nothing by itselfthe name of classmethodor variable in java is called an identifierwhich can be any string of characters as long as it begins with letter and consists of lettersnumbersand underscore characters (where "letterand "numbercan be from any written language defined in the unicode character setwe list the exceptions to this general rule for java identifiers in table table listing of the reserved words in java these names cannot be used as method or variable names in java reserved words abstract
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 methoda class that has nothing but abstract methods and no instance variables is more properly called an interface (see section )so an abstract class usually has mixture of abstract methods and actual methods (we discuss abstract classes and their uses in section the final class modifier describes class that can have no subclasses (we will discuss this concept in the next the public class modifier describes class that can be instantiated or extended by anything in the same package or by anything that imports the class (this is explained in more detail in section public classes are declared in their own separate file called classname javawhere "classnameis the name of the class if the public class modifier is not usedthe class is considered friendly this means that it can be used and instantiated by all classes in the same package this is the default class modifier base types the types of objects are determined by the class they come from for the sake of efficiency and simplicityjava also has the following base types (also called primitive types)which are not objectsboolean boolean valuetrue or false char -bit unicode character byte -bit signed two' complement integer short -bit signed two' complement integer
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 followed immediately by an 'lor ' 'in which case they are of type long floating-point constantslike or are of type doubleunless followed immediately by an 'for ' 'in which case they are of type float we show simple class in code fragment that defines number of base types as local variables for the main method code fragment base class showing example uses of base types
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 particular note is comment that begins with /**for such comments have special format that allows program called javadoc to read these comments and automatically generate documentation for java programs we discuss the syntax and interpretation of javadoc comments in section in addition to block commentsjava uses /to begin inline comments and ignores everything else on the line all comments shown in this book will be colored blueso that they are not confused with executable code for example/this is block comment *
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 examplethe counter class (code fragment had single instance variable that was of type int another nice feature of base types in java is that base-type instance variables are always given an initial value when an object containing them is created (either zerofalseor null characterdepending on the typeobjects in javaa new object is created from defined class by using the new operator the new operator creates new object from specified class and returns reference to that object in order to create new object of certain typewe must immediately follow our use of the new operator by call to constructor for that type of object we can use any constructor that is included in the class definitionincluding the default constructor (which has no arguments between the parenthesesin figure we show number of dissected example uses of the new operatorboth to simply create new objects and to assign the reference to these objects to variable figure example uses of the new operator
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 constructor fills in meaningful values for the instance variables and performs any additional computations that must be done to create this object after the constructor returnsthe new operator returns reference (that isa memory addressto the newly created object if the expression is in the form of an assignment statementthen this address is stored in the object variableso the object variable refers to this newly created object number objects we sometimes want to store numbers as objectsbut base type numbers are not themselves objectsas we have noted to get around this obstaclejava defines wrapper class for each numeric base type we call these classes number classes in table we show the numeric base types and their corresponding number classalong with examples of how number objects are created and accessed since java creation operation is performed automatically any time we pass base number to method expecting corresponding object likewisethe
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 creation example access example byte byte new byte((byte) ) bytevalueshort short new short((short) ) shortvalueint integer new integer( ) intvaluelong long new long( )
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 before in (so the first character is at index in javathe alphabet used to define strings is the unicode international character seta -bit character encoding that covers most used written languages other programming languages tend to use the smaller ascii character set (which is proper subset of the unicode alphabet based on -bit encodingin additionjava defines special built-in class of objects called string objects for examplea string could be "hogs and dogs"which has length and could have come from someone' web page in this casethe character at index is 'gand the character at index is 'aalternatelyp could be the string "cgtaatagttaatccg"which has length and could have come from scientific application for dna sequencingwhere the alphabet is {gcatconcatenation string processing involves dealing with strings the primary operation for combining strings is called concatenationwhich takes string and string combines them into new stringdenoted qwhich consists of all the characters of followed by all the characters of in javathe "+operation
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 to have built-in method tostring(that returns string associated with the object this description of the string class should be sufficient for most uses we discuss the string class and its "relativethe stringbuffer class in more detail in section object references as mentioned abovecreating new object involves the use of the new operator to allocate the object' memory space and use the object' constructor to initialize this space the locationor addressof this space is then typically assigned to reference variable thereforea reference variable can be viewed as "pointerto some object it is as if the variable is holder for remote control that can be used to control the newly created object (the devicethat isthe variable has way of pointing at the object and asking it to do things or give us access to its data we illustrate this concept in figure figure illustrating the relationship between objects and object reference variables when we assign an object reference (that ismemory addressto reference variableit is as if we are storing that object' remote control at that variable
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 objectand each reference to specific object can be used to call methods on that object such situation would correspond to our having many remote controls that all work on the same device any of the remotes can be used to make change to the device (like changing channel on televisionnote that if one remote control is used to change the devicethen the (singleobject pointed to by all the remotes changes likewiseif we use one object reference variable to change the state of the objectthen its state changes for all the references to it this behavior comes from the fact that there are many referencesbut they all point to the same object one of the primary uses of an object reference variable is to access the members of the class for this objectan instance of its class that isan object reference variable is useful for accessing the methods and instance variables associated with an object this access is performed with the dot ("operator we call method associated with an object by using the reference variable namefollowing that by the dot operator and then the method name and its parameters this calls the method with the specified name for the object referred to by this object reference it can optionally be passed multiple parameters if there are several methods with this same name defined for this objectthen the java runtime system uses the one that matches the number of parameters and most closely matches their respective types method' name combined with the number and types of its parameters is called method' signaturefor it takes all
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 returnsso java does not allow two methods with the same signature to return different types instance variables java classes can define instance variableswhich are also called fields these variables represent the data associated with the objects of class instance variables must have typewhich can either be base type (such as intfloatdoubleor reference type (as in our remote control analogy)that isa classsuch as string an interface (see section )or an array (see section base-type instance variable stores the value of that base typewhereas an instance variable declared with class name stores reference to an object of that class continuing our analogy of visualizing object references as remote controlsinstance variables are like device parameters that can be read or set from the remote control (such as the volume and channel controls on television remote controlgiven reference variable vwhich points to some object owe can access any of the instance variables for that the access rules allow for examplepublic instance variables are accessible by everyone using the dot operator we can get the value of any such instance variableijust by using in an arithmetic expression likewisewe can set the value of any such instance variable,iby writing on the left-hand side of the assignment operator ("="(see figure for exampleif gnome refers to gnome object that has public instance variables name and agethen the following statements are allowedgnome name "professor smythe"gnome age alsoan object reference does not have to only be reference variable it can also be any expression that returns an object reference figure illustrating the way an object reference can be used to get and set instance variables in an
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 cannot be accessed directly from remote control for examplesome devices have internal parameters that can only be read or assigned by factory technician (and user is not allowed to change those parameters without violating the device' warrantywhen we declare an instance variablewe can optionally define such variable modifierfollow that by the variable' type and the identifier we are going to use for that variable additionallywe can optionally assign an initial value to the variable (using the assignment operator ("="the rules for variable name are the same as any other java identifier the variable type parameter can be either base typeindicating that this variable stores values of this typeor class nameindicating that this variable is reference to an object from this class finallythe optional initial value we might assign to an instance variable must match the variable' type for examplewe could define gnome classwhich contains several definitions of instance variablesshown in in code fragment
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 usedthe instance variable is considered friendly friendly instance variables can be accessed by any class in the same package packages are discussed in more detail in section in addition to scope variable modifiersthere are also the following usage modifiersstaticthe static keyword is used to declare variable that is associated with the classnot with individual instances of that class static variables are used to store "globalinformation about class (for examplea static variable could be used to maintain the total number of gnome objects createdstatic variables exist even if no instance of their class is created finala final instance variable is one that must be assigned an initial valueand then can never be assigned new value after that if it is base typethen it is constant (like the max_height constant in the gnome classif an object variable is finalthen it will always refer to the same object (even if that object changes its internal statecode fragment the gnome class
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_name - }where the modifier can be blankpublicprotectedor private the name of this enumnamecan be any legal java identifier each of the value identifiersvaluenameiis the name of possible value that variables of this enum type can take on each of these name values can also be any legal java identifierbut the java convention is that these should usually be capitalized words for examplethe following enumerated type definition might be useful in program that must deal with datespublic enum day montuewedthufrisatsun }once definedwe can use an enum typesuch as thisto define other variablesmuch like class name but since java knows all the value names for an enumerated typeif we use an enum type in string expressionjava will automatically use its name enum types also have few built-in methodsincluding method valueofwhich returns the enum value that is the same as given string we show an example use of an enum type in code fragment code fragment type an example use of an enum
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 parameters that are passed every method in java is specified in the body of some class method definition has two partsthe signaturewhich defines the and parameters for methodand the bodywhich defines what the method does method allows programmer to send message to an object the method signature specifies how such message should look and the method body specifies what the object will do when it receives such message declaring methods the syntax for defining method is as followsmodifiers type name(type parameter type - parameter - /method body
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 list of parameters and their types declares the local variables that correspond to the values that are to be passed as arguments to this method each type declaration type can be any java type name and each parameter can be any java identifier this list of parameters and their types can be emptywhich signifies that there are no values to be passed to this method when it is invoked these parameter variablesas well as the instance variables of the classcan be used inside the body of the method likewiseother methods of this class can be called from inside the body of method when method of class is calledit is invoked on specific instance of that class and can change the state of that object (except for static methodwhich is associated with the class itselffor exampleinvoking the following method on particular gnome changes its name public void renamegnome (string sname /reassign the name instance variable of this gnome method modifiers as with instance variablesmethod modifiers can restrict the scope of methodpublicanyone can call public methods protectedonly methods of the same package or of subclasses can call protected method privateonly methods of the same class (not methods of subclasscan call private method if none of the modifiers above are usedthen the method is friendly friendly methods can only be called by objects of classes in the same package the above modifiers may be preceded by additional modifiersabstracta method declared as abstract has no code the signature of such method is followed by semicolon with no method body for examplepublic abstract void setheight (double newheight)
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 variables are not declared to be finalreturn types method definition must specify the type of value the method will return if the method does not return valuethen the keyword void must be used if the return type is voidthe method is called procedureotherwiseit is called function to return value in javaa method must use the return keyword (and the type returned must match the return type of the methodhere is an example of method (from inside the gnome classthat is functionpublic booleanismagical (returnmagicalas soon as return is performed in java functionthe method ends java functions can return only one value to return multiple values in javawe should instead combine all the values we wish to return in compound objectwhose instance variables include all the values we want to returnand then return reference to that compound object in additionwe can change the internal state of an object that is passed to method as another way of "returningmultiple results parameters method' parameters are defined in comma-separated list enclosed in parentheses after the name of the method parameter consists of two partsthe parameter type and the parameter name if method has no parametersthen only an empty pair of parentheses is used all parameters in java are passed by valuethat isany time we pass parameter to methoda copy of that parameter is made for use within the method body so if we pass an int variable to methodthen that variable' integer value is copied the method can change the copy but not the original if we pass an object reference as parameter to methodthen the reference is copied as well remember that we can have many different variables that all refer to the same object changing the
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 (since and are currently referring to the same objectconstructors constructor is special kind of method that is used to initialize newly created objects java has special way to declare the constructor and special way to invoke the constructor firstlet' look at the syntax for declaring constructormodifiers name(type parameter type - parameter - /constructor body thusits syntax is essentially the same as that of any other methodbut there are some important differences the name of the constructornamemust be the same as the name of the class it constructs soif the class is called fishthe constructor must be called fish as well in additionwe don' specify return type for constructor--its return type is implicitly the same as its name (which is also the name of the classconstructor modifiersshown above as modifiersfollow the same rules as normal methodsexcept that an abstractstaticor final constructor is not allowed here is an examplepublicfish (intwstring nweight wname ,constructor definition and invocation the body of constructor is like normal method' bodywith couple of minor exceptions the first difference involves concept known as constructor chainingwhich is topic discussed in section and is not critical at this point the second difference between constructor body and that of regular method is that return statements are not allowed in constructor body constructor' body
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 exampleconsider the following constructor invocation (which is also declaration for the myfish variable)fish myfish new fish ( "wally") class can have many constructorsbut each must have different signaturethat iseach must be distinguished by the type and number of the parameters it takes the main method some java classes are meant to be used by other classesothers are meant to be stand-alone programs classes that define stand-alone programs must contain one other special kind of method for class--the main method when we wish to execute stand-alone java programwe reference the name of the class that defines this program by issuing the following command (in windowslinuxor unix shell)java aquarium in this casethe java run-time system looks for compiled version of the aquarium classand then invokes the special main method in that class this method must be declared as followspublic static voidmain(string[args)/main method body the arguments passed as the parameter args to the main method are the commandline arguments given when the program is called the args variable is an array of string objectsthat isa collection of indexed stringswith the first string being args[ ]the second being args[ ]and so on (we say more about arrays in section calling java program from the command line java programs can be called from the command line using the java commandfollowed by the name of the java class whose main method we wish to runplus
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 definition is that it allows each class to define stand-alone programand one of the uses for this method is to test all the other methods in class thusthorough use of the main method is an effective tool for debugging collections of java classes statement blocks and local variables the body of method is statement blockwhich is sequence of statements and declarations to be performed between the braces "{and "}method bodies and other statement blocks can themselves have statement blocks nested inside of them in addition to statements that perform some actionlike calling the method of some objectstatement blocks can contain declarations of local variables these variables are declared inside the statement bodyusually at the beginning (but between the braces "{and "}"local variables are similar to instance variablesbut they only exist while the statement block is being executed as soon as control flow exits out of that blockall local variables inside it can no longer be referenced local variable can either be base type (such as intfloatdoubleor reference to an instance of some class single statements and declarations in java are always terminated by semicolonthat isa ";there are two ways of declaring local variablestype nametype name initial_valuethe first declaration simply defines the identifiernameto be of the specified type the second declaration defines the identifierits typeand also initializes this variable to the specified value here are some examples of local variable declarationsdouble rpoint new point ( )point new point ( )
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 and then discuss operators in some detail literals literal is any "constantvalue that can be used in an assignment or other expression java allows the following kinds of literalsthe null object reference (this is the only object literaland it is defined to be from the general object classbooleantrue and false integerthe default for an integer like or - is that it is of type intwhich is -bit integer long integer literal must end with an "lor " ,for example or - land defines -bit integer floating pointthe default for floatingnumberssuch as and is that they are double to specify that literal is floatit must end with an "for " floating-point literals in exponential notation are also allowedsuch as or the base is assumed to be characterin javacharacter constants are assumed to be taken from the unicode alphabet typicallya character is defined as an individual symbol enclosed in single quotes for example'aand '?are character constants in additionjava defines the following special character constants'\ (newline'\ (tab'\ (backspace'\ (return
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 section the assignment operator the standard assignment operator in java is "=it is used to assign value to an instance variable or local variable its syntax is as followsvariable expression where variable refers to variable that is allowed to be referenced by the statement block containing this expression the value of an assignment operation is the value of the expression that was assigned thusif and are both declared as type intit is correct to have an assignment statement like the followingi ;/works because '=operators are evaluated right-to-left arithmetic operators the following are binary arithmetic operators in javaaddition subtraction multiplication division
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 expression to invert its sign parentheses can be used in any expression to define the order of evaluation java also uses fairly intuitive operator precedence rule to determine the order of evaluation when parentheses are not used unlike ++java does not allow operator overloading increment and decrement operators like and ++java provides increment and decrement operators specificallyit provides the plus-one increment (++and decrement (--operators if such an operator is used in front of variable referencethen is added to (or subtracted fromthe variable and its value is read into the expression if it is used after variable referencethen the value is first read and then the variable is incremented or decremented by sofor examplethe code fragment int int ++int ++iint --int ++assigns to to to to nand leaves with value logical operators java allows for the standard comparison operators between numbersless than
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 second operand (to the rightin their expression if it is not needed to determine the value of the expression this feature is usefulfor examplefor constructing boolean expressions where we first test that certain condition holds (such as reference not being null)and then test condition that could have otherwise generated an error condition had the prior test not succeeded bitwise operators java also provides the following bitwise operators for integers and booleansbitwise complement (prefix unary operatorbitwise and bitwise or bitwise exclusive-or shift bits leftfilling in with zeros shift bits rightfilling in with sign bit
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 to variable variable op expression except that if variable contains an expression (for examplean array index)the expression is evaluated only once thusthe code fragment [ [ +++ leaves [ with value and with value string concatenation strings can be composed using the concatenation operator (+)so that the code string rug "carpet"string dog "spot"string mess rug dogstring answer mess will cost me dollars!"would have the effect of making answer refer to the string "carpetspot will cost me dollars!this example also shows how java converts nonstring constants into stringswhen they are involved in string concatenation operation
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 (whichincidentallyis the same as in cin table table the java precedence rules operators in java are evaluated according to the above orderingif parentheses are not used to determine the order of evaluation operators on the same line are evaluated in left-to-right order (except for assignment and prefix operationswhich are evaluated right-to-left)subject to the conditional evaluation rule for boolean and and or operations the operations are listed from highest to lowest precedence (we use exp to denote an atomic or parenthesized expressionwithout parenthesizationhigher precedence operators are performed before lower precedence operators operator precedence type symbols postfix ops prefix ops cast exp +exp -++exp --exp +exp -exp ~exp !exp (typeexp mult /div */
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 expression is true or false (we discuss the use of the instanceof operator in the next casting and autoboxing/unboxing in expressions casting is an operation that allows us to change the type of variable in essencewe can take variable of one type and cast it into an equivalent variable of another type casting can be useful for doing certain numerical and input/output operations the syntax for casting an expression to desired type is as follows(typeexp where type is the type that we would like the expression exp to have there are two fundamental types of casting that can be done in java we can either cast with respect to the base numerical types or we can cast with respect to objects herewe discuss how to perform casting of numerical and string typesand we discuss object casting in section for instanceit might be helpful to cast an int to double in order to perform operations like division ordinary casting when casting from double to an intwe may lose precision this means that the resulting double value will be rounded down but we can cast an int to double without this worry for exampleconsider the following
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 when used with integersdivision does not keep track of the fractional partfor example when used with doublesdivision keeps this partas is illustrated in the following exampleint int dresult (double) (double) ;/dresult has value dresult value /dresult has notice that when and were cast to doublesregular division for real numbers was performed when and were not castthe /operator performed an integer division and the result of was the int thenjavajava then did an implicit cast to assign an int value to the double result we discuss implicit casting next implicit casting and autoboxing/unboxing there are cases where java will perform an implicit castaccording to the type of the assignment variableprovided there is no loss of precision for exampleint iresulti double dresultd dresult dcast to double /dresult is was
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 integer and floatand their related base typeslike int and float any time number object is expected as parameter to methodthe corresponding base type can be passed in this casejava will perform an implicit castcalled autoboxingwhich will convert the base type to its corresponding number object likewiseany time base type is expected in an expression involving number referencethat number object is changed to the corresponding base typein an operation called unboxing there are few caveats regarding autoboxing and unboxinghowever one is that if number reference is nullthen trying to unbox it will generate an errorcalled nullpointerexception secondthe operator"=="is used both to test the equality of base type values as well as whether two number references are pointing to the same object so when testing for equalitytry to avoid the implicit casts done by autoboxing and unboxing finallyimplicit castsof any kindtake timeso we should try to minimize our reliance on them if performance is an issue incidentallythere is one situation in java when only implicit casting is allowedand that is in string concatenation any time string is concatenated with any object or base typethat object or base type is automatically converted to string explicit casting of an object or base type to string is not allowedhowever thusthe following assignments are incorrectstring (string wrong/this is string "value (string ;/this is wrongstring /this is wrongto perform conversion to stringwe must instead use the appropriate tostring method or perform an implicit cast via the concatenation operation thusthe following statements are correct
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 restricted forms of "jumps(the break and continue statementsthe if and switch statements in javaconditionals work similarly to the way they work in other languages they provide way to make decision and then execute one or more different statement blocks based on the outcome of that decision the if statement the syntax of simple if statement is as followsif (boolean_exptrue_statement else false_statement where boolean_exp is boolean expression and true_statement and false_statement are each either single statment or block of statements enclosed in braces ("{and "}"note thatunlike some similar languagesthe value tested by an if statement in java must be boolean expression in particularit is definitely not an integer expression neverthelessas in other similar languagesthe else part (and its associated statementin java if statement is optional there is also way to group number of boolean testsas followsif (first_boolean_exptrue_statement