🎉 Special Offer !    Code: GET300OFF    Flat ₹300 OFF on every Java Course
Grab Deal 🚀

Bubble Sort Algorithm in DSA (Java)  


Introduction
  • Bubble Sort is a simple comparison-based sorting algorithm used to arrange elements in ascending or descending order.
  • It repeatedly compares adjacent elements and swaps them if they are in the wrong order.
  • This process continues until the entire array is sorted.
  • Logic / Steps (Simple):
    1. Start from the first element and compare it with the next element.
    2. If they are in the wrong order, swap them.
    3. Repeat this process for each adjacent pair, moving the largest element to the end in each pass.
    4. Continue the passes until no swaps are needed, meaning the array is sorted.
Bubble Sort Algorithm in Java DSA
  • Program:
    public class BubbleSortExample
    {
        public static void main(String[] args)
        {
            int[] arr = {55, 32, 44, 25, 16};
    
            int leng = arr.length;
            
            // Bubble Sort Algorithm
            for (int i = 1; i < leng; i++)
            {
                boolean swapped = false;
    
                for (int j = 0; j < leng - i; j++)
                {
                    if (arr[j] > arr[j + 1])
                    {
                        // Swap arr[j] and arr[j+1]
                        int temp = arr[j];
                        arr[j] = arr[j + 1];
                        arr[j + 1] = temp;
    
                        swapped = true;
                    }
                }
    
                if(swapped == false)
                {
                    break;
                }
            }
    
            // Print sorted array
            System.out.print("Sorted Array: ");
            for (int num : arr)
            {
                System.out.print(num + " ");
            }
        }
    }

Important Points to Note :-
  • Bubble Sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order.
  • It is stable (preserves the order of equal elements) and works well for small datasets.
  • It is adaptive when implemented with a swapped flag; stops early if the array is already sorted.
  • Bubble Sort follows the iterative comparison and swapping approach.
  • Using a swapped flag can optimize Bubble Sort to terminate early if the array is already sorted.
  • Time Complexity for Bubble Sort:
    • Case Description No. of Comparisons Time Complexity
      Worst Case Array is in reverse order; maximum number of swaps required. n(n-1)/2 O(n²)
      Average Case Elements are in random order; some swaps required. n(n-1)/4 Θ(n²)
      Best Case Array is already sorted; only comparisons, no swaps. n-1 Ω(n)
  • Space Complexity:
    • O(1) → only a few variables used; no extra memory needed.