比较数组中的两个连续元素

OhD*_*eSu 0 ruby compare conditional-statements

我想创建一个"冒泡排序"方法,这意味着我在一个数组中取两个连续元素,比较它们,如果左边元素大于右边元素,它们应该切换位置.我想重复它,直到我的数组按升序排序.

我的代码只能部分工作.如果我的数组太大,就不会发生任何事情(我必须用CTRL + C退出ruby).对于小于5个元素的数组,我的代码工作正常:

def bubbles(array)

  while array.each_cons(2).any? { |a, b| (a <=> b) >= 0 }                   

  # "true" if there are two consecutives elements where the first one 
  # is greater than the second one. I know the error must be here somehow.

    array.each_with_index.map do | number, index |
      if array[index + 1].nil?
        number
        break
      elsif number > array[index + 1]
        array[index], array[index + 1] = array[index + 1], array[index]     # Swap position!
      else
        number
      end   
    end
  end

p array
end
Run Code Online (Sandbox Code Playgroud)

如果我用一个包含4个元素的数组调用我的方法,它可以正常工作:

 bubbles([1, 5, 8, 3])       # => [1, 3, 5, 8]
Run Code Online (Sandbox Code Playgroud)

如果我用更大的数组调用它,它不起作用:

 bubbles([5, 12, 2, 512, 999, 1, 2, 323, 2, 12])   # => Nothing happens. I have to quit ruby with ctrl + c.
Run Code Online (Sandbox Code Playgroud)

我以某种方式用my语句创建了一个无限循环吗?

Ser*_*sev 5

问题出在你的停止状态.你不会停止,直到你有一个数组,每个元素都是较小比下.但是在长数组中,您有重复的元素,因此排序的元素将具有彼此相等的相邻元素.

不太喜欢你的代码会让你的生活更轻松:)

while array.each_cons(2).any? { |a, b| a > b }                   
Run Code Online (Sandbox Code Playgroud)