Reputation: 6837
I'm trying to use the bubble sort method to sort an array of only three numbers. The code I'm using is below.
def my_sort(list)
return list if list.size <= 1
swapped = false
while !swapped
swapped = false
0.upto(list.size-2) do |i|
if list[i] > list[i+1]
list[i], list[i+1] = list[i+1], list[i]
swapped = true
end
end
list
end
my_sort([3,1,2])
Here is the error message I keep getting:
Syntax error, unexpected $end, expecting keyword_end
I was just wondering which end shouldn't be included?
Upvotes: 2
Views: 9172
Reputation: 11
arr = [1,2,8,4,5,3,1,0,6]
0.upto(arr.size - 1) do |i|
(i+1).upto(arr.size - 1) do |j|
if arr[i] > arr[j]
arr[j],arr[i] = arr[i],arr[j]
end
end
end
Upvotes: 0
Reputation: 1
def sort(arr)
arr_len = arr.length - 1
swap = true
while swap
swap = false
arr_len.times do |i|
if arr[i] > arr[i+1]
arr[i],arr[i + 1] = arr[i + 1],arr[i]
swap = true
end
end
end
p arr
end
Upvotes: 0
Reputation: 1254
This looks a better and quicker one.
arr = [1,5,7,2,3,50,78,34, 1, 15, 89, 8]
def sort_array(arr)
arr.size.times do
arr.map.with_index do |num, index|
next if index.eql?(arr.size - 1)
arr[index], arr[index+1] = arr[index+1], arr[index] if num > arr[index+1]
end
end
end
Call the above method as print sort_array(arr)
to get expected result.
Upvotes: 2
Reputation: 867
What worked for me, is below.
def my_sort(list)
n = list.length
loop do
swapped = false
(n-1).times do |i|
if list[i] > list[i+1]
list[i], list[i+1] = list[i+1], list[i]
swapped = true
end
end
break if not swapped
end
list
end
Upvotes: 0
Reputation: 1
#Using bubble sort algorithm in ruby
a = [1,5,7,2,3,50,78,34,89]
a.size.times.each do |t|
i=0
a.each do |b|
if b > a[i+1]
a[i],a[i+1] = a[i+1],a[i]
end
i+=1 if i < a.size-2
end
end
print a
#output: [1, 2, 3, 5, 7, 34, 50, 78, 89]
Upvotes: -1
Reputation: 191
Your code works for that specific array. Because your loop is looking if the next element is higher, then swipe. But what about more elements in the array? This is recursive solution for all cases.
def my_sort(list, new_array = nil)
return new_array if list.size <= 0
if new_array == nil
new_array = []
end
min = list.min
new_array << min
list.delete(min)
my_sort(list, new_array)
end
puts my_sort([3, 1, 2, 20, 11, 14, 3, 6, 8, 5])
Upvotes: 1
Reputation: 30442
You're missing an end
after swapped = true
. It would be best to indent your code thoroughly and accurately to avoid this kind of problem:
def my_sort(list)
return list if list.size <= 1
swapped = false
while !swapped
swapped = false
0.upto(list.size-2) do |i|
if list[i] > list[i+1]
list[i], list[i+1] = list[i+1], list[i]
swapped = true
end
end
end
list
end
Upvotes: 3
Reputation: 22268
You're missing an end
if list[i] > list[i+1]
list[i], list[i+1] = list[i+1], list[i]
swapped = true
end # <--------------------------------------------------------
Edit: As the other answer mentions, indent your code to make these errors more visible.
Upvotes: 3