"sort an array" method

A

adamw

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
 
B

baumanj

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.
 
A

adamw

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".
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,480
Members
44,900
Latest member
Nell636132

Latest Threads

Top