3.1 (evens) - Section 3.1 Algorithms 55 CHAPTER 3 The...

Info icon This preview shows pages 1–7. Sign up to view the full content.

View Full Document Right Arrow Icon
Image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Image of page 2
Image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Image of page 4
Image of page 5

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Image of page 6
Image of page 7
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Section 3.1 Algorithms 55 CHAPTER 3 The Fundamentals: Algorithms, the Integers, and Matrices SECTION 3.1 Algorithms 2. a) This procedure is not finite, since execution of the while loop continues forever. b) This procedure is not effective, because the step in. := l/n cannot be performed when n = U, which will eventually be the case. c) This procedure lacks definiteness, since the value of 3'. is never set. cl) This procedure lacks definiteness, since the statement does not tell whether .1: is to be set equal to a. or to b. 4. Set the answer to be ~00. For i going from 1 through it — 1, compute the value of the (i —I— 1)51 element in ,‘th the list minus the 1 element in the list. If this is larger than the answer, reset the answer to be this value. 6. We need to go through the list and count the negative entries. procedure riegatiiies{a.1,a2, . . . ,en : integers) I: :: U for i z: 1 to n if (15(0 then it :2 k+1 end { k is the number of negative integers in the list} 8. This is similar to Exercise 7, modified to keep track of the largest even integer we encounter. procedure largest even. location(a.1,eg, . . . ,on : integers) k :: 0 largest 2: —00 for i :: 1 to n. if (a,- is even and e,- > largest) then begin it :2 i largest z: it, end end { k is the desired location (or 0 if there are no evens)) 10. We assume that if the input a 2 0, then it > 0, since otherwise 3:“ is not defined. In our procedure, we lot m = |n| and compute .r'" in the obvious way. Then if n is negative, we replace the answer by its reciprocal. procedure gnome-rte : real number, n : integer) m :: |n| power := 1 for i :: 1 to in power :: power - :r if n < 0 then power 2: 1/pouier' {power 2 .17" ] 12. Four assignment statements are needed, one for each of the variables and a temporary assignment to get started so that we do not lose one of the original values. 56 Chapter 3 The Fundamentals: Algorithms, the Integers, and Matrices temp :2 :3 IL' :2 y y :2 z z :2 temp 14. a) With linear search we start at the beginning of the list, and compare 7 successively with 1, 3, 4, 5, 0', 8, 9, and 11. When we come to the end of the list and still have not found 7, we conclude that it is not in the list. b) We begin the search on the entire list, with i 2 1 and j 2 n 2 8. We set or :2 4 and compare 7 to the fourth element of the list. Since 7 > 5, we next restrict the search to the second half of the list, with i 2 5 and j 2 8. This time we set In. :2 6 and compare 7 to the sixth element of the list. Since 7 )4 8, we next restrict ourselves to the first half of the second half of the list, with i. 2 5 and j 2 6. This time we set In. :2 5, and compare 7 to the fifth element. Since 7 > 6, we now restrict ourselves to the portion of the list between i. 2 6 and j 2 6. Since at this point 2‘ 7i j, we exit the loop. Since the sixth element of the list is not equal to 7, we conclude that 7 is not in the list. 16. We let min be the smallest element lound so far. At the end, it is the smallest element, since we update it as necessary as we scan through the list. procedure smallestml, 02,...,(1-n : natural numbers) min. :2 (1.1 for 2' :2 2 to n if e,- < min then min :2 e,- { min is the smallest integer among the input} 18. This is similar to Exercise 17. procedure last smalles£(a1,ag,...,en : integers) min :2 a] location :2 1 for i :2 2 to n. if min 2 a,- then begin min :2 0., location. :21‘. end { location. is the location of the last occurrence of the smallest element in the list} 20. We just combine procedures for finding the largest and smallest elements. procedure smallest and laryesflal , a2, . . . ,on : integers) min :2 (11 may: :2 al for 2". :2 2 to n begin if a,- < min then min :2 a,- if a, > more then mam :2 (I) end { min is the smallest integer among the input, and mum is the largest} 22. We assume that the input is a sequence of symbols, a; , n.2, .. . , on , each of which is either a letter or a blank. Vile build up the longest word in word; its length is length. ‘Ne denote the empty word by A. Section 3.1 Algorithms 57 procedure longest U.=ord(r1.1,o-2,. . . , (In : symbols) martlength z: 0 mammd :: /\ 'i 2: 1 while i S n begin word :2 )l length. := 0 while (If 76 blank and i. g n begin length := length, + 1 word :: concatenation of word and a,- 1 z: '1'. + 1 end if length. > man: then begin mantle-right. :: length. mamword :2 word end i :2 i + 1 end 24. This is similar to Exercise 2.3. We let the arra}r hit keep track of which elements of the codomain B have already been found to be images of elements of the domain A. When we find an element that has already been hit being hit again. we conclude that the function is not oneto-one. procedure one_one(f : fLiIic:t,i011,a1.rig,.. . ,a.n,b1,b2, . .. ,bm : integers) for i := 1 to m hit(b,-) 2: 0 once-no :: true for j :: 1 to n. if h.it(f(aj)) = 0 then h,it(f(n.3,)) :: 1 else one_on.e :: false 26. There are two Cl’lauges. First, we need to test 2: : am (right after the computation of m) and take appropriate action if equality holds (what we do is set i and j both to be m). Second, if a; )4 am, then instead of setting j equal to m, we can set j equal to m i 1. The advantages are that this allows the size of the “half” of the. list being looked at to shrink slightly faster, and it allows us to stop essentially as soon as we have found the element we are looking for. 28. This could be thought of as just doing two iterations of binary search at once. We compare the soughteafter element to the middle element in the still-active portion of the list, and then to the middle element of either the top half or the bottom half. This will restrict the subsequent search to one of four sublists, each about one-quarter the size of the previous list. “’e need to stop when the list has length three 01' less and make explicit checks. Here is the pseudocode. procedure tetmrg scare/1.011 : i11tege1‘,al,ag,... ,an : increasing integers) 'i := 1 j :: '11 while 1' < j i ‘2 begin l3:1(‘1"l'v’n"}/‘1l 171:: [(-i +jl/2j n. := [30: +j)/4J 58 end Chapter 3 if a: > am then if m S ou then begin 2'. := m + 1 j z: u end else i. := u + 1 else if a: > a; then begin :5 := l + 1 j z: 711. end else 3' := l if 3: : u,- then location ::-i else if :1: : (1.3- then location := j else if .1- : riL(,-_+j)/2J then location: [(i +j)/2j else location :: 0 { location is the subscript of the term equal to :1: (0 if not found)} The Fundamentals: Algorithms, the li'itegors, and Matrices 30. The following algorithm will find all modes in the sequence and put them into a list L. At each point in the execution of this algorithm, modecount is the number of occurrences of the elements found to occur most often so far (the elements in L). ’Whenever a more frequently occurring element is found (the main inner loop). modecouut and L are updated; whenever an element is found with this same count, it is added to L. procedure find all. -modes(o.1,ag, . .. modecount :: 0 11:21 while i S n begin end value c: 0,: count :: 1 while i S n and oi : value begin count :: count +1 i 2: i + 1 end if count > modecount then begin modem-uni :: count ,an : nondecreasing integers) set L to consist just of value end else if count = modecount then add value to L { L is a list of all the values occurring most often, namely modecou‘nt times} 32. The following algorithm will find all terms of a finite sequence of integers that are greater than the sum of all the previous terms. We put them into a list L , but one could just as easily have them printed out, if that were desired. It might be more useful to put the indices of these terms into L, rather than the terms themselves (i.e., their values), but we take the former approach for variety. As usual, the empty list is considered to have sum 0, so the first term in the sequence is included in L if and only if it positive. procedure find all biggiesmhog, set L to be the empt)r list sum :2 0 'i::1 , an : integers) Section 3.1 Algorithms 59 while 7'. S n begin if a,- > sum. then append a, to L sum :: sum. + a, i :: i + 1 end { L is a list of all the values that exceed the sum of all the previous terms in the sequence} 34. There are five passes through the list. After one pass the list reads 2, 3, 1, 5, 4, 6, since the 6 is compared and moved at each stage. During the next pass, the 2 and the 3 are not interchanged, but the 3 and the 1 are, as are the 5 and the 4, yielding 2,1,3,4,5,6. On the third pass, the 2 and the 1 are interchanged, yielding 1,2,3, 4, 5,6. There are two more passes, but no further interchanges are made, since the list is now in order. 36. The procedure is the same as that given in the solution to Exercise 35. We will exhibit the lists obtained after each step, with all the lists obtained during one pass on the same line. rift-mob, dfirmab, efficient), rifkumb, (ifkahm. affirabm, (ifkabm, dfak‘bm, dfabkm dfabk m, dnfbkm, dabfkm adhfkm, abdficm uhdfkm 38. We start with 6,2,3,1,5,4. The first step inserts 2 correctly into the sorted list 6, producing 2,6,3,1,5,4. Next 3 is inserted into 2,6, and the list reads 2,3,6,1,5,4. Next 1 is inserted into 2,3,6, and the list reads 1,2,3,6, 5,4. Next 5 is inserted into 1,2,3,6, and the list reads 1,2,3,5,6,4. Finally 4 is inserted into 1,2, 3, 5,6, and the list reads 1, 2,3, 4, 5, 6. At each insertion, the element to be inserted is compared with the elements already sorted, starting from the beginning, until its correct spot is found, and then the previously sorted elements beyond that spot are each moved one position toward the back of the list. 40. We start with (hf, in,m,c,b. The first step inserts f correctly into the sorted list d, producing no change. Similarly, no change results when k and m are inserted into the sorted lists d, f and d,f, iv, respectively. Next a is inserted into d,f,k,m, and the list reads a,d.,f,ir., m,b. Finally 1') is inserted into a,d,f,k,m, and the list reads a, b, d, f, lam. At each insertion, the element to be inserted is compared with the elements already sorted, starting from the beginning, until its correct spot is found, and then the previously sorted elements beyond that spot are each moved one position toward the back of the list. 42. we let minspot be the place at which the minimum remaining element is found. After we find it on the it" pass, we just have to interchange the elements in location mans-pot and location i. procedure selectionmhag, . . . , an) forizzlton—l begin minspot 2: i forj:=i+'l to n if a} < aminspot then mills-pot :: j interchange ammwo, and (7., end [the list is now in order} 44. “’9 carry out the binary search algorithm given as Algorithm 3 in this section, except that we replace the final check with if :1: < a; then location. :: 2' else location 2: i + 1. 60 46. 48. 50. 52. Chapter 3 The Fundamentals: Algorithms, the Integers, and Matrices We are counting just the comparisons of the numbers in the list, not any comparisons needed for the book— keeping in the for loop. The second element in the list must be compared only with the first {in other words, when j = 2 in Algorithm 5, 17 takes the values 1 before we drop out of the while loop). Similarly, the third "" element must be element must be compared only with the first. We continue in this way, until finally the 11 compared only with the first. So the total number of comparisons is n — 1. This is the best case for insertion sort in terms of the number of comparisons, but moving the elements to do the insertions requires much more ellbrt. For the insertion sort, one comparison is needed to lind the correct location of the 4, one for the 3, four for the 8, one for the 1, four for the 5, and two for the 2. This is a total of 13 comparisons. For the binary insertion sort, one comparison is needed to find the correct location of the 4, two for the 3, two for the 8, three for the 1 , three for the 5, and four for the 2. This is a total of 15 comparisons. If the list were long (and not almost in decreasing order to begin with), we would use many fewer comparisons using binary insertion sort. The reason that the answer came out “wrong” here is that the list is so short that the binary search was not efficient. a) This is essentially the same as Algorithm 5, but working from the other end. However, we can do the moving while we do the searching for the correct insertion spot, so the pseudocode has only one section. procedure backward insertion sort(a.1,a2,...,a.,, : real numbers with n 2.2) for j := 2 to n. begin m. 1: (113' i :: j w 1 while (m < a, and i > U) begin (n+1 i: Gr 2' :: i. —— 1 end Gf+1 I: m. end {01,a2,. . . ,0,” are sorted} b) On the lirst pass the 2 is compared to the 3 and found to be less, so the 3 moves to the right. We have reached the beginning of the list, so the loop terminates (1' : 0), and the 2 is inserted, yielding 2,3, 4,5, 1,6. On the second pass the 4 is compared to the 3, and since 4 > 3, the while loop terminates and nothing changes. Similarly, no changes are made as the 5 is inserted. One the fourth pass, the 1 is compared all the way to the front of the list, with each element moving toward the back of the list as the comparisons go on, and finally the 1 is inserted in its correct position, yielding l, ‘2, 3, 4, 5, 6. The final pass produces no change. c) Only one comparison is used during each pass, since the condition m < a, is immediately false. Therefore a total of 7?. ~ 1 comparisons are used. (1) The 3” pass requires 3' _ 1 comparisons of elements, so the total number of comparisons is 1 + 2 + + (n — 1) = n.(n —-1)/2. In each case we use as many quarters as we can, then as many dimes to achieve the remaining amount, then as many nickels, then as many pennies. a) The algorithm uses the maximum number of quarters, three, leaving 12 cents. It then uses the maximum number of dimes (one) and nickels (none), before using two pennies. b) one quarter, leaving 24 cents, then two dimes, leaving 4 cents, then four pennies c) three quarters, leaving 24 cents, then two dimes, leaving zl cents, then four pennies d) one quarter, leaving 8 cents, then one nickel and three pennies Section 3.1 Algorithms 61 54. 56. 58. 60. 62. a) The algorithm uses the maximum number of quarters, three, leaving 12 cents. It then uses the maximum number of dimes (one), and then two pennies. The greedy algorithm worked, since we got the same answer as in Exercise 52. b) one quarter, leaving 24 cents, then two dimes, leaving 4 cents, then four pennies (the greedy algorithm worked, sinCe we got the same answer as in Exercise 52) c) three quarters, leaving 24 cents, then two dimes, leaving 4 cents, then four pennies (the grei-tdy algorithm worked, since we got the same answer as in Exercise 52) d) The greedy algorithm would have us use one quarter, leaving 8 cents, then eight pennies, a total of nine coins. However, we could have used three dimes and three pennies, a total of six coins. Thus the greedy algorithm is not correct for this set of coins. One approach is to come up with an example in which using the 12-eent coin before using dimes or nickels would be inefficient. A dime and a nickel together are worth 15 cents, bu t. the greedy algorithm would have us use four coins (a iQ-cent coin and three pennies) rather than two. An alternative example would be 29 cents, in which case the greedy algorithm would use a quarter and four pennies, but we could have done better using two 12-cent coins and a. nickel. If all the men get their first choices, then the matching will be stable, because no man will be part of an unstable pair, preferring another woman to his assigned partner. Thus the pairing ('fi31W3,T'122w1,Tll-31U2) is stable. Similarly, if all the women get their first choices, then the matching will be stable, because no woman will be part of an unstable pair, preferring another man to her assigned partner. Thus the matching (7711‘fll1,'fli.2‘w2, Ni3w3) is stable. Two of the other four matchings pair ml with tag, and this cannot be stable, because ml prefers ml to wz, his assigned partner, and w] prefers m, to her assigned partner, whoever it is, because in, is her favorite. In a similar: way, the matching ('i’rlltU3,TfigUJ2,‘m3‘w1) is unstable because of the unhappy unmatched pair ”1311):; (each preferring the other to his or her assigned partner). Finally, the matching (mm-1, mgwg, m3iu2) is stable, because each couple has a reason not to break up: wl got her favorite and so is content, 7113 got his favorite and so is content, and 1U3 only prefers mg to her assigned partner but he doesn’t prefer her to his assigned partner. Suppose we had a program 5' that could tell whether a program with its given input ever prints the digit 1. Here is an algorithm for solving the halting problem: Given a program P and its input I, construct a program P', which is just like P but never prints anything (even if P did print something) except that if and when it is about to halt, it prints a 1 and halts. Then P halts on an input. if and only if P' ever prints a 1 on that same input. Feed P’ and I to 8, and that will tell us whether or not P halts on input I. Since we know that the halting problem is in fact not solvable, we have a contradiction. Therefore no such program 3 exists. The decision problem has no input. The answer is either always yes or always no, depending on whether or not the specific program with its specific input halts or not. In the formcr ease, the decision procedure is “say | yes," and in the latter case it is “say no.” ...
View Full Document

{[ snackBarMessage ]}

What students are saying

  • Left Quote Icon

    As a current student on this bumpy collegiate pathway, I stumbled upon Course Hero, where I can find study resources for nearly all my courses, get online help from tutors 24/7, and even share my old projects, papers, and lecture notes with other students.

    Student Picture

    Kiran Temple University Fox School of Business ‘17, Course Hero Intern

  • Left Quote Icon

    I cannot even describe how much Course Hero helped me this summer. It’s truly become something I can always rely on and help me. In the end, I was not only able to survive summer classes, but I was able to thrive thanks to Course Hero.

    Student Picture

    Dana University of Pennsylvania ‘17, Course Hero Intern

  • Left Quote Icon

    The ability to access any university’s resources through Course Hero proved invaluable in my case. I was behind on Tulane coursework and actually used UCLA’s materials to help me move forward and get everything together on time.

    Student Picture

    Jill Tulane University ‘16, Course Hero Intern