Implement Bubble Sort using Java

If you’re in a computer science background, widening your technical horizons is the best thing you should do. However, your programming skills matter the most and one must continuously keep sharpening these skills, to become a better programmer in the future. Though there are multiple things to focus on, one specific area you must focus on is the world of data structures. Data structures in general are specific approaches to solve problems in such a way that computer resources get used minimum. In general, there are multiple data structures you can learn and implement as well. However, to keep things simple were going to start with some basic programs you must learn before moving on to complex algorithms. Therefore today we’re going to learn how to Implement Bubble Sort using Java.


What is Bubble Sort?


  • Comes in the list of simplest data structures, Bubble Sort is the way of arranging elements in ascending order. The array is either sorted or is unsorted.


  • Works by comparing adjacent elements in an array and swapping them, if required. This process continues till each element in an array gets sorted.


What’s The Approach?


  • Consider array, arr[n] of size n we want to implement Bubble Sort on. So firstly we’ll iterate a for loop, with an iterative variable i from 0 to n-1.


  • Next, inside the previous for loop, we’ll iterate a new for loop, with an iterative variable j from 0 to n-i-1.


  • we’ll compare the element at iterating index with its next element from the array. If the comparing element is smaller, we’ll swap the elements.


Also Read: Implement Linked List using Java


Java Program To Implement Bubble Sort




64, 34, 25, 12, 22, 11, 90




Sorted array:

11 12 22 25 34 64 90


// Java program for implementation of Bubble Sort
class TechDecodeTutorials
    //Bubble Sort Function
    void bubbleSort(int arr[])
        int n = arr.length;
        for (int i = 0; i < n-1; i++)
            for (int j = 0; j < n-i-1; j++)
                if (arr[j] > arr[j+1])
                    // swap arr[j+1] and arr[j]
                    int temp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;

    /* Prints the array */
    void printArray(int arr[])
        int n = arr.length;
        for (int i=0; i<n; ++i)
            System.out.print(arr[i] + " ");

    // Driver method
    public static void main(String args[])
        TechDecodeTutorials TDT = new TechDecodeTutorials();
        int arr[] = {64, 34, 25, 12, 22, 11, 90};
        System.out.println("Sorted array");



I'm a coding geek interested in cyberspace who loves to write and read

Leave a Reply

Your email address will not be published. Required fields are marked *