Bubble Sort
1 min readJun 6, 2025
This algorithm focuses on moving the highest element to the end by swapping a larger neighboring element to the right.
- We perform the operation only
n - 1times (outer loop) because the last element will automatically be in the correct position once the others are sorted. - We maintain a boolean flag to check if any swap occurred during a particular cycle. If no swaps happen, it means the array is already sorted.
- Since one element reaches its correct position at the end in each cycle, we reduce the number of inner loop iterations by the current outer loop count, i.e.,
n - 1 - i. Also, we compare thejth element with the(j + 1)th element. - If the neighboring element is greater, it will be swapped.
Get Harshavardhana P’s stories in your inbox
Join Medium for free to get updates from this writer.
public void bubbleSort(int[] arr){
int n=arr.length;
for (int i = 0; i < n-1; i++) {
boolean swapped=false;
for (int j = 0; j < n-i-1; j++) {
if (arr[j]>arr[j+1]) {
swapped=true;
int temp=arr[j+1];
arr[j+1]=arr[j];
arr[j]=temp;
}
}
if(!swapped){
break;
}
}
}




