Bubble Sort in Java
Introduction
Bubble Sort is a simple sorting algorithm used to arrange elements in ascending or descending order.
It works by comparing two adjacent elements and swapping them if they are in the wrong order.
Example
Let's take an array:
int[] arr = {11, 13, 10, 9};
Our goal is to sort it in ascending order.
Pass 1:
11 13 10 9
11 10 13 9
11 10 9 13
Pass 2:
10 11 9 13
10 9 11 13
Pass 3:
9 10 11 13
Now the array is sorted!
Java Code
for (int i = 0; i < n - 1; i++) {
for (int j = 1; j < n - i; j++) {
if (arr[j] < arr[j - 1]) {
int temp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = temp;
}
}
}
How It Works
- Outer loop controls the number of passes.
- Inner loop compares adjacent elements.
- If the current element is smaller than the previous element, they are swapped.
- After every pass, the largest unsorted element moves to the end.
Time Complexity
- Best Case: O(n²)
- Average Case: O(n²)
- Worst Case: O(n²)
- Space Complexity: O(1)
Conclusion
Bubble Sort is easy to understand and implement. It is a good starting point for learning sorting algorithms in Java.
Top comments (0)