top of page

How to Implement Bubble Sort in Java

Updated: Aug 8, 2023

Sorting algorithms play an important role in computer science and programming, as they allow us to efficiently arrange data in a particular order. One such algorithm is the Bubble Sort, which, while not the most efficient sorting method for large datasets, serves as a fundamental building block in understanding sorting techniques and algorithmic principles.


In this article, we will walk you through the process of implementing the Bubble Sort algorithm in Java.



Before we begin, you might notice an unusual import statement: import java.util.Arrays;. Don't let this confuse you! While we're not using the sort method from this library, we're employing it to neatly print arrays for better readability. Also, we've introduced a swap function to enhance code readability. If you prefer, you can inline the code directly within the swap method, right within the inner loop's if statement.


Additionally, while we've utilized the main method for demonstration purposes, we encourage you to write unit test cases to thoroughly validate your Bubble Sort implementation. If you're unfamiliar with this process, you can refer to our JUnit tutorial for guidance.


Code:

import java.util.Arrays;

public class BubbleSort {
 
   public static void main(String args[]) {
        bubbleSort(new int[] { 20, 12, 45, 19, 91, 55 });
        bubbleSort(new int[] { -1, 0, 1 });
        bubbleSort(new int[] { -3, -9, -2, -1 });
    }

    public static void bubbleSort(int[] numbers) {
        System.out.printf("Unsorted array in Java: %s %n", Arrays.toString(numbers));

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

        System.out.printf("Sorted Array using Bubble sort algorithm: %s %n",
                Arrays.toString(numbers));
    }

    public static void swap(int[] array, int from, int to) {
        int temp = array[from];
        array[from] = array[to];
        array[to] = temp;
    }
}

The code begins with an import statement, import java.util.Arrays;, which is used to import the Arrays class from the java.util package. While the code doesn't directly use the sort method from this class, it utilizes it for neatly printing arrays.


The BubbleSort class contains a main method that serves as the entry point for the program. It showcases the usage of the bubbleSort method with different arrays to demonstrate the algorithm's functionality.


The bubbleSort method is defined to perform the Bubble Sort algorithm on the input integer array. It takes an array of integers (numbers) as an argument.


The method starts by printing the unsorted array using Arrays.toString(numbers), which converts the array into a readable string format.


The algorithm employs nested loops: an outer loop and an inner loop. The outer loop, controlled by the variable i, iterates through each element in the array.


The inner loop, controlled by the variable j, iterates through the array in reverse order (from the end towards the beginning), ensuring that the largest element bubbles up to the end of the array in each iteration.


Within the inner loop, the code checks if the element at numbers[j] is smaller than the element at numbers[j - 1]. If this condition holds true, the swap method is called to exchange the positions of these elements, effectively placing the smaller element before the larger one.


After completing all the iterations, the sorted array is printed using the Arrays.toString(numbers) function, displaying the result of the Bubble Sort algorithm.


The swap method is defined to exchange two elements within the given array. It takes the array array and the indices from and to as arguments and performs the swapping using a temporary variable temp.


Output:

How to Implement Bubble Sort in Java


0 comments

תגובות


bottom of page