How to sort an array in Java using bubble sort

Normally when sorting an array in Java the convenient method sort() of the Arrays class is used. If this was what you where looking for, follow this link to:
How to sort an array

This example shows how to sort an array without using that method, just for better understanding on how bubble sort works. Two different scenarios are used here, one where we sort an array of int values and one where we sort an array of objects.
This first example shows how to use bubble sort to sort integer values in ascending order.

We begin from the start element of the array and compare that value to the next element. If the value of the first element is greater than the value of the second element, they switch place. If not, we move on to compare the second element with the third element etc.
If there is a switch of values in the array, we start from the beginning of the array again. This procedure is done over and over until we reach the end of the array without any elements switching place.

Sorting an array of int values using bubble sort

Here is the code for sorting an array of int values:

The output from the code above is a sorted list of values:

If we instead would like to sort in descending order we just have to change this line:


Sorting an array of objects using bubble sort

In this example the principles are the same but instead of sorting an array of int values we sort an array of objects. We create an inner class that only contains one field which is the int value (it could of course be created as a public class in its own class file). To be able to compare these created objects with each other, the most common way is for the class to implement the Comparable interface. When the Comparable interface is implemented we need to override the compareTo() method and that’s where we implement our code to compare one object with another.

The below example shows the bubble sort code:

Note the use of a call to compareTo when using objects instead of only the ‘less than’ (<) and 'greater than' (>) operators that we used in the first example when an array of int values was used.

Search for more Java info on this site here:
Custom Search

Please type any questions here.