Files
Python/sorts/radix_sort.py
TheRodzzandChristian Clauss 5a6cc4869a fix(sorts): raise ValueError for negative inputs in radix_sort (#14950) (#14986)
* fix(sorts): raise ValueError for negative inputs in radix_sort (#14950)

This commit updates `radix_sort()` to validate that all integers in `list_of_ints` are non-negative.
Radix sort relies on digit-by-digit sorting and only supports non-negative integers.
If any negative integer is present in `list_of_ints`, `radix_sort()` now raises a `ValueError`.
Empty list input is also handled gracefully. Additionally, pre-commit noqa annotations are updated where needed.

Fixes #14950

* Apply suggestion from @cclauss

---------

Co-authored-by: Christian Clauss <cclauss@me.com>
2026-09-09 14:18:19 +02:00

59 lines
1.5 KiB
Python

"""
This is a pure Python implementation of the radix sort algorithm
Source: https://en.wikipedia.org/wiki/Radix_sort
"""
from __future__ import annotations
RADIX = 10
def radix_sort(list_of_ints: list[int]) -> list[int]:
"""
Examples:
>>> radix_sort([0, 5, 3, 2, 2])
[0, 2, 2, 3, 5]
>>> radix_sort(list(range(15))) == sorted(range(15))
True
>>> radix_sort(list(range(14,-1,-1))) == sorted(range(15))
True
>>> radix_sort([1,100,10,1000]) == sorted([1,100,10,1000])
True
>>> radix_sort([-1, 2, 3])
Traceback (most recent call last):
...
ValueError: All elements in list_of_ints must be non-negative integers
"""
if not list_of_ints:
return []
if any(i < 0 for i in list_of_ints):
raise ValueError("All elements in list_of_ints must be non-negative integers")
placement = 1
max_digit = max(list_of_ints)
while placement <= max_digit:
# declare and initialize empty buckets
buckets: list[list] = [[] for _ in range(RADIX)]
# split list_of_ints between the buckets
for i in list_of_ints:
tmp = int((i / placement) % RADIX)
buckets[tmp].append(i)
# put each buckets' contents into list_of_ints
a = 0
for b in range(RADIX):
for i in buckets[b]:
list_of_ints[a] = i
a += 1
# move to next
placement *= RADIX
return list_of_ints
if __name__ == "__main__":
import doctest
doctest.testmod()