Sub topic 13
Handling Negative Numbers and Strings
This chapter assumes you have read the earlier chapters on stable counting sort, LSD radix sort, and MSD radix sort. It also assumes you know how two's-complement integers are stored. Up to now every key has been a non-negative integer. Real data often has negative numbers and text keys. This chapter shows how to turn those keys into non-negative digits while keeping their order the same, and covers the edge cases that break simple versions.
The code blocks build on each other. Run them in order in one Python session, because later blocks reuse counting_sort_by_key and radix_sort_lsd from the first block.
What Goes Wrong with Negative Keys
The LSD radix sort from earlier chapters pulls out digits with (x >> shift) & mask and stops once max_val >> shift reaches zero. Both steps assume x >= 0. In Python, >> on a negative number is an arithmetic shift, so the sign spreads into the high bits, and & mask then returns a large positive digit. If every value is negative, the loop condition is false from the start and the input comes back unsorted.
def counting_sort_by_key(items, key, k):
"""Stable sort of items whose key(item) is an integer in 0..k."""
counts = [0] * (k + 1)
for item in items:
counts[key(item)] += 1
total = 0
for v in range(k + 1):
counts[v], total = total, total + counts[v]
out = [None] * len(items)
for item in items:
kv = key(item)
out[counts[kv]] = item
counts[kv] += 1
return out
def radix_sort_lsd(a, bits_per_digit=8):
"""Sort non-negative integers using LSD radix sort."""
if not a:
return []
mask = (1 << bits_per_digit) - 1
max_val = max(a)
out = list(a)
shift = 0
while (max_val >> shift) > 0:
out = counting_sort_by_key(out, lambda x: (x >> shift) & mask, mask)
shift += bits_per_digit
return out
print(radix_sort_lsd([-5, -1, -3])) # [-5, -1, -3] loop never ran
print(radix_sort_lsd([3, -1, 2])) # [2, 3, -1] -1 became digit 255Neither run raises an error. Both just return the wrong order. The fix is to map every key to a non-negative integer with an order-preserving function: if a < b, then f(a) < f(b). The two standard maps are an offset and a sign-bit flip.
Approach 1: Subtract the Minimum
Shifting every value by -min(a) moves the smallest key to 0 and keeps the gaps between keys unchanged.
def radix_sort_signed(a):
"""Sort integers that may be negative by shifting them to start at 0."""
if not a:
return []
lo = min(a)
shifted = [x - lo for x in a]
return [x + lo for x in radix_sort_lsd(shifted)]
print(radix_sort_signed([5, -3, 0, -10, 7, 2])) # [-10, -3, 0, 2, 5, 7]
print(radix_sort_signed([-5, -1, -3])) # [-5, -3, -1]This method works for any integers in Python, and it has a side benefit. The number of passes depends on the spread max - min, not on the size of the values. Keys between 1,000,000 and 1,000,255 need one 8-bit pass after shifting, where the plain version would need three.
Watch for these edge cases:
- Overflow in fixed-width languages. In C, Java, or NumPy with
int64,x - looverflows when the range is wider than half the type, for example[-2**63, 2**63 - 1]. Do the subtraction in the unsigned type of the same width. There it wraps correctly, and the result always fits. - Extra passes over the data. Finding
minandmaxcosts one pass, buildingshiftedcosts another, and shifting back costs a third. With records instead of bare integers, you would computekey(item) - loinside the key function instead of copying the data.
Approach 2: Flip the Sign Bit
For fixed-width integers there is a cheaper map that needs no scan for the minimum. In 32-bit two's complement, negative numbers have the top bit set. If you read the bits as unsigned, negatives therefore come after all the positives. XOR-ing the top bit swaps the two halves: the most negative value becomes 0 and the most positive becomes 2**32 - 1, and order within each half does not change.
def int32_key(x):
"""Order-preserving map from a signed 32-bit int to an unsigned 32-bit int."""
return (x & 0xFFFFFFFF) ^ 0x80000000
def radix_sort_int32(a):
"""LSD radix sort for values in the signed 32-bit range, 8 bits per pass."""
out = list(a)
for shift in (0, 8, 16, 24):
out = counting_sort_by_key(
out, lambda x: (int32_key(x) >> shift) & 0xFF, 0xFF
)
return out
data = [5, -3, 0, -2147483648, 2147483647, -1]
print(radix_sort_int32(data))
# [-2147483648, -3, -1, 0, 5, 2147483647]
assert radix_sort_int32(data) == sorted(data)The flip only affects the top byte, so production code often leaves the first three passes alone and applies ^ 0x80 to the digit in the last pass. Some implementations skip the flip and handle the top byte by placing buckets 128–255 before buckets 0–127. Both give the same result.
| Method | Needs a min scan | Pass count depends on | Works for unbounded ints | Overflow risk |
|---|---|---|---|---|
| Subtract minimum | Yes | `max - min` | Yes | Yes, unless you subtract in an unsigned type |
| Flip sign bit | No | Fixed type width | No | None |
String Keys: Characters as Digits
A string is a sequence of digits where each character is one digit. Lexicographic order compares the first characters, then the second characters, and so on. This is exactly the most-significant-first order that radix sort uses. Two decisions remain: which digits to use, and how to handle strings of different lengths.
Which digits. Python characters are Unicode code points up to 0x10FFFF, so a count array indexed by code point would have over a million entries for every pass. Encode the strings to UTF-8 instead. Each digit is then a byte (0–255), and UTF-8 byte order matches code point order, so the sorted result equals sorted() on the original strings. UTF-16 does not have this property: characters above U+FFFF are stored as surrogate pairs, which sort before U+E000–U+FFFF.
Uneven lengths. "ban" must come before "banana" because it is a prefix. To get that, give every position past the end of a string a digit lower than any real byte. Use 0 for "no character here" and byte + 1 for real bytes, so the radix is 257.
LSD Radix Sort on Variable-Length Strings
LSD processes positions from right to left. Shorter strings get padded with the 0 digit.
def lsd_string_sort(strings):
"""Stable LSD radix sort of str values by their UTF-8 bytes."""
data = [(s, s.encode("utf-8")) for s in strings]
if not data:
return []
width = max(len(b) for _, b in data)
for pos in range(width - 1, -1, -1):
data = counting_sort_by_key(
data,
lambda item: item[1][pos] + 1 if pos < len(item[1]) else 0,
256,
)
return [s for s, _ in data]
words = ["banana", "band", "ban", "apple", "b", "bandana", "éclair", "zebra"]
print(lsd_string_sort(words))
# ['apple', 'b', 'ban', 'banana', 'band', 'bandana', 'zebra', 'éclair']
assert lsd_string_sort(words) == sorted(words)This is correct, but the cost is O(W · (n + 257)), where W is the length of the longest string. One 10,000-byte string in a list of short words forces 10,000 passes over every element. LSD suits keys with a fixed or nearly fixed length, such as dates, ZIP codes, or hashes. For data with mixed lengths, use MSD.
MSD Radix Sort on Strings
MSD sorts by the first byte, then recurses into each bucket on the next byte. Strings that have run out of characters land in bucket 0. At that point they are all identical, so they need no further work. The recursion only reads the bytes it needs to tell strings apart. Each call allocates a 257-entry count array, though, so small buckets go to a comparison sort below a cutoff size.
def msd_string_sort(strings, cutoff=16):
"""MSD radix sort of str values by UTF-8 bytes."""
data = [(s, s.encode("utf-8")) for s in strings]
_msd(data, 0, len(data), 0, cutoff)
return [s for s, _ in data]
def _msd(data, lo, hi, depth, cutoff):
if hi - lo <= cutoff:
data[lo:hi] = sorted(data[lo:hi], key=lambda item: item[1][depth:])
return
def digit(item):
b = item[1]
return b[depth] + 1 if depth < len(b) else 0
data[lo:hi] = counting_sort_by_key(data[lo:hi], digit, 256)
start = lo
while start < hi:
d = digit(data[start])
end = start + 1
while end < hi and digit(data[end]) == d:
end += 1
if d != 0: # bucket 0 holds strings that ended here: all equal
_msd(data, start, end, depth + 1, cutoff)
start = end
import random
random.seed(1)
words = ["".join(random.choice("abc") for _ in range(random.randint(0, 6)))
for _ in range(1000)]
assert msd_string_sort(words, cutoff=1) == sorted(words)
assert msd_string_sort(words) == sorted(words)
print(msd_string_sort(
["she", "sells", "sea", "shells", "by", "the", "sea", "shore"], cutoff=1))
# ['by', 'sea', 'sea', 'sells', 'she', 'shells', 'shore', 'the']Three gotchas apply to this implementation:
- Recursion depth grows with the length of the longest shared prefix. Python's default limit of 1000 frames fails on many long, near-identical strings such as URLs or file paths. Use an explicit stack in that case.
- Duplicates are cheap. Equal strings descend together and stop at bucket 0. Long shared prefixes are expensive, because each shared byte costs a full counting pass over that bucket.
- The cutoff matters more than you would expect. With
cutoff=1, every tiny bucket pays for a 257-entry count array. Values in the range 8–32 are typical choices.
Exercises
Exercise
radixsortsigned is called on [1012, 1012 + 3, 10**12 + 1]. How many 8-bit counting passes run, and how many would radixsortlsd run on the same list without the shift?
Show answer
After subtracting the minimum the values are [0, 3, 1], so maxval is 3 and one pass runs. Without the shift, maxval is about 2**40, so the loop runs until the shift reaches 40, which is 5 passes (shifts 0, 8, 16, 24, 32).
Exercise
Why does lsdstringsort use item[1][pos] + 1 for real bytes instead of item[1][pos]? Give an input that would sort wrong without the + 1.
Show answer
Missing positions use digit 0, so real bytes must start at 1 for a shorter prefix to sort first. Without the + 1, the byte 0x00 and the padding would share digit 0. Then "a" and "a\x00" have equal keys, and the stable sort keeps their input order. The input ["a\x00", "a"] would stay as it is, even though "a" < "a\x00".
Exercise
You need to sort 50 million 64-bit signed integers in C and also 2 million file paths with long shared prefixes. Which technique would you use for each, and why?
Show answer
For the integers, use LSD radix sort with the sign-bit flip. The width is fixed, no min scan is needed, and nothing can overflow. For the file paths, use MSD radix sort with an explicit stack and a small-bucket cutoff, or a comparison sort. LSD would pay for the full length of the longest path on every element, and recursive MSD could overflow the stack on the long shared prefixes.