泡沫排序Bubble Sort
def bubble_sort(list)
list.each_with_index do |no|
(list.length - 1).times do |e|
if list[e] > list[e + 1]
list[e],list[e+1] = list[e+1],list[e]
end
end
end
end
插入排序法(Insertion Sort)
def insertion_sort(list)
list.each_with_index do |no, index|
(0..index).each do |i|
if list[index] < list[i]
list[index], list[i] = list[i], list[index]
end
end
end
end
選擇排序(Selection sort)
def select_sort(list)
(list.length - 1).times do |i|
p "#{i} times fo #{list} and the mis is #{list[i..-1].min}"
min_index = list.rindex list[i..-1].min
if list[i] > list[i..-1].min
list[i], list[min_index] = list[i..-1].min,list[i]
end
end
list
end
Written with StackEdit.
沒有留言:
張貼留言