I have been working through Chris Pine's tutorial for Ruby and am currently working on a way to sort an array of names without using sort
.
My code is below. It works perfectly but is a step further than I thought I had got!
puts "Please enter some names:"
name = gets.chomp
names = []
while name != ''
names.push name
name = gets.chomp
end
names.each_index do |first|
names.each_index do |second|
if names[first] < names[second]
names[first], names[second] = names[second], names[first]
end
end
end
puts "The names you have entered in alphabetical order are: " + names.join(', ')
It is the sorting that I am having trouble getting my head around.
My understanding of it is that each_index
would look at the position of each item in the array. Then the if
statement takes each item and if the number is larger than the next it swaps it in the array, continuing to do this until the biggest number is at the start. I would have thought that this would just have reversed my array, however it does sort it alphabetically.
Would someone be able to talk me through how this algorithm is working alphabetically and at what point it is looking at what the starting letters are?
Thanks in advance for your help. I'm sure it is something very straightforward but after much searching I can't quite figure it out!
Your understanding is just a bit off.
You said:
But this is not what the
if
statement is doing.First, the two blocks enclosing it are simply setting up iterators
first
andsecond
, which each count from the first to the last element of the array each time through the block. (This is inefficient but we'll leave discussion of efficient sorting for later. Or just see Brian Adkins' answer.)When you reach the if statement, it is not comparing the indices themselves, but the
names
which are at those indices.You can see what's going on by inserting this line just before the
if
. Though this will make your program quite verbose: