baumanj
4/5/2006 6:04:00 PM
You're missing
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.
adamw@ratio.co.uk wrote:
> Hi
> I'm new to programming and Ruby. I've tried to write my own sorting
> method. It sorts well except the 3, 5, 7 element etc. It doesn't do the
> first check after repeating "...times do" (simply pushes the first
> element before looking for the smallest) and I have no idea why... If
> someone could look at the code and give me the answer please:
>
> 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