Sorting an Array in Ruby without using Sort method

后端 未结 7 1919
感动是毒
感动是毒 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条回答
  • 2020-12-20 02:52

    What worked for me, is below.

    def my_sort(list)   
      n = list.length   
      loop do
        swapped = false
        (n-1).times do |i|
          if list[i] > list[i+1]
            list[i], list[i+1] = list[i+1], list[i]
            swapped = true
          end
        end
        break if not swapped  
      end   
      list 
    end   
    
    0 讨论(0)
提交回复
热议问题