Sorting an Array in Ruby without using Sort method

后端 未结 7 1960
感动是毒
感动是毒 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:40

    Your code works for that specific array. Because your loop is looking if the next element is higher, then swipe. But what about more elements in the array? This is recursive solution for all cases.

    def my_sort(list, new_array = nil)
    
      return new_array if list.size <= 0
      if new_array == nil
        new_array = []
      end
      min = list.min
      new_array << min
      list.delete(min)
    
      my_sort(list, new_array)
    
    end
    
    puts my_sort([3, 1, 2, 20, 11, 14, 3, 6, 8, 5])
    

提交回复
热议问题