Data Structures & AlgorithmsHardTCS Digital · Infosys SP

Counting sort on [1, 1, 2, 1, 0, 3, 3, 0, 2, 0] (values 0–4) builds count[], turns it into cumulative counts, then scans the input from RIGHT to LEFT placing each value v at index count[v] − 1 (0-based) and decrementing count[v]. What is the cumulative count array, and at which index is the LAST input element (0) placed?

  1. A. [3, 6, 8, 10, 10]; index 2
  2. B. [3, 6, 8, 10, 10]; index 3
  3. C. [3, 6, 8, 10, 10]; index 0
  4. D. [3, 3, 2, 2, 0]; index 2

Correct answer: A. [3, 6, 8, 10, 10]; index 2

Cumulative counts [3, 6, 8, 10, 10] give the end of each value's block. Scanning from the right places the last 0 at the last slot of its block, index 2, which keeps the sort stable.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic