bubble_sort and me.

There has been a clear pattern developing during my first three weeks at Flatiron School. I am introduced to something new and I spend hours studying and learning to use it properly. Shortly after, I discover a shortcut that easily performs everything I just struggled to learn. Never was this more evident than with associations in Active Record.

When I was introduced to Ruby there were some fundamental methods, like #count and #capitalize, that were simple to understand. Without much knowledge of Ruby, I was quickly able to return information or change an object. At the time, I figured these methods just worked, and it wasn’t important to know why.

I practiced Ruby by solving challenges from a number of different websites. I remember seeing a problem about implementing a bubble sort, without the use of #sort. I did not know what a bubble sort was, so I looked it up. I came across some gifs and explanations that confused me even more.

A bubble sort is an algorithm that loops through a collection, repeatedly comparing adjacent elements, and swapping their positions if they are in the wrong order. The pairs swap positions until all of the elements have been compared. At this point the final element is sorted correctly, and the loop and swapping commences begins again. This continues until the collection is sorted.

Bubble sort visualized.

I found this challenge extremely difficult and totally useless. The sort method was supposed to help solve problems quickly. What was the point of taking it away?

The following code mimics the definition of a bubble sort. The code is much more readable than how I originally solved the problem.

def bubble_sort(element)
loop do
swapped = false
0.upto(element.count-2) do |i|
if element[i] > element[i+1]
element[i], element[i+1] = element[i+1], element[i]
swapped = true
break if swapped == false

After a couple more weeks of learning and practicing Ruby I eventually solved the bubble sort challenge. New concepts or methods usually make tasks easier. Shortcuts are fun, and my goal while learning to code is to make everything seem routine. The bubble sort challenge took away a valuable shortcut, but it forced me to understand how it worked. Before the challenge, I knew that #sort would return a sorted array, but I did not know (or care) how it worked. I was forced to use new information and tedious steps to implement something that had a seemingly magical alternative.