Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to sort an Array using bubble sort algorithm .

Java Code Example — Array Programs

ADVERTISEMENT

Java Program to sort an Array using bubble sort algorithm .

Objective

Write a Java program to sort an array using the Bubble Sort algorithm.

Algorithm / Approach

  1. Create a method bubbleSort(int[] a).
  2. Start an outer loop from i = 1 to a.length - 1 representing the number of passes.
  3. Start an inner loop from j = 0 to a.length - i - 1.
  4. Inside the inner loop, compare adjacent elements: if a[j] > a[j+1], swap them using a temporary variable.
  5. After all passes, print the sorted array.
Test.java
class Test{
 void  bubbleSort(int[] a) {
  int temp;
  for(int i = 1;i< a.length-1; i++) {
   for(int j = 0; j< a.length-i; j++) {
    if(a[j]>a[j+1]) {
     temp = a[j];
     a[j] = a[j+1];
     a[j+1] = temp;
    }
   }
  }
  for(int i=0; i< a.length; i++) {
   System.out.println(a[i]);
  }
 }
 public static void main(String[] a)
 {
  int[] arr ={10,6,8,3,5};
  Test t = new Test();
  t.bubbleSort(arr);
 }
}

Expected Output

3
5
6
8
10

Explanation of the Program

  • Bubble sort works by repeatedly stepping through the list, comparing adjacent elements and swapping them if they are in the wrong order.
  • With each full pass of the outer loop, the largest unsorted element "bubbles up" to its correct position at the end of the array.
  • This is why the inner loop bounds decrease by i on each pass—the last elements are already sorted and don't need to be checked again.

Complexity

Time Complexity O(n2) - Due to the nested loops comparing elements.
Space Complexity O(1)
ADVERTISEMENT