'Sorting an Array in Ruby without using Sort method
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?
Solution 1:[1]
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.
Solution 2:[2]
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.
Solution 3:[3]
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])
Solution 4:[4]
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
Solution 5:[5]
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
Solution 6:[6]
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
Solution 7:[7]
#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]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kyle |
| Solution 2 | V K Singh |
| Solution 3 | Melissa Quintero |
| Solution 4 | Vieenay Siingh |
| Solution 5 | Adrian Mole |
| Solution 6 | Ashwin |
| Solution 7 | Ganesh Kaliannan |
