Ruby based insertion and bubble sorting algorithms

Time:2020-3-23

1. Insert sort

Copy codeThe code is as follows:
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. Bubble sorting

Copy codeThe code is as follows:
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}

Recommended Today

Django log — output to log file

We all know that it is very important to log in the project, because bugs appear when the project is running in the server and there is no log to record. We may not know that bugs exist at all. In the past, I didn’t feel that I had made my own development in school. […]