HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrubyMinor

Bubble sort in Ruby

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
sortbubbleruby

Problem

For practice, I tried implementing Bubble sort in Ruby. I wasn't very sure how nested for loops would look like in Ruby. Is this the 'right way' to do this in Ruby? I found this question, but it looks much more complicated with stacks.

def bubble_sort(list)
  n = list.length
  n.downto(2) do |i|
    0.upto(i-2) do |j|
      if list[j] > list[j+1]
        list[j],list[j+1] = list[j+1],list[j]
      end
    end
  end
  puts list
end


This is the code I wrote in Python which I then translated into Ruby code above.

def bubbleSort(alist):
    n = len(alist)
    for i in range(n, 1, -1):
        for j in range(i-1):
            if alist[j] > alist[j+1] :
                alist[j],alist[j+1] = alist[j+1],alist[j]

Solution

A significant difference between your Python and Ruby implementations is that the Ruby one prints the sorted list at the end.
It shouldn't, just like the Python version doesn't.
The function should do just one thing, in this example just sort.

Also, I suggest to putting a space after commas separating variable lists, like this:

list[j], list[j+1] = list[j+1], list[j]


I don't know much Ruby,
but I don't think a bubble sort can get any better than this.
You are using nice Ruby-like idiomatic expressions like downto and upto,
and the rest is clear, straight code.
Anything more clever than this would be too clever for the purpose,
in my opinion.

A tiny final remark about the Python implementation:
snake_case is recommended for function names instead of camelCase.

Code Snippets

list[j], list[j+1] = list[j+1], list[j]

Context

StackExchange Code Review Q#90950, answer score: 3

Revisions (0)

No revisions yet.