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
循环没有第二次(或第一次)设置该值。我做错了什么?
你需要'@ min'呢? – Stefan
@Stefan我没有,但由于原始实现返回一个值,存储在实例变量中,我决定减少我的更改的影响。 – mudasobwa