ruby实现的插入排序和冒泡排序算法,相信不是很多人都会进行操作,然而我们从一开始就需要把元素放到最后,下面武林技术频道小编来给大家详细介绍一下吧!
1、插入排序
1.upto(seq.length-1) do |i|
if seq[i] < seq[i-1]
tmp = seq[i]
j = i-1
while(j>=0 && tmp<seq[j]) do
seq[j+1] = seq[j]
j=j-1
end
seq[j+1]=tmp
end
end
seq.each {|num| puts num}
2、冒泡排序
0.upto(seq.length-1) do |i|
exchange = false
0.upto(seq.length-1-i-1) do|j|
if seq[j]>seq[j+1]
tmp = seq[j+1]
seq[j+1] = seq[j]
seq[j] = tmp
exchange = true
end
end
if !exchange
break
end
end
seq.each {|num| puts num}
通过武林技术频道小编介绍的ruby实现的插入排序和冒泡排序算法,相信大家都了解了,希望能给大家带来帮助。
新闻热点
疑难解答
图片精选