Junior — Middle
Explain the mechanism of the bubble sort method and its features.
sobes.tech AI
Answer from AI
Bubble sort is a simple sorting algorithm that repeatedly passes through the list, compares adjacent elements, and swaps them if they are in the wrong order. The passes are repeated until the list is sorted.
Features:
- Easy to implement.
- Inefficient on large datasets (worst-case time complexity O(n²)).
- Can be optimized if no swaps are made during a pass — meaning the array is already sorted.
Example in Java:
void bubbleSort(int[] arr) {
int n = arr.length;
boolean swapped;
for (int i = 0; i < n - 1; i++) {
swapped = false;
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true;
}
}
if (!swapped) break; // array is already sorted
}
}