amber tunnell

puts 'my thoughts on the magic that is code'

# Sorting Algorithms Series: Bubble Sort

When I was learning Ruby, we never discussed sorting algorithms. It’s my understanding that most sorting algorithm problems can be solved quite easily using built-in methods in most languages. That being said, it is important to understand the different sorting techniques available in computer science. Along those lines, here’s a series of blog posts on the most common sorting algorithms!

Bubble Sort is a simple sorting algorithm.

1. You start by comparing the first two items in an array. If the first item is larger than the second, you swap the two items.
2. Then, you compare the second and third items. If the second is larger than the third, you swap them.
3. Continue until you reach the end of the array.
4. Then, you start from the beginning again and repeat the process until you have one full pass of the array in which you did not swap any items.
5. You now have a sorted array!

The name ‘bubble sort’ derives from the event of the smaller numbers slowly ‘bubbling’ to the front of the array through the swapping process.

Here’s the bubble sort algorithm implemented in Ruby.

And, here’s it in JavaScript.

One of the biggest problems with using bubble sort is that it isn’t practical on large data sets. It is incredibly inefficient with an average and worst-case time complexity of О(n2).

In the best-case where the array is already sorted, the time complexity is O(n) because it only has to do one pass of the array, whereas most other algorithms still have to go through all their steps even when given an already-sorted array.

That being said, bubble sort is still a very undesirable and inefficient sorting technique.

This is the first post in a series of posts on various sorting algorithms in computer science. See the entire series here.

Amber is a web developer in New York who believes in creating beautiful, interactive stories through code. She is a lover of good coffee, good books, and good code.