DSA interview question
You're explaining sorting to a class by lining students up by height. The simplest rule anyone can follow: walk down the line, and whenever two neighbours are in the wrong order, swap them. After one walk, the tallest student has "bubbled" to the end; repeat with the rest. That's bubble sort. It's slow in general, but with one small optimisation (stop as soon as a full pass makes no swaps) it detects an already sorted line in a single pass. It's also stable, which matters when sorting records by one field.
Example: [5, 1, 4, 2, 8] → [1, 2, 4, 5, 8].
int bubbleSort(vector<int>& a); // sorts in place; returns the number of passes made
Input a | Output | Passes | Explanation |
|---|---|---|---|
[5, 1, 4, 2, 8] | [1, 2, 4, 5, 8] | 3 | The third pass makes no swaps, so the loop stops early |
[5, 2, 9, 1, 5, 6] | [1, 2, 5, 5, 6, 9] | 4 | Duplicates keep their relative order |
[1, 2, 3] | [1, 2, 3] | 1 | Already sorted: one pass, no swaps, O(n) |
[4, 3, 2, 1] | [1, 2, 3, 4] | 3 | Reverse order is the worst case |
[42] | [42] | 0 | Nothing to compare |
[] | [] | 0 |
(Confirm: sort in place, non-decreasing; the early exit is expected; the code also cross-checks 1,000 random arrays against std::sort.)
On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in