jyim
jyim

Reputation: 119

Until loop-- why doesn't it exit immediately?

Question: with the first line in the "until" loop, we set the boolean, sorted, to true. Why does the loop even run after this line? Also why can we not put sorted = true after the .times do loop (to close the until sorted loop) and achieve the same result?

def bubble_sort(arr)
  len = arr.length
  sorted = false
  until sorted
    sorted = true
    (len-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

Thanks in advance!

Upvotes: 0

Views: 58

Answers (1)

mu is too short
mu is too short

Reputation: 434665

The loop condition is checked at the beginning of each iteration through the loop. The value of sorted inside the loop body doesn't matter, all that matters is the value of sorted when the loop is about to start another iteration. The loop isn't watching sorted to see when its value changes, it just evaluates sorted before each iteration and stops the looping when it is truthy (i.e. not false and not nil) when it is checked.

Upvotes: 4

Related Questions