Sorting an Array in Ruby without using Sort method

后端 未结 7 1975
感动是毒
感动是毒 2020-12-20 02:20

I\'m trying to use the bubble sort method to sort an array of only three numbers. The code I\'m using is below.

def my_sort(list)
  return list if list.         


        
7条回答
  •  梦毁少年i
    2020-12-20 02:37

    You're missing an end after swapped = true. It would be best to indent your code thoroughly and accurately to avoid this kind of problem:

    def my_sort(list)
      return list if list.size <= 1 
    
      swapped = false
      while !swapped
        swapped = false
        0.upto(list.size-2) do |i|
          if list[i] > list[i+1]
            list[i], list[i+1] = list[i+1], list[i]
            swapped = true
          end
        end
      end
    
      list
    end
    

提交回复
热议问题