I’m trying to understand the given solution to a programing problem that uses the bubble sort algorithm to sort through an array. I know there are other, probably much easier ways to satisfy the tests at the end of the program, but I need to understand how it’s solved in this given way.
# Write a function `bubble_sort(arr)` which will sort an array of
# integers using the "bubble sort"
# methodology. (http://en.wikipedia.org/wiki/Bubble_sort)
#
# Difficulty: 3/5
def bubble_sort(arr)
sorted = false
until sorted
sorted = true
(arr.count - 1).times do |i|
if arr[i] > arr[i + 1]
arr[i], arr[i + 1] = arr[i + 1], arr[i]
sorted = false
end
end
end
arr
end
puts bubble_sort([]) == []
puts bubble_sort([1]) == [1]
puts bubble_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
What I don’t understand:
-
I haven’t used until loops much. But from my understanding they are a sort of reverse condition while loop. In other words the loop should until sorted = true. But on the very next line after the until loop starts, sorted is set to be true. So shouldn’t the loop just end?
-
What’s happening inside the times loop? If the element preceding the element after it is of less value, this happens
arr[i], arr[i + 1] = arr[i + 1], arr[i]
sorted = false
What is actually happening here? I’ve never seen syntax where there’s commas in code. It looks like it’s also assigning the value of the array index to itself? Lost here.
Sorry if it seems like there’s a lot here I need help with. I tried looking up the syntax elsewhere but couldn’t find anything. This was in a series of programing problems I needed to solve and all of the previous ones were much less difficult for me to figure out. Here I’ve just been thrown for a loop so to speak and I’m lost. Thanks in advance