Computer Science An Overview 12th Edition Brookshear Solutions Manual 1
Computer Science An Overview 12th Edition Brookshear Solutions Manual 1
EDITION BROOKSHEAR
Chapter Five
ALGORITHMS
Chapter Summary
In this chapter we turn to an explicit study of algorithms—a topic that was introduced as the core of
computer science in Chapter 0. The chapter begins with a formal definition of an algorithm and a
discussion of the meaning of that definition. This leads to a discussion of algorithm creation (a creative
process that parallels the more generic task of problem solving) and algorithm representation (the
process of expressing an algorithm in preparation for, or during, programming). The chapter closes
with the subjects of algorithm efficiency (using big theta notation) and correctness.
The search for algorithm development techniques is presented as an ongoing activity—not a
settled issue. The chapter discusses some of the ideas proposed by researchers in the field of problem
solving and relates these ideas to the problem of algorithm discovery and representation.
This chapter also presents iterative structures by means of the sequential search and insertion sort
algorithms as well as recursive structures by means of the binary search algorithm. In each case,
emphasis is placed on the components involved in controlling the repetitive process.
For communication purposes, the chapter introduces a pseudocode that is closely aligned with
Python. This pseudocode is also used at times later in the text, although these later appearances are
rather intuitive in that they do not require previous, rigorous coverage of this chapter. So, if you’re
teaching a course for non-majors, you can treat the pseudocode lightly without creating problems in
future chapters.
25
Comments
1. You will find this text's approach to problem solving somewhat different from that of other texts.
The problem solving section in this chapter is intended to be a refreshingly honest discussion. It does
not try to convince students that they can become good problem solvers merely by learning a
particular problem solving technique. In particular, it does not preach top-down design via stepwise
refinement.
Students don't learn to solve problems by practicing explicit techniques in an isolated section of a
course. They learn to solve problems unconsciously over an extended period of time in which they
are required to do it. Thus, every chapter of the text is designed to develop the students' problem-
solving skills. (Maybe I'm old-fashioned, but I think we produce too much rhetoric about problem
solving and don’t require our students to do enough.)
3. The following is a problem that I have given students to work on. The point is not whether they
solve it but that they realize that solving a problem is a creative process that may not be achieved by
following a methodology. Actually, you could argue that there are many correct answers to this
problem, but I think you'll agree that the one given below is a good one.
Problem: Fill in the blank in the sequence
110, 20, 12, 11, 10, __, ...
Answer: 6. The pattern is
110 (base two) = 6, 20 (base three) = 6, 12 (base four) = 6
11 (base five) = 6, 10 (base six) = 6, so 6 (base seven) = 6
4. Here is a good problem for demonstrating bottom-up design and the use of abstraction in problem
solving. Imagine three railroad spurs each opening into a Y that connects to the other spurs. (It is
really three stacks, but we have not studied data structures yet.) Cars are on each spur and a
locomotive is in the “middle” of the track system. Show that the locomotive can rearrange the cars in
any order.
A first step is to show that the locomotive can move the car "on top" of any spur to the top of any
other spur. This is actually a two-step process since the locomotive must remain in the "middle" of
the track system. The next step is to show that any two cars on a spur can be interchanged. Then show
that any two cars in the system can be interchanged. Finally, show that any arrangement can be
obtained by a sequence of interchanging two cars at a time.
5. I've debated marking the introduction to recursion as an optional section, but the truth is that
recursion is a very important topic in computer science. I even include it when I teach "computer
literacy" to non-majors and have always found the class to respond well. (I show the class that solving
a problem recursively is like getting something for nothing—we always ask someone else to do the
hard work. The students like that.)
Thus, an important goal in this chapter is to begin developing the concept of recursion. I say "begin"
because experience has shown that students acquire an understanding of recursion over a period of
time. I like to devote a significant part of a class period to walking through an example of the binary
search, as done in the book. Each time another activation of the algorithm is called, I mark my place
in the current copy of the algorithm, move to a new location on the chalkboard, draw another copy,
copy the pertinent portion of the list next to it, and then proceed with execution. (Some form of
overhead projection saves time, but working on a chalkboard gives students time to think.) Each time
an activation terminates, I transfer its list back into the larger list in the previous activation, erase the
terminating activation, and then proceed in the previous one. Such a careful presentation pays
numerous dividends. Not only does it clearly present the recursive process, but it also sets the stage
for later discussions regarding stacking activation environments, issues of global versus local
variables, and parameter passing.
I also like to walk through some short examples such as
26
def PrintValues(Input):
if (Input != 0):
print(Input)
PrintValues(Input – 1)
in which I point out the difference in the output obtained by reversing the statements in the then
clause.
6. Here are some additional problems you may want to give your students. Each has the characteristic
that one can see a solution fairly quickly, but then one must wrestle with the problem of organizing
and expressing the solution.
a. Design an algorithm for solving the traveling salesman problem. (Given a network of roads, cities,
and mileages, find the shortest route that leads through each city at least once.)
b. Design an algorithm for converting a string of 1s into a string of 0s under the following constraints.
The right-most bit can always be complemented. Any other bit can be complemented if and only if
the bit to its immediate right is a 1 and all other bits to its right (if there are any) are 0.
c. Design an algorithm for testing a tic-tac-toe board to see if there has been a winner.
d. Design an algorithm for finding a path through a maze.
7. I like to use the problem "Design an algorithm for predicting the sum of the top and bottom faces
of four dice." to emphasize the distinction between algorithm discovery and algorithm representation.
In this case it’s the discovery step that may be tough. (Opposing faces on a die always add to seven.
Thus, the opposing faces on four dice must add to 28. Once this is discovered, the underlying
algorithm can be expressed as the single statement "print the value 28").
8. A good exercise for "experienced" programmers who think loop control is trivial is to design an
iterative algorithm for printing all possible permutations of a list of letters. (This is also a good
example of how the use of recursion can simplify matters.)
27
Count = 1
while (Count != 5):
print(Count)
Count = Count + 1
9. The conditions appearing in the statements would be negations of each other. That is, the statement
repeat (. . .) until (x is zero) is equivalent to do (. . .) while (x is not zero).
10. Here's an outline of one possible solution.
Starting from the right end of the input, find the first digit that is
smaller than the one to its right. (If there isn't such a digit, no the
input cannot be rearranged to represent a larger value.)
Call the position in the input in which this digit was found the target
position.
Interchange the digit found above with the smallest digit to its right
that is still larger than itself.
Sort the digits to the right of the target position in descending order
from right to left.
11. Suppose N is the given integer. Then the following will work. You may want to ask your students
how this solution could be made more efficient.
X = 1
while (X N):
if (X divides N):
print(X)
X = X + 1
12. Start with a date whose day of the week is known. Figure out how many days are between that
date and the given date (remember leap years). Then divide that total by seven and use the remainder
to determine the displacement from the known day.
13. Pseudocode is a relaxed version of a programming language used to jot down ideas. A formal
programming language prescribes strict rules of grammar that must be obeyed.
14. Syntax refers to the way something is expressed, whereas semantics refers to what is being
expressed.
15. W = 6, X = 9, Y = 5, Z = 1. Most will get their foot in the door by realizing that the carry has to be
1. Then they may figure out that X must be 9 since X + Y = 1Y.
16. V = 0, W = 4, X = 1, Y = 3, Z = 9. Most will get their foot in the door by realizing that X must be 1
since X times XY is XY. Then they may discover that Z must be 9 since it must be a one-digit perfect
square (Y times Y) which when added to one produces a carry.
17. X = 1, Y = 0. A simple algorithm would be to try X = 1 and Y = 0 first. If that works, report the
solution. Otherwise, try X = 0 and Y = 1. If that works, report the solution. Otherwise, report that there
is no solution.
18. Andrews and Blake go through the shaft first (2 minutes), and Andrews returns with the lantern
(1 minute). Then, Johnson and Kelly go through (8 minutes), and Blake returns with the lantern (2
minutes). Finally, Andrews and Blake go through again (2 minutes). The total travel time is 2 + 1 + 8
+ 2 + 2 = 15 minutes.
28
19. They are the same. Suppose the volume of the small glass is V and x units of water are poured into
the large glass. Then the large glass contains V + x units of liquid—V units of wine and x units of
water. When the small glass is filled from the large one, x units of liquid are returned to the small
glass of which V/(V + x) is wine. Therefore, the small glass will end up with xV/(V + x) units of wine.
Furthermore, xx/(V + x) units of water will be returned to the small glass, meaning that exactly x –
xx/(V + x) = xV/(V + x) units of water will be left in the large glass.
20. Approximately 122 meters. Let the distance between the hives be y. Since each bee flies at a
constant speed, the ratio of the distances traveled must be the same each time the meet. Therefore,
50/(y – 50) = (y + 20)/(2y – 20). Solving for y implies that y is approximately 7.5 meters or 122 meters.
21. How about this?
def SubStringSearch(FirstString, SecondString):
P = 0
Success = false
while (P + length of FirstString) <= (length of SecondString)
and Success == false):
N = 1
while (P + Nth character in SecondString ==
Nth character in FirstString):
N = N + 1
if (N == length of FirstString):
Success = true
P = P + 1
return Success
22. Body: Everything indented below the while
Initialization: The first two assignment statements
Modification: The last assignment statement (Some could argue that it is the last three
assignment statements.)
Test: while (Current < 100)
The output will be 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89.
23. This is a recursive version of Problem 13. Its output will be 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89.
24. Move the print statement below the recursive call to MysteryWrite.
25. When searching for J: H, L, J
When searching for Z: H, L, N, 0
26. Sequential search: 3000
Binary search: at least 13
27. a. Count 5 b. Count = 1 c. (Count 5) or (Total 56)
28. The body consists of the indented statements below the while. It will be executed twice. The
proposed modification would produce a nonterminating loop.
29. It may not terminate because the value in Count may never be exactly 1 (due to round-off errors).
30.
29
Another document from Scribd.com that is
random and unrelated content:
“I declare you’ll make me lose my temper with you!” said Mrs. Palmer
violently. “Answer me this instant.”
“I went to the cinema.”
“Who took you?”
“That fellow in the office—that Leary boy.”
“Why couldn’t you come in last night and say where you’d been, then?
The fact is, Elsie, you’re telling me a pack of lies, and I know it perfectly
well. You can’t take your mother in, let me tell you, whatever you may
think, I’m sure I don’t know what to do with you. I sometimes think
you’d better go and live with your aunties; you’d find Aunt Gertie strict
enough, I can tell you.”
Elsie knew this to be true, and was fiercely resolved never to put it to the
test.
“What you want is a thorough good whipping,” said Mrs. Palmer,
already absent-minded and preoccupied with preparations for breakfast.
“Put that kettle on, Elsie, and be quick about it. And I give you fair
warning that the very next time I have to speak to you like this—(see if
that’s the girl at the door—it ought to be, by this time)—the very next
time, I’ll make you remember it in a way you won’t enjoy, my lady.”
Mrs. Palmer’s active display of wrath was over, and Elsie knew that she
had nothing to do but to keep out of her mother’s way for the next few
days.
She helped to get the breakfast ready in silence. She was too much used
to similar scenes to feel very much upset by this one; nevertheless it
influenced her in favour of acting upon Irene Tidmarsh’s advice.
She knew very well that it would not be as easy to hoodwink Mrs.
Palmer over a week-end spent out of London as she had pretended to Mr.
Williams. Elsie was still afraid of her mother, and believed that she
might quite well carry out her threat of sending her daughter to live with
the two aunts.
Her chief pang was at relinquishing the thought of the pink silk
underclothes, but she endeavoured to persuade herself that they might
still be hers, when she should be on the point of marrying Mr. Williams.
After all, it would be more satisfactory to own them on those terms than
to be obliged to put them away after two days into hiding, in some place
—and Elsie wondered ruefully what place—where they should not be
spied out by Geraldine.
She went to the office as usual and was a good deal disconcerted when
Fred Leary announced that “the Old Man” had telephoned to say that he
was called away on business, and should not be back for two days.
Elsie, rather afraid that her own determination might weaken, decided to
write to him, sending the letter to his home address.
Her unformed, back-sloping hand, covered one side of a sheet of
notepaper that she bought in the luncheon hour.
“D M .W ,
“One line to tell you that I have thought over your very kind
suggestion about a holiday, but do not feel that I can say yes
to same. Dear Mr. Williams, it is very kind of you, but I
cannot feel it would be right of me to do as you ask, and so I
must say no, hoping you will not be vexed with me. I do want
to be a good girl. So no more, from
“Your little friend,
“E .”
VIII
I took Elsie exactly three months to bring Mr. Williams to the point
predicted by Irene Tidmarsh.
During that time she was quiet, and rather timid, scrupulously exact in
saying “sir” and very careful never to be heard laughing or chattering
with Fred Leary.
Williams at first made no allusion to her note. When at last he spoke of
it, he did so very much in his ordinary manner.
“I was sorry to get your little note the other day, Elsie, and to see that
you don’t quite trust me after all.”
“Oh, but I do,” she stammered.
He shook his head. “I’m afraid not. I’m afraid my little friend isn’t quite
as staunch as I fancied. It doesn’t matter. Perhaps some day you’ll know
me better.”
“It wasn’t anything like that. It was just that I—I thought mother
wouldn’t like it,” simpered Elsie. “It didn’t seem to me to be quite right.”
“It would have been quite right, or I shouldn’t have asked you to do it,”
he replied firmly. “I’m a man of great experience, Elsie, a good many
years older than you are, and you may be quite sure that I should never
mislead you. But I see I made a mistake, you are not old enough to have
the courage to be unconventional.”
He looked hard at her as he spoke, but Elsie’s vanity was not of the sort
to be wounded at the term of which he had made use. She merely
drooped her head and looked submissive.
A month later he asked her, in thinly veiled terms, whether she had yet
changed her mind.
“I shan’t ever change it,” Elsie declared. “I daresay I’ve sometimes been
rather silly, and not as careful as I ought, but I know very well that it
wouldn’t do for me to act the way you suggest. Why, you’d never respect
me the same way again, if I did!”
She felt that the last sentence was a masterpiece. Williams shrugged his
shoulders.
“Come, Elsie, let’s understand one another. You’re not ignorant, a girl
like you must have had half a dozen men after her. And then what about
that doctor fellow—Woolley?”
“What about him?”
“That’s what I’m asking you. Something happened to cause the
unpleasantness between Mrs. Woolley and yourself, and I’ve a very
shrewd suspicion that I know what it was.”
“Then I needn’t tell you,” said Elsie feebly.
“That isn’t the way to speak.”
His low voice was suddenly nasty, and she felt frightened. “I’m sorry.”
“Yes. Don’t do it again, Elsie. How far did Woolley go? That’s what I
want to know.”
“He—he frightened me. He tried to kiss me.”
“And succeeded. Anything else?”
“Mr. Williams!”
He gazed at her stonily. “Well,” he said at last, “I’m half inclined to
believe you. How old are you?”
“Seventeen.”
“Seventeen!” he repeated after her, and his accent was covetous. “You
should be very innocent, at seventeen, Elsie—very innocent and very
pure. Now, my dear little late wife, when we were married, although she
was a good deal older than you are, knew nothing whatever. Her husband
had to teach her everything. That’s as it should be, Elsie.”
A certain prurient relish of his own topic, in Williams’ manner, affected
Elsie disagreeably. Neither did she like his reference to Mrs. Williams.
She was glad that the conversation should at that point be interrupted by
the entrance of the austere Mr. Cleaver.
Suspense was beginning to make her feel very irritable. She now wanted
Williams to propose marriage to her, but had begun to doubt his ever
doing so. He continued to look at her meaningly, and to lay his rather
desiccated hand from time to time on her shoulder, or upon the thin
fabric of her sleeve, with a lingering, caressing touch. Elsie, however,
had inspired too many men to such demonstrations to feel elated by
them, and her employer’s proximity roused in her little or no physical
response.
One day, to her surprise, he brought her a present.
“Open it, Elsie.”
She eagerly lifted the lid of the small cardboard box.
Inside was a large turquoise brooch, shaped like a swallow, with
outspread wings.
She knew instantly that it had belonged to his dead wife, but the
knowledge did not lessen her pleasure at possessing a trinket that she
thought beautiful as well as valuable, nor her triumph that he should
wish to give it to her.
“Oh, I say, how lovely! Do you really mean me to keep it?”
“Yes, really,” Mr. Williams assured her solemnly.
“But I couldn’t! It’s too lovely—I mean to say, really it is!”
“No, it isn’t, Elsie. You must please put it on, and let me have the
pleasure of seeing you wear it.”
“Put it on for me, then,” murmured Elsie, glancing up at him, and then
down again.
He took the ornament from her with hands that fumbled. “Where?”
“Just here.”
She indicated the round neck of her transparent blouse, just below the
collar-bone.
He stuck the pin in clumsily enough, and she stifled a little scream as it
pricked her, but remained passive under his slowly-moving, dry-skinned
fingers.
“There! I’m sorry there isn’t a looking-glass, Elsie.”
“Oh, I’ve got one! Don’t look, though!”
She stooped, pulled up her skirt, revealing a plump calf, and in a flash
had pulled out a tiny combined mirror and powder-puff from the top of
her stocking. She had no other pocket.
Williams did not utter a sound. He only kept his pale grey eyes fixed
gleamingly upon her.
“Are you shocked?” Elsie giggled. “I didn’t ought to, I suppose, but
really it’s hard to know what else to do.”
She peeped into the tiny looking-glass. “Isn’t it pretty!”
“You are,” said Williams awkwardly. “How are you going to thank me,
Elsie?”
He always seemed to take pleasure in repeating her name.
“How do you suppose?”
“You know what I’d like.”
He came nearer to her, and put his hands upon her shoulders. Although
Elsie was short, he was very little taller.
She shut her eyes and put her head back, her exposed throat throbbing
visibly. She could feel his breath upon her face, when suddenly she
ducked her head, twisting out of his grasp, and cried wildly:
“No, no! It isn’t right—I oughtn’t to let you! Oh, Mr. Williams, I’d rather
not have the brooch, though it’s lovely. But I can’t be a bad girl!”
He had taken a step backwards in his disconcerted amazement. “What on
earth——Why, Elsie, you don’t think there’s any harm in a kiss, do
you?”
“I don’t know,” she muttered, half crying. “But you make me feel so—so
helpless, somehow, Mr. Williams.”
Purest instinct was guiding her, but no subtlety of insight could have
better gauged the effect of her implication upon the little solicitor’s
vanity.
He drew himself up, and expanded the narrow width of his chest.
“You’re not frightened of me, little girl, are you?”
“I—I don’t know,” faltered Elsie.
“I can assure you that you needn’t be. Why, I—I—I’m very fond of you,
surely you know that?”
Elsie felt rather scornful of the lameness of his speech. She saw that he
was afraid of his own impulses, and the knowledge encouraged her.
“Here, Mr. Williams,” she said rather tremulously, holding out the
turquoise brooch.
He closed her hand over it. “Keep it. Are you fond of jewellery?”
“Yes, very.”
“It’s natural, at your age. I’d like to give you pretty things, Elsie, but you
mustn’t be such a little prude.”
“Mother always told me that one shouldn’t take a present—not a
valuable present—from a man, without he was a relation or—or else
——” She stopped.
“Or else what?”
“He’d asked one to marry him,” half whispered Elsie.
Williams recoiled so unmistakably that for a sickening instant she was
afraid of having gone too far.
Genuine tears ran down her face, and she did not know what to say.
“Don’t cry,” said the solicitor dryly. “I’d like you to keep the brooch, and
you can thank me in your own time, and your own way.”
“Oh, how good you are!”
She was relieved that he said no more to her that day.
She wore the brooch on the following morning, and fingered it very
often. Williams eyed her complacently.
She began to notice that he was taking some pains with his own
appearance, occasionally wearing a flower in his coat, and discarding the
crêpe band round his arm. She even suspected, from a certain smell
noticeable in the small office, that he was trying the effect of a hair-dye
upon his scanty strands of hair. Elsie mocked him inwardly, but felt
excited and hopeful.
When Williams actually did ask her to marry him, Elsie’s head reeled
with the sudden knowledge of having achieved her end. He had offered
to take her for a walk one Sunday afternoon, and they were primly going
across the Green Park.
To Elsie’s secret astonishment, he had neither put his arm round her
waist nor attempted to direct their steps towards a seat beneath one of the
more distant trees. He simply walked beside her, with short little steps,
every now and then jerking up his chin to pull at his tie, and saying very
little.
Then, suddenly, it came.
“Elsie, perhaps you don’t know that I’ve been thinking a great deal about
you lately.” He cleared his throat. “I—I’ve been glad to see that you’re a
very good girl. Perhaps you’ve not noticed one or two little tests, as I
may call them, that I’ve put you through. We lawyers learn to be very
cautious in dealing with human nature, you know. And I’m free to admit
that I thought very highly of you after—after thinking it over—for the
attitude you took up over that little trip we were going to take together.
Not, mind you, that you weren’t mistaken. I should never, never have
asked you to do anything that wasn’t perfectly right and good. But your
scruples, however unfounded, made a very favourable impression on
me.”
He stopped and cleared his throat again.
Intuition warned Elsie to say nothing.
“A young girl can’t be too particular, Elsie. But I don’t want to give up
our plan—I want my little companion on holidays, as well as on work
days. Elsie,” said Mr. Williams impressively, “I want you to become my
little wife.”
And as she remained speechless, taken aback in spite of all her previous
machinations, he repeated:
“My dear, loving little wife.”
“Oh, Mr. Williams!”
“Call me Horace.”
Elsie very nearly giggled. She felt sure that it would be quite impossible
ever to call Mr. Williams Horace.
“Let’s sit down,” she suggested feebly.
They found two little iron chairs, and Mr. Williams selected them
regardless of their proximity to the public path.
When they sat down, Elsie, really giddy, leant back, but Mr. Williams
bent forward, not looking at her, and poking his stick, which was
between his knees, into the grass at their feet.
“Of course, there is a certain difference in our ages,” he said, speaking
very carefully, “but I do not consider that that would offer any very
insuperable objection to a—a happy married life. And I shall do my
utmost to make you happy, Elsie. My house is sadly in want of a
mistress, and I shall look to you to make it bright again. You will have a
servant, of course, and I will make you an allowance for the
housekeeping, and, of course, I need hardly say that my dear little wife
will look to me for everything that concerns her own expenditure.”
He glanced at her as though expecting her to be dazzled, as indeed she
was.
It occurred to neither of them that Elsie’s acceptance of his proposal was
being tacitly taken for granted without a word from herself. She
wondered if he would mention Mrs. Williams, but he did not do so.
He continued to talk to her of his house, and of the expensive furniture
that she would find in it, and of the fact that she would no longer have to
work.
All these considerations appealed to Elsie herself very strongly, and she
listened to him willingly, although a sense of derision pervaded her mind
at the extraordinary aloofness that her future husband was displaying.
At last, however, he signed to a taxi as they were leaving the park, and
said that he would take her to have some tea. Almost automatically, Elsie
settled herself against him as soon as the taxi had begun to move.
Rather stiffly, Williams passed his arm round her. His first kiss was a
self-conscious, almost furtive affair that Elsie received on her upraised
chin.
Intensely irritated by his clumsiness, she threw herself on him with
sudden violence, and forced her mouth against his in a long, clinging
pressure.
“H , Elsie!”
“Hallo, Geraldine!”
“You’re quite a stranger, aren’t you? I think it’s about a year since we
had the honour of seeing your majesty last.”
“Well, now I have come, aren’t you going to take the trouble to invite me
to come in?” asked Elsie good-humouredly.
“There’s a visitor of mine in the drawing-room.”
“Who is it? Aunt Ada?”
“No, not Aunt Ada, Miss Smarty. It’s a friend of mine, I tell you, who I
knew at the office during the war.”
“Well, you can introduce me to her, I suppose,” said Elsie carelessly.
She noticed that Geraldine’s hair was not, as it generally was, in curling-
pins, and that she was wearing a new dress, of an unbecoming shade of
emerald green. Geraldine always went wrong over her clothes, Elsie
reflected complacently. She herself wore a new black picture hat, and it
was partly from the desire to show herself in it that she had come to her
old home.
“Where’s mother?”
“Out.”
“What a mercy!”
Elsie walked into the familiar drawing-room, feeling glad that she no
longer lived at Hillbourne Terrace, under her mother’s dominion, and
forced to share a bedroom with the fretful Geraldine.
A young man of two- or three-and-twenty was sitting in the drawing-
room, and rose to his feet as Elsie and Geraldine came in.
“This is my sister, Mrs. Horace Williams. Elsie, this is my friend, Mr.
Morrison,” said Geraldine with pride.
Elsie was immediately conscious of a quickened interest. The young man
was of a type that appealed strongly to her; dark and tall, with very