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