Introduction
Bubble Sort is a fundamental algorithm that organizes elements by repeatedly comparing and exchanging adjacent values when they’re out of sequence. Although it’s not well-suited for large-scale data due to its slow performance, it remains a popular choice for teaching algorithm basics because of its simplicity. The method involves looping through the dataset multiple times until all elements are arranged in the correct order.
How Bubble Sort Works
The algorithm operates in multiple rounds. In each round, it traverses the array from start to finish, examining neighboring elements one pair at a time. Whenever it finds two elements in the wrong order, it switches their positions. With every complete pass, the largest unsorted element gradually moves to its rightful spot at the end of the array.
This process repeats until a full pass occurs with no swaps, indicating that the array is fully sorted.
Java Implementation
Here is a basic implementation of Bubble Sort in Java:
@Test
public void BubbleSortTest() throws Exception {
int[] arrToBeSorted = {55, 66, 88, 99, 677, 55, 25, 77};
bubbleSortingAlg(arrToBeSorted);
for (int elem : arrToBeSorted) {
System.out.println(elem + " ");
}
}
private void bubbleSortingAlg(int[] arrToBeSorted) {
int n = arrToBeSorted.length;
boolean swappedElems;
for (int i = 0; i < n - 1; i++) {
swappedElems = false;
for (int j = 0; j < n - i - 1; j++) {
if (arrToBeSorted[j] > arrToBeSorted[j + 1]) {
int temp = arrToBeSorted[j];
arrToBeSorted[j] = arrToBeSorted[j + 1];
arrToBeSorted[j + 1] = temp;
swappedElems = true;
}
}
if (!swappedElems) {
break;
}
}
}
Time and Space Complexity of Bubble Sort
- Best Case (Already Sorted): O(n)
- Average Case: O(n²)
- Worst Case (Reversed Order): O(n²)
- Space Complexity: O(1) (because it sorts in-place)
When to Use Bubble Sort
Bubble Sort is best suited for:
- Learning the fundamentals of sorting algorithms
- Small datasets where performance isn’t a major concern
- Situations where the focus is on simplicity over efficiency
For larger datasets or situations requiring high performance, algorithms like Quick Sort or Merge Sort are more suitable.
Conclusion
Bubble Sort serves as an excellent introductory sorting algorithm. Though it’s inefficient for handling large datasets, its simplicity and straightforward implementation make it a popular choice for beginners learning Java programming.
You can find the example code on Github.
