Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the Bubble sort method for an array in Ruby [closed]

I'm trying to implement the Bubble sort method into an easy coding problem for Ruby, but I'm having some trouble. I understand the idea is to look at the value of the first element and compare it to the value of the second element and then swap them accordingly, but I can't seem to do it in an actual problem. Would anyone be willing to provide a brief example of how this might work in Ruby?

like image 518
ppreyer Avatar asked Jun 18 '12 21:06

ppreyer


People also ask

What is bubble sort in Ruby?

Ruby Course One of the simpler (but more processor-intensive) ways of sorting a group of items in an array is bubble sort, where each element is compared to the one next to it and they are swapped if the one on the left is larger than the one on the right. This continues until the array is eventually sorted.

Is bubble faster than merge?

Merge Sort - Is a 'Divide and Conquer' algorithm that splits a list into discrete elements and then merges the elements back together in order. A merge sort is quicker and more efficient than a bubble sort when using longer lists.

What is <=> in Ruby sort?

The Ruby sorting operator ( <=> )Also called the spaceship operator, takes two parameters and returns one of three values. 0 if the two parameters are equal. -1 if the first parameter is less than the second parameter. 1 if the first parameter is greater than the second parameter.

What is bubble sort in array?

Bubble sort is a data sorting algorithm that works by randomly copying elements from the first array into a smaller second array, and then reversing the order of these arrays.


2 Answers

Correct implementation of the bubble sort with a while loop

def bubble_sort(list)
  return list if list.size <= 1 # already sorted
  swapped = true
  while swapped do
    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] # swap values
        swapped = true
      end
    end    
  end

  list
end
like image 154
cluv Avatar answered Oct 26 '22 09:10

cluv


arr = [4,2,5,1]
loop until arr.each_cons(2).with_index.none?{|(x,y),i| arr[i],arr[i+1] = y,x if x > y}
p arr #=> [1, 2, 4, 5]
like image 35
steenslag Avatar answered Oct 26 '22 11:10

steenslag