问题:你有一个未排序的整数列表,需要对它进行有效的升序排序。
解决方案: 使用 Radix 排序算法对列表进行排序。Radix Sort 的工作原理是处理从最小有效数字到最大有效数字的数字,根据每个数字的值将数字分配到桶中,然后按正确顺序将它们收集起来。这一过程会持续到每个数字位置,最终得到一个完全排序的列表。
Python 代码:
def radix_sort (arr):
# Find the maximum number to determine the number of digits
max_num = max (arr)
num_digits = len(str (max_num))
# Initialize buckets
buckets = [[] for _ in range (10)]
# Perform counting sort for each digit, starting from the least significant digit
for digit_place in range(1, num_digits + 1):
# Distribute numbers into buckets
for num in arr:
digit = (num // 10** (digit_place - 1)) % 10
buckets[digit].append (num)
# Collect numbers from buckets
arr = [num for bucket in buckets for num in bucket]
# Clear buckets for the next pass
buckets = [[] for _ in range (10)]
return arr
# Example usage:
unsorted_list = [170, 45, 75, 90, 802, 24, 2, 66]
sorted_list = radix_sort (unsorted_list)
print (sorted_list) # [2, 24, 45, 66, 75, 90, 170, 802]

