Hey all,
I’m going through Chris P.‘s Learning to Program book, and there’s
a problem in Chapter 10 that asks you to write your own sorting method
without using #sort. I had initially attempted to do this using two
arrays and iterating through one of them, attempting to compare the
words inside the array, find the smallest word, and pass it to another
array (we’ll call it sorted_words). This failed, however. I’ve been
working on it for the better part of a day, and it’s not working. I took
a peek at Chris’ solution. Here is the pastebin link with my comments:
http://pastebin.com/9p5fUbnL. The comments are my attempts to understand
Chris’ thought process, which he describes here:
“What strikes me as probably the easiest way to do this is to keep two
more lists around: one will be our list of already-sorted words, and the
other will be our list of still-unsorted words. We’ll take our list of
words,find the “smallest” word (that is, the word that would come first
in the dictionary), and stick it at the end of the already-sorted list.
All of the other words go into the still-unsorted list. Then you do the
same thing again but using the still-unsorted list instead of your
original list: find the smallest word, move it to the sorted list, and
move the rest to the unsorted list. Keep going until your still-unsorted
list is empty.”
I have a few questions. First, what is the point of the first method
(def sort)? What is its function? I don’t get why it’s necessary.
Second, although I tried to work through the iteration of unsorted.each
(as noted in my comments), it’s just not clear to me what is going on.
My third question is a bit more abstract. When I first looked at this
problem at no point did it occur to me to do anything Chris did in his
solution. This worries me. I’ve been teaching myself Ruby for about 6-7
months and I know I will always be learning new things even years from
now. But the solution that Chris came up with did cross my mind for a
second. Does this kind of thinking eventually come with exposure / more
study? I’m a little deflated with how much I worked on this problem
fruitlessly, and how far away I was from the actual solution. Granted I
know there are many solutions to problems in Ruby, but the fact that I
still can’t grasp exactly what this program is doing is making me doubt
myself.