1、插入排序
复制代码 代码如下:
seq = [3,4,9,0,2,5,9,7,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、冒泡排序
复制代码 代码如下:
seq = [3,4,9,0,2,5,9,7,1,100,99,24,64,18,88,66]

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}

广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!