Bubble Sort: Java Array Sorting with a For Loop

bubblesortjavaBubble sort is one of those more advanced concepts that they teach in college to not only help you understand for loops, but it helps you understand arrays and how to work with array values within the indexes. Arrays are more difficult to understand for a new programmer, but they are essential for Java developers. The bubble sort takes an array of numbers and sorts them within the array indexes in either ascending or descending order. This means that when you print out the values, you print out an ordered list of numbers.

Just starting out with Java? Take a Java fundamentals course.

Java For Loops

If you’re familiar with any C-style languages, you’re probably familiar with for loops. For loops are typically used with primitive type arrays that contain either string or integer values. You use these loops when you need to manipulate or read each value in the array. For loops are a part of almost every Java program, and you’re guaranteed to run into them when you start your programming career.

Getting Started with the Bubble Sort

The first item you need for a bubble sort is an array of integers. You can have two or thousands of integers to sort through. For this example, a list of five integers is stored in an array named “numbers.” The following code shows you how to create an integer array in Java:

int[] numbers = { 5, 8, 14, 1, 5678 };

The first part of this line of code is the array data type. The “int[]” data type assignment tells the Java compiler that you are setting up a single-dimensional array of integers. The brackets are appended to the data type to indicate that it’s an array variable. You can do this with any primitive data type. For instance, using “string[]” indicates that you are defining an array of strings.

Learn about data types and Java functions.

Next, you need to set up a temporary variable. The temporary variable is used to “move” the data and switch the value from one location to another during the bubble sort. This will be better explained later. The following code creates a temp variable for your bubble sort:

int tempVar;

The For Loop Template and Setup

The main logic in a bubble sort is set up using two for loops. The first for loop goes through each index in the integer array. The embedded, second for loop compares the current index value with all other values in the array. It’s this embedded second loop that does the “bubbling” and moves values up the array to sort the list of integers.

To get started, you first set up your “main” loop. The following code creates the template for the main loop:

for (int i = 0; i < numbers.length; i++)
{
}

Getting started with for, while, do while and foreach loops.

There are three parts to this for loop separated by semicolons. The first defines the increment number (in this case “i”) that’s used to cycle through each index in the array. Java arrays start with an index of 0, so your increment number should always be initialized to 0. The second part defines how many iterations you want to make in the for loop. Because we want to go through each number in the array, this section basically says “loop from 0 to the last index in the array.” The “numbers.length” syntax returns the total amount of integers stored in the array. Finally, the last section is the increment operator. The “i++” syntax is Java’s shorthand way of incrementing an integer by 1.

Now you need the embedded array. The embedded array needs an increment number that is unique to its enclosing for loop. In this example, we will use “j” as the increment number. Add the following code to your first for loop:

for (int i = 0; i < numbers.length; i++)
{
       for(int j = 0; j < numbers.length; j++)
       {
       }
}

In the code above, the “j” for loop goes through each array element as does the enclosing “i” for loop. All of the business logic and bubble sort manipulation happens in the embedded “j” for loop. The reason for this loop is that you need to compare each value in the index with all other values. As you compare each value, the lowest number in the sort order moves up the array, one-by-one in the embedded “j” for loop.

The first bit of logic is comparing the current index value from the “i” loop with the current “j” loop value. If the value of the “j” loop is less than the value of the “i” index, then you need to switch the values. This concept is difficult to understand, but it gets easier to understand as you see the code. For now, you need to add the Java if statement into the embedded “j” loop code. Add the following code to your bubble sort:

for (int i = 0; i < numbers.length; i++)
{
       for(int j = 0; j < numbers.length; j++)
       {
                    if(numbers[i] > numbers[j + 1])
                    {
                    }
       }
}

Notice that the “if” statement compares the current index in the first for loop with the j loop’s “next” value. The “j + 1” allows you to compare the current number with the next number in the loop. The reason you add the “+ 1” to the embedded code’s current index is because you want to compare all numbers except for the number held in the “i” index. Therefore, you are comparing all numbers except for the number you are trying to bubble.

Within the “if” statement, you do the actual bubble sort. The “if” statement only executes if the number that’s in the next index is less than the current number. This is where you implement the temporary variable you defined earlier with the integer array. Add the following code to complete the bubble sort:

for (int i = 0; i < numbers.length; i++)
{
       for(int j = 0; j < numbers.length; j++)
       {
                if(numbers[i] > numbers[j + 1])
                {
                            tempVar = numbers [j + 1];
                            numbers [j + 1]= numbers [i];
                            numbers [i] = tempVar;
                }
        }
}

Within the if statement, you now have 3 lines of code. These lines of code have difficult concepts, but it’s easy once you read and understand the code. Remember, the concept is to move the lowest number up the array, so you have an ascending order of integers.

