The bubble sort algorithm offers a simple solution to sorting items in an array; the array can be of a primitive data type e.g. int or it can be an array of objects. The bubble sort works for both numerical values as well as for String and char.
SORT NUMBERS
On YouTube, on the “Joe James” channel there is an excellent animation of the bubble sort algorithm using integers. NOTE: The code shown below is slightly easier than Joe James’ version but they both work exactly the same way.
NOTE: At position 6m35s Joe shows the structure of a public method that we can call in order to sort the array. He passes an array to the method and the sorted array is returned. Thus the parameter for this method is an array (not a primitive data type). Take note of the syntax of how to pass and return an array.
SORT STRINGS
To sort Strings, we need to use the String method “compareTo” which compares Strings alphabetically (lexographically is the word in the text book) i.e. it subtracts the Unicode values (ASCII values) of the second String from the first. If the difference is zero the two Strings are the same. If the difference is negative the second string has a bigger ASCII code value than the first and therefore comes after the first alphabetically. Revise “compareTo” here if you are not sure about this (this is a PowerPoint download)
For more information on String, On YouTube, on the “estudy.in” channel is an explanation of the bubble sort algorithm using String.
SORT AN ARRAY OF OBJECTS