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?
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.
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.
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.
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.
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With