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
- Create a method
bubbleSort(int[] a). - Start an outer loop from
i = 1toa.length - 1representing the number of passes. - Start an inner loop from
j = 0toa.length - i - 1. - Inside the inner loop, compare adjacent elements: if
a[j] > a[j+1], swap them using a temporary variable. - 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
ion 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)