Ruby冒泡排序不排序所有元素

时间:2016-08-12 01:33:07

标签: arrays ruby sorting while-loop

尝试实现简单的冒泡排序。代码如下:

def bubble(array)
  start = 0
  sorted = []
  while start < array.length - 1
    if array[start] > array[start + 1]
      array[start], array[start + 1] = array[start + 1], array[start] 
    else
    end
  start += 1
  end
  return array
end

print bubble([4,8,2,6,7,1])

我得到的输出是:

[4, 2, 6, 7, 1, 8]

我的代码中的问题在哪里?

1 个答案:

答案 0 :(得分:0)

首先,如果您打算使用sorted,则应避免修改array而是使用副本。您需要反复遍历数组,直到没有其他项目出现故障,例如:

def bubble(array)
  sorted = array.dup
  finished = false
  until finished
    start = 0
    finished = true
    while start < sorted.length - 1
      if sorted[start] > sorted[start + 1]
        sorted[start], sorted[start + 1] = sorted[start + 1], sorted[start]
        finished = false
      end
      start += 1
    end
  end
  return sorted
end

虽然我提到明确的return在Ruby中相对不受欢迎;你可以简单地将sorted作为相同语义的最后一行。

相关问题