Bubble Sort in Java
Bubble Sort Explained with Code
Bubble Sort is a basic comparison based sorting algorithm used to arrange elements in a data structure. In this method, each element is compared with its adjacent element, and they are swapped if they are not in the correct order.
- Algorithm starts with comparing the first pair of elements.
- If the first element is smaller than the second element, then the elements are swapped.
- Algorithm is not suitable for large data sets.

What is Bubble Sort?
Bubble Sort is a simple comparison based sorting algorithm. It works by repeatedly swapping adjacent elements if they are in the wrong order.
The largest element “bubbles up” to the end of the array in each iteration, hence the name Bubble Sort.
How Bubble Sort Works ?
Let’s understand Bubble Sort with a simple step by step explanation:
- Starting from the beginning of the array, compare the first and second elements.
- If the first element is greater than the second, swap them.
- Move to the next pair (second and third), and repeat the process till the end of the array.
- After the first pass, the largest element will be at the end.
- Repeat the same process for the remaining elements, excluding the last sorted elements.
This process is repeated n-1 times for an array of size n.
Bubble Sort Algorithm (Pseudocode)
function bubbleSort(array): n = length of array for i from 0 to n-1: swapped = false for j from 0 to n-i-2: if array[j] > array[j + 1]: swap(array[j], array[j + 1]) swapped = true if not swapped: break
Swapped flag is used to check if the array is already sorted. If no swaps occur during a pass, the array is considered sorted, and the loop breaks early.

