def selection_sort_enum(array) n = array.length - 1 0.upto(n - 1) do |i| smallest = i (i + 1).upto(n) do |j| smallest = j if array[j] < array[smallest] end array[i], array[smallest] = array[smallest], array[i] if i != smallest end end def selection_sort_loop(array) n = array.length - 1 i = 0 while i <= n - 1 smallest = i j = i + 1 while j <= n smallest = j if array[j] < array[smallest] j += 1 end array[i], array[smallest] = array[smallest], array[i] if i != smallest i += 1 end end puts "Using enum:" a1 = [*1..10].shuffle puts "Before sort: #{a1.inspect}" selection_sort_enum(a1) puts "After sort: #{a1.inspect}" puts puts "Using while:" a2 = [*1..10].shuffle puts "Before sort: #{a2.inspect}" selection_sort_enum(a2) puts "After sort: #{a2.inspect}"
Standard input is empty
Using enum: Before sort: [6, 4, 9, 10, 2, 5, 8, 1, 7, 3] After sort: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Using while: Before sort: [5, 9, 1, 10, 6, 3, 4, 2, 7, 8] After sort: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]