Optimizing Bubble Sort with Early Termination Using a Boolean Flag
The article recounts a interview scenario where a candidate struggled with a basic bubble sort implementation, then explains the standard bubble sort algorithm, its inefficiencies, and demonstrates an optimization that adds a boolean flag to detect a sorted pass and terminate early, improving performance.
Recently a reader shared an interview experience at Meituan where the interviewer asked him to write bubble sort on paper, catching him off guard despite his familiarity with the algorithm.
The article first presents a straightforward Java implementation of bubble sort:
public void bubbleSort(int[] source) {
for(int i = source.length - 1; i > 0; i--) {
for(int j = 0; j < i; j++) {
if(a[j] > a[j+1])
// swap omitted
swap(source, j, j+1);
}
}
}While functionally correct, the code can be optimized because once a pass makes no swaps the array is already sorted, and further passes are unnecessary.
The suggested improvement introduces a boolean flag that records whether any swap occurred during a pass; if no swap happens, the method returns early:
public void bubbleSort(int[] source) {
boolean exchange;
for(int i = source.length - 1; i > 0; i--) {
exchange = false;
for(int j = 0; j < i; j++) {
if(a[j] > a[j+1]) {
swap(source, j, j+1);
exchange = true;
}
}
if(!exchange) return;
}
}This simple change reduces the best‑case time complexity to O(N) when the input is already sorted, while the worst‑case remains O(N²). The article also reflects on why interviewers still ask about classic algorithms: they test fundamental understanding and problem‑solving mindset rather than just memorization.
Finally, the author encourages readers to study classic data structures and algorithms thoroughly and to practice interview questions to avoid similar pitfalls.
Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.