Video in progress
How does bubble sort work, and why wouldn't you use it in real code?
It compares neighboring elements and swaps the ones in the wrong order; on each pass the largest "floats up" to the end. Time is O(n²), so in real code you use Arrays.sort or List.sort instead.
📖 Answer
static void bubbleSort(int[] a) {
for (int end = a.length - 1; end > 0; end--) {
boolean swapped = false;
for (int i = 0; i < end; i++) {
if (a[i] > a[i + 1]) {
int t = a[i]; a[i] = a[i + 1]; a[i + 1] = t;
swapped = true;
}
}
if (!swapped) break; // already sorted
}
}
The swapped flag matters: if the array is already sorted, it stops after one pass, so the best case is O(n).
Why do they ask it in an interview? To see whether you can write the loop bounds and the swap without mistakes. But with 100,000 elements, bubble sort does about 5 billion comparisons, while the standard sort finishes in under two million.
In practice you don't write your own sorting algorithm. If you need one, use Arrays.sort, Collections.sort or stream().sorted().
Sign up to mark studied questions and save your progress.