Lately during my free time I’ve been reading through sorting algorithms for fun and decided to implement several in Ruby. I’ll be posting each one in a separate article as I go through them.

Here’s a bubble sort in Ruby.

Bubble sort is a pretty fun and easy sorting algorithm. For each pass through an array of values, each value is compared to its adjacent value and swapped into the correct order and so on. Worst case is O(n^2) and best case is O(n) if the array is already sorted.

Let’s start with the test.

In the test I create an array of random numbers and assert_equal to the result of the bubble sort.

Next the code for the bubble sort.

I use recursion for each pass until swapped is equal to false, which means that the array is sorted.

© Aaron Van Bokhoven 2005-