2017-05-16 41 views
0

我正在尝试查找数组中的最小元素。每个循环中的选择排序设置值

我试图与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) 

它从以前的阵列返回的最小元素。我认为问题在于each循环没有第二次(或第一次)设置该值。我做错了什么?

回答

1

@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 
+0

你需要'@ min'呢? – Stefan

+0

@Stefan我没有,但由于原始实现返回一个值,存储在实例变量中,我决定减少我的更改的影响。 – mudasobwa