每次循环中的选择排序设置值

Selection sort setting value in each loop

我正在尝试查找数组中的最小元素。

我尝试使用 finding_smallest 方法来执行此操作,如下所示:

def finding_smallest arr_arg
  # first time returns 3;
  # second time returns 3 again, even though arr_arg doesn't have it.
  p arr_arg    
  arr_arg.each do |el|
    if el < @min
      @min = el
    end
  end
  @min
end

def selection_sort array
  counter = 0
  sorting = ->(arr){
    arr_range = arr[counter..-1]
    smallest = finding_smallest(arr_range)
    p arr_range # first iteration - whole array; second iteration - [1..end of the array]
    p smallest # first iteration: 3, second iteration: 3;
    first_element_in_range = arr_range[0] # for switching indexes of smallest and first in array
    arr_range[arr_range.index(smallest)], arr_range[0] = arr_range[0], arr_range[arr_range.index(smallest)] #switching places
    counter += 1
    sorting.call(arr_range) unless counter == array.length || arr.nil?
  }
  sorting.call(array)
end

@array = [78, 42, 51, 49, 74, 53, 66, 39, 40, 3, 66, 100]
@min = @array[0]
selection_sort(@array)

它returns 是前一个数组中的最小元素。我认为问题是 each 循环没有第二次(或第一次)设置值。我做错了什么?

@min 在 [这里] 扮演全局变量的角色(main 的实例变量。)一旦设置,它永远不会更新,因为最小值永远不会再被触及。

您可能希望在每次后续调用时更新它的值:

def finding_smallest arr_arg
  @min = arr_arg.first

  arr_arg.each do |el|
    if el < @min
      @min = el
    end
  end
  @min
end

在 ruby 中我们使用 Enumerable#reduce

def finding_smallest arr_arg
  @min = arr_arg.reduce do |min, el|
    el < min ? el : min
  end
end