Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running Through a Ruby Bubble Sort

Tags:

I'm writing a bubble sort code as part of a beginner's class on Ruby. I know that (array.length - 1).times do |i| is bad practice because I don't need to run to the end of an array each time. (In my example, [5,4,3,2,1] five is moved to the end during the first run through, the four is in its right place by the end of the second, etc., so there's no need to examine those numbers again):

def bubble_sort(array)
  (array.length - 1).times do
    (array.length - 1).times do |i|
      array[i], array[i+1] = array[i+1], array[i] if array[i] > array[i+1]
    end 
  end
end

bubble_sort([5,4,3,2,1])

Is there a neat way to tell the method to examine one fewer element of the array each time?

like image 694
dedaumiersmith Avatar asked May 11 '16 12:05

dedaumiersmith


People also ask

What is the best running time for bubble sort?

The bubble sort is made up of only a few lines of code. With a best-case running time complexity of O(n), the bubble sort is helpful in determining whether or not a list is sorted. Other sorting methods frequently cycle through their entire sorting sequence, taking O(n2) or O(n log n) time to complete.

How many times does bubble sort need to run?

The algorithm for bubble sort requires a pair of nested loops. The outer loop must iterate once for each element in the data set (of size n) while the inner loop iterates n times the first time it is entered, n-1 times the second, and so on.

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. However, it uses more memory and can take longer to sort shorter lists.

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.


1 Answers

What about adding a variable j in the outer loop and substracting j from array.length - 1 ?

It would look like that:

def bubble_sort(array)
  (array.length - 1).times do |j|
    (array.length - 1 - j).times do |i|
      array[i], array[i+1] = array[i+1], array[i] if array[i] > array[i+1]
    end 
  end
end

bubble_sort([5,4,3,2,1])
like image 136
Pholochtairze Avatar answered Sep 28 '22 04:09

Pholochtairze