Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

"sort an array" method

0 views
Skip to first unread message

ad...@ratio.co.uk

unread,
Apr 5, 2006, 1:07:25 PM4/5/06
to
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

bau...@gmail.com

unread,
Apr 5, 2006, 2:04:06 PM4/5/06
to
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.

ad...@ratio.co.uk

unread,
Apr 6, 2006, 8:28:03 AM4/6/06
to
Thanks a lot :)
I understand that without knowing "n" it didn't run the first
"while..end" loop at all, and just pushed the first available element?
Basically I'm following "Learn to Program" by Chris Pine and it's one
of the exercises you should do using just the basic tools introduced so
far in the book. I'm afraid "array.delete_at()" was already cheating a
bit, not mentioning "array.min".

0 new messages