Hi,
I worked through the exercise in Chris P.'s tutorial where you sort
an array without using the sort method
(Arrays and Iterators - Learn to Program), and I got a working
solution, but I’m curious about how to improve it. Can anyone offer
some tips? I’ve looked at a couple of solutions here like this one:
def bubblesort(a)
(a.length-1).downto(0) do |i|
puts a.to_s
0.upto(i-1) do |j|
if a[j] > a[j+1]
a[j], a[j+1] = a[j+1], a[j] # swap
end
end
end
end
This is pretty much over my head but it looks a lot cooler. I would
like to write this way. What I don’t understand about the above is
this:
if a[j] > a[j+1]
a[j], a[j+1] = a[j+1], a[j] # swap
I’m reading this to mean if the jth position in a is lexically greater
than the jth + 1 position, then those two positions switch places, for
example [z, m, p, a] becomes [ m, p, a, z], but then how does ‘a’ get
to the top of the array? And is that formula of a[j], … = … a
simple equation you can use in many different ways or a more specific
method?
I tried to use only what I had learned in the tutorial up to the point
of the exercise, though I admit I flaked and looked up what the delete
method was. Here’s what I wrote:
declare variables and arrays
word = ‘start’
unsortedList = []
sortedList = []
lowercase = []
trues = 0
say hello
puts 'Hello. Type a word, press [ENTER] after every word, [ENTER] when
done: ’
get the input
while word != ‘’
word = gets.chomp
unsortedList.push word
end
downcase the list so we can sort it
unsortedList.each do |i|
lowercase.push i.downcase
end
sort the list
while lowercase.length > 0
lowercase.each do |i|
lowercase.each do |j|
if (i <= j)
trues = trues + 1
end
end
if (trues == lowercase.length)
sortedList.push i
lowercase.delete(i)
trues = 0
else
trues = 0
end
end
end
see the sorted list
puts ‘-’ * 60
puts ‘Your sorted list, dude:’
puts sortedList
done
Needless to say this looks much more clunky to me though it was still a
lot of fun to do. If anyone can help with some of my questions or
comment on my solution that would be awesome,
thanks, George