I'm a beginner going through Chris Pine's online book & exercises.
One of them required me to alphabetize a list of words WITHOUT using the
.sort method.
I discovered the following bubble sort algorithm online and understand
it except for one thing.
How is it able to determine that array|first| points to position 0 on
the array, and array[second] points to position 1, in order to make the
comparison?
To me, it looks like both array[first] and array[second] would equal one
another.
array.each_index do |first|
array.each_index do |second|
if array[first] < array[second]
array[first], array[second] = array[second], array[first]
end
end
end
You misunderstand the code. "first" and "second" aren't fixed values.
They are the block parameters belonging to the two iterators, so their
value will change on each iteration.
Have a look at the outer iterator first:
array.each_index do |first|
end
This iterator loops over the indices of "array". On each iteration, the
current index is assigned to the "first" parameter. So if array is ['x',
'z', 'y'] for example, the parameter will be assigned the values 0, 1
and 2 subsequently.
You can test this:
array.each_index do |first|
puts first
end
Then there is also an inner iterator, which also loops over the indices
of array. This means: While the outer iterator is going through the
indices 0, 1, 2, 3, ..., the inner iterator will do the same on every
step.
See for yourself:
array.each_index do |first|
array.each_index do |second|
puts "first (outer): #{first}, second (inner): #{second}"
end
end
By the way, the code you posted is *not* bubble sort. I do not even know
it, but it is definitely a bad algorithm, since it involves a lot of
unnecessary element swapping.
The reason I google'd and used that algorithm is because Chris Pine
states that we should try to alphabetize an array of user-input words,
without using the sort method: http://pine.fm/LearnToProgram/?Chapter=07
Thus, I wrote:
word = 'word'
listOfWords = []
while word != ''
puts 'Enter a word and press enter: '
word = gets.chomp.downcase
listOfWords.push word
end
listOfWords.pop
But became stuck at how I could alphabetize the array, using only the
things we have learned so far.
If you have a better way I could accomplish this without using the
previously described algorithm, I would very much appreciate it. It's
something I've been struggling with all night.
If you have a better way I could accomplish this without using the
previously described algorithm, I would very much appreciate it. It's
something I've been struggling with all night.
Well, you can use *any* sorting algorithm. You may also stick to the one
above. I didn't say it's wrong, I just said it's inefficient (and not
bubble sort).
Typical and simple sorting algorithms are insertion sort, selection sort
and bubble sort (the actual one). You'll find good explanations at
wikipedia:
And if you're looking for implementations, this is a good source: