PPractick

DSA interview question

Selection Sort

Easy · Algorithms · Topics: sorting, algorithm

The problem

A warehouse robot reorganises boxes on a shelf by weight, lightest first. Picking up and moving a box is slow and expensive, while reading a box's label is cheap. Selection sort fits this constraint: on each pass it scans the unsorted part to find the smallest item, then makes a single swap to put it in place. It always needs about n²/2 comparisons, but never more than n − 1 swaps, the fewest moves of any simple sorting algorithm. It's also the easiest algorithm to reason about, which is why it's usually the first one taught.

Example: [4, 1, 3, 9, 7] → [1, 3, 4, 7, 9].

Function signature

void selectionSort(vector<int>& a);  // sorts a in non-decreasing order, in place

Test cases

Input aOutputExplanation
[4, 1, 3, 9, 7][1, 3, 4, 7, 9]
[5, 2, 9, 1, 5, 6][1, 2, 5, 5, 6, 9]Duplicates are fine
[3, -1, 0, -7][-7, -1, 0, 3]Negative values
[1, 2, 3][1, 2, 3]Already sorted: still O(n²) comparisons, but no swaps
[4, 3, 2, 1][1, 2, 3, 4]Reverse order
[42][42]
[][]

(Confirm: sort in place in non-decreasing order; the code also cross-checks 1,000 random arrays against std::sort.)

How interviewers phrase it

Clarifying questions to ask

  1. Ascending or descending?
  2. In place, or can I return a new array?
  3. Does stability matter (keeping equal elements in their original order)?
  4. How large is the input? (Selection sort is only reasonable for small n.)

Follow-ups to expect

  1. "What's the time complexity?"
  2. "How many swaps does it make?"
  3. "Is it stable?"
  4. "Is it in place?"
  5. "Can you make it stable?"

Practise questions like this with a real engineer

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 interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in