对Ruby中的数组使用冒泡排序方法 [英] Using the Bubble sort method for an array in Ruby

查看:78
本文介绍了对Ruby中的数组使用冒泡排序方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将Bubble排序方法实现为Ruby的一个简单编码问题,但遇到了一些麻烦。我了解的想法是先查看第一个元素的值,然后将其与第二个元素的值进行比较,然后相应地交换它们,但我似乎无法在实际问题中做到这一点。有人愿意提供一个简短的示例说明如何在Ruby中工作吗?

I'm trying to implement the Bubble sort method into an easy coding problem for Ruby, but I'm having some trouble. I understand the idea is to look at the value of the first element and compare it to the value of the second element and then swap them accordingly, but I can't seem to do it in an actual problem. Would anyone be willing to provide a brief example of how this might work in Ruby?

推荐答案

使用a正确的气泡排序实现while循环

Correct implementation of the bubble sort with a while loop

def bubble_sort(list)
  return list if list.size <= 1 # already sorted
  swapped = true
  while swapped do
    swapped = false
    0.upto(list.size-2) do |i|
      if list[i] > list[i+1]
        list[i], list[i+1] = list[i+1], list[i] # swap values
        swapped = true
      end
    end    
  end

  list
end

这篇关于对Ruby中的数组使用冒泡排序方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