用ruby撸代码——选择排序算法

2019-10-28  本文已影响0人  春木橙云

最近双十一,公司赶上线新功能,忙疯了,终于忙里偷闲撸一下ruby代码,新手入坑,勿喷!

新源代码:(多重赋值节省代码)

$array = [21, 35, 33, 41, 16, 6]

def select_rank(arr)
  arr.each_with_index do |item, index|
    init_index = index
    inner_arr = arr[index + 1, arr.length - index]
    inner_arr.each_with_index do |i, idx|
      min_num = item
      min_index = init_index
      if min_num > i
        min_index = idx + index + 1
        min_num = arr[min_index]
      end
      arr[init_index], arr[min_index] = arr[min_index], arr[init_index]
    end
  end
end

原源代码:

$array = [21, 35, 33, 41, 16, 6]

def select_rank(arr)
  arr.each_with_index do |item, index|
    init_index = index
    inner_arr = arr[index+1, arr.length - index]
    inner_arr.each_with_index do |i, idx|
      min_num = item
      min_index = init_index
      if min_num > i
        min_index = idx + index + 1
        min_num = arr[min_index]
      end
      select_change_position($array, init_index, min_index)
    end
  end
end
def select_change_position (arr, init_index, min_index)
  arr_store = arr[init_index]
  arr[init_index] = arr[min_index]
  arr[min_index] = arr_store
end

p "原始数组",$array
select_rank($array)
p "排序后数组",$array

结果:

"原始数组"
[21, 35, 33, 41, 16, 6]
"排序后数组"
[6, 16, 21, 33, 35, 41]

总结:

上一篇 下一篇

猜你喜欢

热点阅读