Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
冒泡排序-Ruby未定义的局部变量或方法_Ruby_Arrays_While Loop_Undefined_Bubble Sort - Fatal编程技术网

冒泡排序-Ruby未定义的局部变量或方法

冒泡排序-Ruby未定义的局部变量或方法,ruby,arrays,while-loop,undefined,bubble-sort,Ruby,Arrays,While Loop,Undefined,Bubble Sort,所以我决定写一个程序对数组进行排序。它获取数组的前两个元素,如果第一个元素小于第二个元素,则对它们进行排序。然后移动到位置1和2的下两个元素,并对它们进行排序 这是我的密码 num_array = [4,7,19,5,71,26,37,52,59,3] def sort_array x = 0 while num_array.find_index (x) < num_array.count if num_array[x] < num_array[x+1]

所以我决定写一个程序对数组进行排序。它获取数组的前两个元素,如果第一个元素小于第二个元素,则对它们进行排序。然后移动到位置1和2的下两个元素,并对它们进行排序

这是我的密码

num_array = [4,7,19,5,71,26,37,52,59,3]

def sort_array
  x = 0
  while num_array.find_index (x) < num_array.count
    if num_array[x] < num_array[x+1]
      num_array[x] = num_array[x]
    else
      num_array[x] = num_array[x+1]
    end
  x += 1
  end
end
我不明白,我在第一行清楚地定义了变量num_数组

我可以使用

num_array.sort
但是我想用冒泡排序法对它进行排序

非常感谢您的帮助。

num\u数组超出范围。您应该将其设为全局变量$num\u array或作为参数传递给sort\u array。最后一个更好

def sort_array!(num_array)
  x = 0
  while num_array[x] < num_array.count
    if num_array[x] < num_array[x+1]
      num_array[x] = num_array[x]
    else
      num_array[x] = num_array[x+1]
    end
    x += 1
  end

  num_array
end

num_array = [4,7,19,5,71,26,37,52,59,3]

puts sort_array!(num_array)

您的冒泡排序和答案是$num_数组=[4,7,19,5,71,26,37,52,59,3]def sort_数组x=0 swapped=true while swapped do swapped=false while x<$num_数组.size-1 if$num_数组[x]>$num_数组[x+1]$num_数组[x],$num_数组[x+1]=$num_数组[x+1],$num_数组[x]swapped=true x=0下一个端点x+=1个端点p$num\u数组。检查端点排序\u数组
def sort_array!(num_array)
  x = 0
  while num_array[x] < num_array.count
    if num_array[x] < num_array[x+1]
      num_array[x] = num_array[x]
    else
      num_array[x] = num_array[x+1]
    end
    x += 1
  end

  num_array
end

num_array = [4,7,19,5,71,26,37,52,59,3]

puts sort_array!(num_array)