简体   繁体   中英

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!

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 (ie not false and not nil ) when it is checked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM