Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 37 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
37
Dung lượng
448,24 KB
Nội dung
Summary Sorting means arranging data in order. Arranging a list of names in alphabetical order is an example of sorting. Sorting a list of numbers means arranging them in ascending or descending order. Ascending order arranges smaller numbers before larger numbers in an array. Descending order puts numbers that are greater in size first, followed by smaller numbers. Next we covered the selection sort, which relies on the ability to find the minimum in a list. The selection sort was explained through an analogy of people attending a party. Then we looked at the selection sort applied to a list of numbers. Next we defined the minimum of a list. It is the smallest number in a list. In order to find the smallest number, the first number from the array (slot [0]) is assigned to a variable called minimum.Thenthealgorithmworksbylooking attherestofthenumbersinthelist—oneatatime—throughtheuseofaloop. As you look at each number, you test whether that number is smaller than the number that is presently assigned to the minimum variable. When the loop is done spinning, the value in the minimum variable is the smallest number in the list. 296 Chapter 19 n Let’s Put Things in Order: Sorting Figure 19.3 The array is shown as the merging of these two ordered halves. Each member from each half goes into its proper position. The merge sort was the second sort we examined. It works very differently from the selection sort. The merge sort repeatedly cuts an array into halves until there are only single elements of the array. Then those members of the array are assembled into their proper order, two pieces at a time. The sort gets its name from the merging that occurs as the pieces are put back together properly. Summary 297 This page intentionally left blank Recursion: Calling Yourself Over and Over Again This chapter examines recursion, which is a method of solving a problem by solving a smaller case of the same problem. I give examples of recursion and explain how the computer can carry out recursion through repeated calls to the same function, but each time using a different, smaller parameter. In This Chapter n Examples of recursion n Definition of recursion n Key features of recursion Recursion—What Is It? Recursion is a particular process involved in solving a problem. Webster’s definition of recursion states that it is ‘‘a procedure that can repeat itself indefinitely.’’ Essentially, the process involves solving a simpler problem of the same type as the original problem you were asked to solve. Let’s first look at some examples outside of the context of programming to understand this process. 299 chapter 20 Example Using Words Let’s say we have a vocabulary word whose meaning we do not know. Your second impulse might be to look up the word in the dictionary. (Your first impulse might be to ask someone the meaning!) Take the word obstreperous. If you look up obstreperous in the dictionary, it might say something like ‘‘recalcitrant or willful.’’ When you read this meaning, at first you will be happy that there is a word you understand—willful—but then disappointed that you need to look up another word—recalcitrant. So you next look up the word recalcitrant to see what that means. This time the dictionary says something like ‘‘defiant.’’ At this point, you might think you know what defiant means, but you need to check it to be sure. So once again you consult the dictionary, and you find that defiant means ‘‘unruly.’’ You’re almost sure of the meaning of the last word—unruly—but you look it up to be certain. Here the dictionary says ‘‘stubborn.’’ See Figure 20.1. So the word obstreperous at the base of all this work means something like stubborn, with some other shades of meaning picked up from the words along the way. Our process of discovering the meaning of this word has been a recursive process. We chose a method to solve our problem—finding the meaning of a word—by using the same process, looking up other words in a dictionary. Each time we looked up a new word, we came closer to understanding the meaning of the original word. 300 Chapter 20 n Recursion: Calling Yourself Over and Over Again Figure 20.1 A word, obstreperous, is shown with other words used to explain its meaning. Each word below another word contributes to the understanding of the meaning of the original word. Recursion is this process of redoing a problem, but in a simpler context than the original problem we did. Consider the next example that uses recursion and involves numbers. Example Using Numbers It is often easier to see recursion in a numeric example than in an example that does not involve numbers. In order to understand this example, we first need to define the factorial of a number. The factorial of a number is a product of the number and all the numbers less than it—all the way down to 1. The factorial of 6 is the answer you get fr om multiplying 6 by all the numbers less thanit—5,4,3,2,and1.Recallthatmultiplicationisrepresentedbytheasterisk(*). 6*5*4*3*2*1 \/ 30*4*3*2*1 \/ 120*3*2*1 \/ 360 * 2 * 1 \/ 720 * 1 \/ 720 So the answer to the factorial of 6 is 720. Factorials quickly produce massive numbers because you are multiplying so many numbers, usually, to get an answer. The factorial of a number is represented by an exclamation point (!). The previous example looks like this symbolically: 6! Before we get to the recursion involved in the problem, let’s redo the problem with some creativity. Let’s start with the symbol for a factorial and use it in writing the multiplication for the factorial. 6! = 6 * 5 * 4 * 3 * 2 * 1 another factorial is here The boldface part of the preceding statement is another factorial. It is called the factorial of 5, or 5!. Let’s rewrite the previous statement using that information. 6!=6*5! Recursion—What Is It? 301 The previous statement means that the factorial of 6 is found by multiplying the number 6 by the factorial of 5. If we only knew the factorial of 5, we could finish this problem right away. So the solution to finding the factorial of 6 rests on our ability to find the factorial of 5, and then to take that answer and just multiply it by the number 6. This way of solving the problem is a recursive method. We are solving the problem by solving a smaller case ofthesametype of problem. Now consider the separate problem of finding the answer to the factorial of 5. Consider what the factorial of 5 looks like as a product of numbers. 5!=5*4*3*2*1 another factorial is here Again, just as in the previous example, we can use another factorial to represent part of the work needed to get the answer to the factorial of 5. Let’s rewrite the problem using that factorial. 5!=5*4! And so the process continues like this. We find the factorial of 4 by finding the factorial of 3 and then multiplying that answer by 4. 4!=4*3! The last two lines of work involve finding the factorial of 3 and the factorial of 2 (The factorial of 1 is the value 1.) Consider these last two lines of computation. 3!=3*2! 2! =2*1 Each line of computation involved finding the answer to a similar—but smaller— factorial problem. The important point to notice is that you are finding the answer to the problem using a smaller case of the same problem. The factorial of 6 used the answer from the smaller case, the factorial of 5. Another point to notice is that this process eventually stops. If it did not stop, then the recursive process would continue forever. Two Features of Recursion In order to understand the topic of recursion more comprehensively, we need to look at key aspects of a recursive solution, or what constitutes a recursive solution to a problem. We will also examine how the previous problems (the 302 Chapter 20 n Recursion: Calling Yourself Over and Over Again words in the dictionary and the factorial problem) modeled these aspects. Let’s examine the key features of a recursive problem: 1. A smaller problem of the same type exists. 2. Eventually you reach a bottom case or stopping state. Recursion would be useless if it continued indefinitely. We would never arrive at an answer if that were the case. In the examples we completed in the previous section, both of these features were present in the solution of the problem. When we looked up the word obstreperous in the dictionary, we eventually found a simpler word whose meaning we did understand. The simpler word, stubborn, is a smaller case of the same type of problem (that is, the word is not as difficult as the original word). The stopping state for the word problem is finding a word whose meaning we do know, and then we can stop looking up words in the dictionary. With the factorial example, the smaller case of the same type of problem is using a factorial of a number less than the number we started with. (The factorial of 5 is a smaller case than the factorial of 6.) The stopping state is reaching a factorial whose answer we do know—the factorial of 2, since it is the product of 2 * 1. Infinite recursion is a problem that arises when one of these parts is not satisfied by the recursive design we make. For example, if we never arrived at a word we understood in the dictionary, we would always be looking up new words. Using Functions in Recursion In order to understand how recursion works, we need to look at how functions are the bedrock of recursion on a computer. Imagine if we defined a function called look_up. This function would look up any word that we did not under- stand. First we would call on it and send in the word obstreperous from the previous example. Then we would want to call the function again, but this time send in the word recalcitrant. We would want to call the function a third time, sending in the next word, defiant. The last time we call the function, we send in the word unruly, where the meaning we get (here, stubborn) is clear to us, so we can stop calling the function look_up. The process of looking up one word and then another and another, until we get a word whose meaning we know, shows that we need to make several calls (four calls, in fact) to this function. See Figure 20.2 Two Features of Recursion 303 One Function Calls Itself The reality behind these repeated calls to one function is that the calling occurs within the function itself. Now what does that mean? I have always talked about the main program (the main function) making the calls to the function. In reality, any function can make a call to another function. In the case of recursion, the function calls itself. Let’s see what this does. In the look_up example, the main function calls the lo ok_ up function and sends in the word obstreperous. Once the look_up function starts its work—looking up a word in a dictionary— i t finds another word it doesn’t know. So it leaves in the middle of its own function and calls look_up again—this time with the new word it did not understand—recalcitrant. The idea behind the call to the function is that once it understands the new word, it can use that knowledge to understand the m eaning of the first word, obstreperous. How Recursion Is Executed Recursion is dependent on the ability of a program to call a function over and over again. The first step in recursion is to define a function that will solve the first case of the problem. 304 Chapter 20 n Recursion: Calling Yourself Over and Over Again Figure 20.2 A chain of calls is shown with a new word sent to the function each time it is called. Copies of Functions Are Generated Each time a call is made to a function, the compiler will generate a copy of the instructions (the code) of the function in the memory of the computer. If you call a function repeatedly, then for each call there will be a copy of the function stored in memory. Let’s say a function called Alpha (with an integer parameter) is called three times during a program’s execution. int x, y, z; . // x , y, and z are assigned before the calls are made . . Alpha (x); . . . Alpha (y); . . . Alpha (z); Alpha’s code will be copied three times in memory as each copy is made for each call. See Figure 20.3. How Recursion Is Executed 305 Figure 20.3 Three copies of the function Alpha are shown for each call made to the function. [...]... of matrix, 210 loading matrix row, 204 nested, 205–209, 211 parts of, 118 printing message for even and odd numbers, 119–121 printing numbers 1 through 10 on-screen, 119 printing out all members of list array, 182 stepping through, 119 variable within range, 113–114 for reserved word, 225 forecolor, 151, 160 ForeColor function, 163, 166–167 foreground, 159 color, 166 foreign languages, 25 Fortran, 12... 93–96 finding syntax errors, 217 generating copies of functions, 305 computer languages basic tasks, 10 logic operators, 49–51 spelling errors, 216 statements, 30–31 syntax, 10 computer problems design, 81–83 prime numbers example, 81–82 youngest person in group example, 82–83 computer programming, 2 computers, 9 electronic states, 9 10 hardware, 2–3 making decisions, 90 software, 2–3 concatenating strings,... 277 understanding, 275–276 bits (binary digits), 1, 7–9 block of code and braces ({}), 100 book struct, 234 book type, 236 boolean condition, 94 even or odd number, 102 104 inside nested for loop, 212–213 loops, 221 boolean expression becoming false, 121 equal (==) operator, 102 false, 126 if .else statement, 99 101 for loop, 114–115, 117 relational operators, 96 value of true or false, 117 boolean type,... increasing value (for example, 5, 7, 12, 16, 20) Assignment Giving a variable a value in a program 311 312 Glossary Attribute An additional quality given to a tag’s function to expand the features of the tag (for example, the width attribute for an image tag) Attribute Value A value assigned to an attribute within a tag (for example, width = 100 ) Background The window area that is not the foreground Binary... class, and the definition of the object itself Glossary High-Level Language A programming language (for example, C, Cþþ, Java, Pascal, Fortran, and so on) that requires more translation than a low-level language HTML Hypertext Markup Language A high-level computer language used to format documents (add images, sound clips, and so forth) and link them over the Internet Identifier The proper name of a variable... client file Program Flow The sequential execution of programming commands in a language Program Fragment A portion or section of a program Programmer The person who writes the program Programming Solving a program by designing an algorithm and expressing that algorithm in a programming language Protocol How a computer communicates with another computer (for example, hypertext transfer protocol [http],... boolean expression, 95 Cþþ programming language, 101 conclusion, 95, 97 developing with relational expression, 273 everyday circumstances, 95 examples, 95–96 mod operator (%), 103 104 outcomes, 97–98 relational operators, 96–97 skipping conclusion, 97 ifstream, 251–252 if .else boolean expression, 115 if .else statement, 99 101 ifstream type, 252 if .then statements, 30 images and forecolor, 151 imaginary... input statement, 182 leaving, 117 for loop, 113–121 message to user, 182 output statement, 220 post-test, 124 pre-test, 123 programs, 109 reading contents of text file, 253–254 reasons to use, 110 repeating steps, 109 – 110 spinning unknown number of times, 112 tracing through, 220–221 types, 112–115 variable holders, 254 low-level languages, 11–113 M machine language, 1, 10 11 main function, 304 calling... symbol (#), 66 number variable, 253 numbers actions performed on, 40 averaging three, 69–70 even or odd, 102 104 factorial of, 301–303 finding square of, 135 identifying elements, 200 integer type, 24 integers, 24 methodically looking for, 274–275 real, 24–25 representing information, 6–9 num_scores variable, 218–219 O object code, 13 object-oriented programming, 238–239 objects, 237–239 accessing parts... solution, 302–303 smaller case, 302 solving, 13–14 product, 306–307 program flow, 93–94, 109 program fragments, 101 programmers, 32 assigning variables, 32–33 listing variables, 36 programming, 2, 15 algorithms, 15 object-oriented, 239 top-down design, 76 programming files, 248 programming languages basic tasks, 10 comments, 63 compilers, 13 control statements, 94 high-level languages, 11–12 input stream, . tag (for example, the width attribute for an image tag). Attribute Value. A value assigned to an attribute within a tag (for example, width = 100 ). Background. The window area that is not the foreground. Binary. number of times (for example, a for loop). for Loop. A loop that executes a fixed number of times. Foreground. The front part of a window. Images drawn by the programmer are part of the foreground. Function Language. A programming language (for example, C, Cþþ, Java, Pascal, Fortran, and so on) that requires more translation than a low-level language. HTML. Hypertext Markup Language. A high-level computer