Skip to content

Resource · Guide or article

Counting Sort

Counting sort for small integer keys, including why it sidesteps the comparison-sort lower bound and how it relates to radix and bucket sort.

Reviewed

Open the original: Counting Sort (opens the original site in a new tab)

Add to a roadmap

Keep this resource with a roadmap you follow. It appears as your own extra resource; the roadmap's steps don't change and it doesn't count toward your tracked steps.

Source content: English

In computer science, counting sort is an algorithm for sorting a collection of objects according to keys that are small integers; that is, it is an integer sorting algorithm. It operates by counting the number of objects that have each distinct key value, and using arithmetic on those counts to determine the positions of each key value in the output sequence. Its running time is linear in the number of items and the difference between the maximum and minimum key values, so it is only suitable for direct use in situations where the variation in keys is not significantly greater than the number of items. However, it is often used as a subroutine in another sorting algorithm, radix sort, that can handle larger keys more efficiently. Because counting sort uses key values as indexes into an array, it is not a comparison sort, and the Ω(n log n) lower bound for comparison sorting does not apply to it. Bucket sort may be used for many of the same tasks as counting sort, with a similar time analysis; however, compared to counting sort, bucket sort requires linked lists, dynamic arrays or a large amount of preallocated memory to hold the sets of items within each bucket, whereas counting…

PrepKit overview

PrepKit editors wrote and reviewed this overview from the source repository. It is not text from the resource itself.

Suited to
The source does not state a level
Format
Reference

What it covers

  • Why it is not a comparison sort and when the key range makes it suitable.
  • Three steps: count occurrences, build cumulative counts, place items into the output array.
  • Complexity table: n + r time and memory, stable, with r the largest number.

How to use it

PrepKit study advice, not a claim made by the source.

Sort [4, 2, 2, 8, 3, 3, 1] by hand through all three steps, then code it and keep it stable.

Scope and limitations

Step illustrations are images hosted on an external blog. No negative-number handling or exercises. A Portuguese version is linked.

Access and format

Free English README on GitHub in trekhleb/javascript-algorithms (MIT license).

Reviewed by PrepKit on Oct 2, 2026. Listing source commit: 85293e3e2b88

Evidence behind this overview
  • src/algorithms/sorting/counting-sort/README.md

Pages that include this

Get the PrepKit newsletter

Optional. You don't need it to use PrepKit.

How we handle your email