Let’s take an example, we have a list of number stored in array….
Pass 1
- ( 28 6 4 2 24 ) -> ( 6 28 4 2 24 ) : Swapped 28 & 6 since 28 > 6
- ( 6 28 4 2 24 ) -> ( 6 4 28 2 24 ) : Swapped 28 & 4 since 28 > 4
- ( 6 4 28 2 24 ) -> ( 6 4 2 28 24 ) : Swapped 28 & 2 since 28 > 2
- ( 6 4 2 28 24 ) -> ( 6 4 2 24 28 ) : Swapped 28 & 24 since 28 > 24
This is called as bubble sort as you can see in each pass we get the largest element, which pushes (bubbles) towards the right always. Just like in a soda the largest bubble traverse to top of first.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Algorithm for Bubble Sort in Java
Steps to implement bubble sort in Java –
- Step1: Repeat step 1 to 4 for i=0 to n
- Step2: For j=0 to n
- Step3: if(arr[j]>arr[j+1]
- Step4: swap(arr[j],arr[j+1])
- Step5: End
Java Program for Bubble Sort
Here is the Java implementation of the Bubble Sort algorithm:
Method 1: Basic Bubble Sort Method
This is a standard implementation of the Bubble Sort algorithm, which repeatedly compares adjacent elements and swaps them if they are in the wrong order.
How Bubble Sort works?
- It uses two nested loops:
- Outer loop runs n-1 times (for each pass).
- Inner loop compares each adjacent pair and swaps if needed.
No optimization is done here, even if the array becomes sorted earlier.
Worst case: O(n²) (e.g., reverse sorted array)
Best case: O(n²) (even if the array is already sorted, it still checks every pair)
Space Complexity: O(1) — in-place sorting with no extra space.
// Time Complexity: O(N^2) // Space Complexity: O(1) class Main { // Standard Bubble Sort function static void bubbleSort(int[] a) { int len = a.length; for (int i = 0; i < len - 1; i++) { for (int j = 0; j < len - i - 1; j++) { // Compare adjacent elements if (a[j] > a[j + 1]) { // Swap a[j] and a[j + 1] int temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; } } } } // Function to print the array static void printArray(int[] a) { for (int value : a) { System.out.print(value + " "); } System.out.println(); } public static void main(String[] args) { int[] arr = {64, 34, 25, 12, 22, 11, 90}; bubbleSort(arr); System.out.println("Sorted array:"); printArray(arr); } }
Output
Sorted array 11 12 22 25 34 64 90
Bubble Sort in Java Optimized Implementation
This is an optimized version of the Bubble Sort algorithm, which includes a flag (swapped) to detect if the array is already sorted and avoid unnecessary passes.
Method 2: Optimized Bubble Sort Implementation
This is a standard implementation of the Bubble Sort algorithm, which repeatedly compares adjacent elements and swaps them if they are in the wrong order.
How Bubble Sort works with optimized approach?
- Works the same way as Method 1, but:
- Introduces a boolean swapped variable.
- If no swaps occur in a full inner loop pass, the outer loop terminates early using break.
- This avoids redundant iterations when the array is already sorted.
As you can see the array is sorted already, but our algorithm(previous) will run all iterations and passes anyways
Arr [ ] = {1, 2, 3, 4, 5, 10, 7}
The above array is nearly sorted, just 10 out of place. However, in pass 1 itself the array will get sorted but previous algorithm will still run all the passes.
If in any pass no swapping happens, it means the array has become sorted and we do not need to run any further passes.
Worst case: O(n²)
Best case: O(n) when the input is already sorted, only one pass is made and then it breaks.
Space Complexity: O(1)
// Time Complexity: O(N^2) // Space Complexity: O(1) class Main { // Optimized Bubble Sort with early termination static void bubbleSort(int[] a) { int len = a.length; for (int i = 0; i < len - 1; i++) { boolean swapped = false; for (int j = 0; j < len - i - 1; j++) { if (a[j] > a[j + 1]) { // Swap a[j] and a[j + 1] int temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; swapped = true; } } // If no two elements were swapped, array is sorted if (!swapped) { break; } } } // Function to print the array static void printArray(int[] a) { for (int value : a) { System.out.print(value + " "); } System.out.println(); } public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5, 6, 7}; bubbleSort(arr); System.out.println("Sorted array:"); printArray(arr); } }
Bubble Sort Algorithm Explained


Why Bubble Sort is Not Used in Practice?
Although Bubble Sort is conceptually simple, it is not efficient for large datasets. Most real world sorting problems use more efficient algorithms like Merge Sort, Quick Sort, or built-in sorting functions.
However, Bubble Sort is often used:
- For educational purposes
- When the input size is very small
- In environments where code simplicity is more important than efficiency
Conclusion
Bubble Sort is an easy to understand, basic sorting algorithm that provides an excellent introduction to the concept of sorting.
- Despite its inefficiencies, understanding Bubble Sort in Java helps lay the groundwork for learning more complex algorithms.
- It is stable, simple, and demonstrates the core principles of sorting algorithms like comparisons, swapping, and early termination optimization.
- While it’s not ideal for real world use on large datasets, its role in foundational learning and small applications remains important

FAQ's related to Bubble Sort in Java
Answer:
Yes. Bubble Sort is a stable sorting algorithm as it does not change the relative order of equal elements.
Answer:
Yes. You can adapt Bubble Sort to sort strings lexicographically by comparing characters using compareTo().
Answer:
Its O(n²) time complexity in the average and worst cases makes it highly inefficient for large datasets.
Answer:
Only in cases with very small input sizes or nearly sorted data, where its simplicity outweighs its inefficiency.
Answer:
- If your data is sorted and random access is allowed (like arrays), Binary Search is objectively the fastest general purpose search algorithm in terms of time complexity.
- If the data is unsorted, then Hashing (e.g., using a Hash Table) gives average case (1) time, but that’s for key-value lookups—not ordered search.
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
public class Main
{
public static void main(String[] args)
{
int a[]={7,9,3,0,2,1,5};
for(int i=0; i<a.length-1; i++){
for(int j=0; ja[j+1]){
//bubble sort
int temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
for(int i=0; i<a.length; i++){
System.out.print(a[i]+" ");
}
}
}
public class Main
{
public static void main(String[] args)
{
int a[]={8,7,6,5,4,3,2,1};
for(int i=0; i<a.length-1; i++){
for(int j=0; ja[j+1]){
//bubble sort
int temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
for(int i=0; i<a.length; i++){
System.out.print(a[i]+" ");
}
}
}
what is the time complexity of bubble sort for all case ?
https://prepinsta.com/cpp-program/bubble-sort/ visit this page Ritik. We hope this will resolve your queries