The first line of code places the smaller number (numbers[j + 1]) in the temporary variable tempVar. The reason is because you need to move the higher number down, and doing so without saving it to a temporary variable will overwrite the number and you will lose it permanently. The temporary variable holds the smaller number so that you can switch its location in the array index.

The second line in the if statement moves the larger integer value to the next location in the array. The larger value overwrites what is in the next index location (numbers[j + 1]), but it’s ok, because the smaller number has been stored in the temporary variable in the previous line of code. This is the main reason for the temporary variable.

Finally, the smaller number is stored in the current index using the tempVar variable. What this has done is switched the location of the smaller number at the lower index, creating an ascending array. For instance, if the number held in numbers[i] is 4 and the number stored in numbers[j + 1] is 3, this bit of code switches the location and places the integer 3 in numbers[i] and places the integer 4 in numbers[j + 1]. This continues for each integer in the array. The result is an ascending order of integers.

You can also use this bubble sort to create a list of integers in descending order. The logic is slightly different, but here is the bubble sort to create a descending list:

for (int i = 0; i < numbers.length; i++)
{
       for(int j = 0; j < numbers.length; j++)
       {
                if(numbers[i] < numbers[j + 1])
                {
                            tempVar = numbers [j + 1];
                            numbers [j + 1]= numbers [i];
                            numbers [i] = tempVar;
                }
       }
}

Notice there is one change: the if statement has a less than sign rather than a greater than sign. The rest of the logic and syntax is the same. When you switch to a less than sign, the integer in the current position is only bubbled up when it is smaller than the next position. Essentially, you reverse the bubble sort.

If you’re experimenting with the Java bubble sort, you can verify you’ve done it correctly by printing out the array of numbers. You can also step through the code, but printing it out lets you see the results quickly without using the debugger. The following code shows you how to print out the newly sorted array:

for (int i = 0; i < numbers.length; i++)
{
         System.out.println(numbers[i].toString());
}

The above Java code prints the numbers to the screen, so you can verify that all numbers were completely sorted. Notice a for loop is used. You could technically print out the array using static references to the indexes in the array, but this code is more efficient. Additionally, if you don’t know the size of the array, this code lets you loop through and print out an array that has one value or thousands of values.

To get the full code, here is the Java code from start to finish:

int[] numbers = { 5, 8, 14, 1, 5678 };
int tempVar;
for (int i = 0; i < numbers.length; i++)
{
       for(int j = 0; j < numbers.length; j++)
       {
                if(numbers[i] > numbers[j + 1])
                {
                       tempVar = numbers [j + 1];
                       numbers [j + 1]= numbers [i];
                       numbers [i] = tempVar;
                }
       }
}
for (int i = 0; i < numbers.length; i++)
{
         System.out.println(numbers[i].toString());
}

The print out is:

1
5
8
14
5678

Incidentally, you can also place your bubble sort in a Java function. This means you can sort any integer values from anywhere in your code. Functions can be a part of any helper class you create, and they make it more convenient so that you don’t need to type the code in every class. The following code is an example of creating a static function and calling that function from your code:

public static void main()
{
       int[] numbers = { 5, 8, 14, 1, 5678 };
       bubblesort(numbers);
}

static void bubblesort(int[] numbers)
{
        int tempVar;
        for (int i = 0; i < numbers.length; i++)
        {
                 for(int j = 0; j < numbers.length; j++)
                 {
                         if(numbers[i] > numbers[j + 1])
                         {
                         tempVar = numbers [j + 1];
                         numbers [j + 1]= numbers [i];
                         numbers [i] = tempVar;
                         }
                 }
        }
        for (int i = 0; i < numbers.length; i++)
        {
                  System.out.println(numbers[i].toString());
        }

}

The beauty of creating a static class for this type of sort is that you do not need to instantiate the class. Simply call the class and the “bubblesort” function, and you can sort any number of integer arrays throughout the code.

Go beyond basic Java and learn advanced functions.

The bubble sort in Java is probably one of the most common ways you can quickly sort an array in either ascending or descending order. Other more complex types have sort functions, but if you need to quickly sort an array with primitive types, the bubble sort is the fastest and most efficient way to sort numbers. You can also use strings in the bubble sort, but strings are measured by length, so the bubble sort will sort strings in ascending order according to string length.

If you go to college for computer science, you will likely need to know this type of sort as well. Many college professors use the bubble sort method to introduce for loop concepts and logic.

Once you understand the bubble sort and how it works with the for loop, you’re ready to move on to more advanced concepts such as “do while” and “while” loops. Many enumeration concepts let you loop through without the use of an incrementing number. Instead, you use an enumerator. However, it’s best to understand the bubble loop to better familiarize yourself with arrays and Java concepts in general.