Saturday, August 1, 2015

Bubble Sort Java Implementations

Out of curiosity, I decided to implement the Bubble Sort to refresh my memory, and play around with Generics. At a really high level, the bubble sort is performed by iterating over an array of elements and comparing adjacent elements. If the adjacent elements are in the wrong order, then you swap them. You continue to iterate over the array until no changes are made to the order of the elements within an iteration. This sort is essentially brute force, and not as performant as other sorts such as quick sort, merge sort, etc.

1. Here is my initial implementation which sorts the characters within a String in lexicographic order:
2. Here is my follow-up implementation which sorts a List:
3. Finally, I decided to implement a version which uses Generics to sort a List of Comparables:
4. Here are some example scenarios and output:
Example output: Thank you for reading this far through the post! If you are curious, the full code example is in GitHub here: https://github.com/jmartin127/InterviewQuestions