challenge #5 Ruby Bubble Sort

Today, i sat up to write a bubble sort in ruby. This is how it goes. First things first. We device a way to find the largest number by comparing the each element with the next. Then we swap them if they are not in ascending order. After the first iteration the biggest number will be the last in the array. Bring another loop (outer) will help us sort it but the problem is that, we will still go through the array even if the array is already sorted. Therefore, before the beginning of the program we assume there is swaping to be done. Swap therefore is true. If there is a swap then swap, then there is probably some more things unsorted in the array. But if it happens that there were no swap the (break).

1  a = [1,1,1,1,1]

2  (a.size).times do
3    swap = true
4      (a.size-1).times do |i|
5        if a[i] > a[i+1]
6          temp = a[i]
7          a[i] = a[i+1]
8          a[i+1] = temp
9          swap = true
10        end
11       break if swap == false
12    end
13  end

14  puts a

As its said, the best way to understand this is to sometimes follow it with paper and pen. It really does help. I hope to hear comments from you so as to shape my writing styles.


About this entry