def sorts a # some array
u = [] # unsorted array
s = [] # sorted array
n = a.length
(n / 2).times do
while n > 1 # find the smallest in a - bubble sort
while a[n - 1] < a[n - 2]
tmp = a[n - 2]
a[n - 2] = a[n - 1]
a[n - 1] = tmp
end
n -= 1
end
s.push a[0]
a.delete_at(0)
print s # debug
puts ''
print a
puts ''
u = a
a = []
n = u.length
while n > 1 # find the smallest in u - bubble sort
while u[n - 1] < u[n - 2]
tmp = u[n - 2]
u[n - 2] = u[n - 1]
u[n - 1] = tmp
end
n -= 1
end
s.push u[0]
u.delete_at(0)
print s # debug
puts ''
print u
puts ''
a = u
u = []
end
if n%2 == 1 # move the last element if a.length was an odd number
s.push a[0]
a.delete_at(0)
print s # debug
puts ''
print a
puts ''
end
print s
end
sorts [ 'd', 'g', 'e', 'b', 'a', 'f', 'c' ]
PRODUCES:
a
dgebcf
ab
dgecf
abd
gecf
abdc
gef
abdcg
ef
abdcge
f
abdcgef
abdcgef
n = a.length
after the
(n / 2).times do
Also, there is a lot of unnessary duplicated code. I understand the
point is that you're trying to learn, so you don't want to take
shortcuts like calling Array.min and such. Here's the version I come up
with without using any fancy library calls:
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
I hope that helps.