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.
#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]
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
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
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])
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.
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.