在 Ruby 中对数组进行排序而不使用 Sort 方法 [英] Sorting an Array in Ruby without using Sort method

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

问题描述

我正在尝试使用冒泡排序方法对只有三个数字的数组进行排序.我正在使用的代码如下.

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.size <= 1 

  swapped = false

  while !swapped
    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]
        swapped = true
      end
    end

    list
  end

my_sort([3,1,2])

这是我不断收到的错误消息:

Here is the error message I keep getting:

Syntax error, unexpected $end, expecting keyword_end

我只是想知道不应该包括哪一端?

I was just wondering which end shouldn't be included?

推荐答案

您在 swapped = true 之后缺少 end.最好彻底准确地缩进代码以避免此类问题:

You're missing an end after swapped = true. It would be best to indent your code thoroughly and accurately to avoid this kind of problem:

def my_sort(list)
  return list if list.size <= 1 

  swapped = false
  while !swapped
    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]
        swapped = true
      end
    end
  end

  list
end

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

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