Skip to interview prep
Apexed

You must sort millions of pixel intensity values in the range 0–255. Which algorithm do you pick?

EasySorting

Technical

Content review

Report an error

Not yet reviewed

Type or dictate your answer. Your draft is saved on this device.

Show model answer

Counting sort: one pass to build a histogram of 256 counters, then write each intensity out count times (or use prefix sums if the pixels carry extra data and order must be stable). It runs in O(n + 256) = O(n) time with a constant 256-entry table, far faster than any O(n log n) comparison sort for large images.

The histogram is often what you actually need anyway (for equalization or median filtering), so the same pass serves both purposes.

You must sort millions of pixel intensity values in the range 0–255. Which algorithm do you pick — Data structures & algorithms interview question — Apexed