Stat Tracker

Saturday, May 30, 2015

Computer Science 101 in Apex - Bubble Sort

Bubble Sort in Apex

The bubble sort algorithm is one of the first sorting algorithms that computer science students learn. It can be thought of as the "Hello World" of sorting algorithms. It is very easy to implement the code, and the algorithm itself is fairly straightforward. The trade off of is that for large data sets it has the worst performance of all the sorting algorithms.

In a bubble sort, an array of values is iterated over one element at at time. The current element is then compared to the next element in the collection. If the current element is greater than the element that is next in the collection, the two values positions are swapped in the collection. The algorithm will iterate over the collection multiple times until all the elements in the array are ordered. In each pass the highest value element is moved to its position in the array, hence the term "bubble sort". It's like the value has "bubbled" its way to the correct position in each iteration.

If you want more details on bubble sorting algorithm take a look at the Wikipedia entry here: http://en.wikipedia.org/wiki/Bubble_sort

Now to the fun stuff. The following code will perform a bubble sort in Apex, which runs on the Salesforce.com PaaS.



Here are some logs showing it working as expected.



How useful is this in real world application of the Salesforce platform? Not very. It is much easier to use the optimized sorting algorithms on the Apex collections objects themselves (List.sort()) for example. Or if you ware working with a SOQL query simply using ORDER BY on the query will sort for you.

However it is a fun little piece of code and illustrates that you can teach core computer science principals on the Salesforce platform. Enjoy!