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 + " ");
}
}
}
Sorted Array: 16 25 32 44 55
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) |
O(1)
→ only a few variables used; no extra memory needed.
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
We’re here to make our tutorials better based on your thoughts and suggestions.