我正在编写一个冒泡排序代码作为Ruby上初学者类的一部分。 我知道(array.length - 1).times do |i| 这是不好的做法,因为我不需要每次都运行到数组的末尾。 (在我的例子中,[5,4,3,2,1]五个在第一次运行期间被移动到最后,四个在第二个结束时位于正确的位置,等等,所以没有必要再次检查这些数字):
def bubble_sort(array) (array.length - 1).times do (array.length - 1).times do |i| array[i], array[i+1] = array[i+1], array[i] if array[i] > array[i+1] end end end bubble_sort([5,4,3,2,1])是否有一种简洁的方法告诉方法每次检查一个较少的数组元素?
I'm writing a bubble sort code as part of a beginner's class on Ruby. I know that (array.length - 1).times do |i| is bad practice because I don't need to run to the end of an array each time. (In my example, [5,4,3,2,1] five is moved to the end during the first run through, the four is in its right place by the end of the second, etc., so there's no need to examine those numbers again):
def bubble_sort(array) (array.length - 1).times do (array.length - 1).times do |i| array[i], array[i+1] = array[i+1], array[i] if array[i] > array[i+1] end end end bubble_sort([5,4,3,2,1])Is there a neat way to tell the method to examine one fewer element of the array each time?
最满意答案
如何在外部循环中添加变量j并从array.length - 1减去j?
它看起来像那样:
def bubble_sort(array) (array.length - 1).times do |j| (array.length - 1 - j).times do |i| array[i], array[i+1] = array[i+1], array[i] if array[i] > array[i+1] end end end bubble_sort([5,4,3,2,1])What about adding a variable j in the outer loop and substracting j from array.length - 1 ?
It would look like that:
def bubble_sort(array) (array.length - 1).times do |j| (array.length - 1 - j).times do |i| array[i], array[i+1] = array[i+1], array[i] if array[i] > array[i+1] end end end bubble_sort([5,4,3,2,1])更多推荐
发布评论