Sub topic 13
Handling Negative Numbers and Strings
This chapter assumes you have already built counting_sort_by_key and LSD radix sort for non-negative integers. You should also know how two's complement represents negative integers, and how Python's bytes type stores text. The radix sort you have so far only accepts keys that are non-negative integers, so this chapter shows how to turn two other kinds of key into that form while keeping their order.
Why Negative Numbers Break the Basic Version
The digit extraction (x >> shift) & mask assumes every key is a non-negative integer. Python handles negative numbers with an infinitely sign-extended two's complement form, so -3 >> 8 is -1 and the loop that checks max_val >> shift never sees the sign. In C or Java, the sign bit of a negative number is 1, so after the last pass negative keys land after positive ones.
You can fix this with either of two transforms. Both keep the order of the keys:
| Approach | How it works | When to use it |
|---|---|---|
| Offset by minimum | Subtract `min(a)` from every key, sort, add it back | Python, or when `max - min` fits in your integer type |
| Flip the sign bit | Treat `x ^ (1 << (w-1))` as an unsigned w-bit value | Fixed-width integers in C, Java, Rust |
Here is how the sign-bit flip works with 8-bit values: -128 becomes 0, -1 becomes 127, 0 becomes 128 and 127 becomes 255. The unsigned order of the flipped values matches the signed order of the originals. The offset approach is simpler, but in a fixed-width language max - min can overflow. For example, the range from -2^63 to 2^63-1 does not fit in a signed 64-bit integer.
Sorting Signed Integers by Offsetting
def counting_sort_by_key(items, key, 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_signed(a, bits=8):
if not a:
return []
lo = min(a)
out = [x - lo for x in a] # now every key is >= 0
mask = (1 << bits) - 1
top = max(out)
shift = 0
while (top >> shift) > 0:
out = counting_sort_by_key(out, lambda x: (x >> shift) & mask, mask)
shift += bits
return [x + lo for x in out]
print(radix_sort_signed([5, -3, 0, -10, 7, 2])) # [-10, -3, 0, 2, 5, 7]Offsetting also has a side benefit. If the keys sit in a narrow band such as 1,000,000 to 1,000,255, subtracting the minimum leaves values that fit in a single 8-bit digit, so the sort needs only one pass.
Sorting Strings
Each byte of a string works as a digit with radix 256. Lexicographic order compares strings from the left, so the first byte is the most significant digit. In UTF-8, byte order matches Unicode code-point order, which is the same order Python's sorted uses for strings.
Strings can have different lengths, and a shorter string must sort before any longer string that starts with it: "ba" comes before "bat". To get this, treat a missing position as digit 0 and shift every real byte up by one, so the digits run from 0 to 256:
def counting_sort_by_key(items, key, 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_strings(words):
if not words:
return []
pairs = [(w.encode("utf-8"), w) for w in words]
width = max(len(b) for b, _ in pairs)
for i in range(width - 1, -1, -1): # rightmost position first
pairs = counting_sort_by_key(
pairs,
lambda p: p[0][i] + 1 if i < len(p[0]) else 0,
256,
)
return [w for _, w in pairs]
print(radix_sort_strings(["bat", "b", "apple", "ba", "cat"]))
# ['apple', 'b', 'ba', 'bat', 'cat']Common Errors
- Forgetting the +1 shift on real bytes. Without it, a missing position and a zero byte get the same digit. That breaks ties wrongly for strings that contain
\x00. - Sorting the strings with
ordinstead of encoding them first. A code point can be as large as 0x10FFFF, which forces a count array of about 1.1 million entries on every pass. - Applying the offset trick to 64-bit keys in C. If the range overflows, the order of the keys is silently corrupted.
Exercise
Using the 8-bit sign-bit flip, what unsigned values do -5, 3, and -128 map to, and what order do they sort into?
Show answer
Flipping bit 7 is the same as adding 128 modulo 256, so -5 maps to 123, 3 maps to 131, and -128 maps to 0. The unsigned order 0, 123, 131 gives -128, -5, 3, which is the correct signed order.
Exercise
Why must radix_sort_strings loop from position width-1 down to 0 rather than from 0 upward?
Show answer
LSD radix sort has to process the least significant digit first. For strings that is the rightmost position. Each stable pass keeps the order set by earlier passes when the current digit ties, so the leftmost byte, which is the most significant digit, has to be sorted last for it to decide the final order.