赞
踩
计数排序是一种非比较排序算法,适用于元素范围较小的整数排序。它通过统计每个元素出现的次数,然后根据计数对元素进行排序。
def counting_sort(lst): if not lst: return [] min_val = min(lst) max_val = max(lst) range_of_elements = max_val - min_val + 1 count_arr = [0] * range_of_elements output_arr = [0] * len(lst) for num in lst: count_arr[num - min_val] += 1 for i in range(1, len(count_arr)): count_arr[i] += count_arr[i - 1] for num in reversed(lst): output_arr[count_arr[num - min_val] - 1] = num count_arr[num - min_val] -= 1 return output_arr # 示例 lst = [4, 2, 2, 8, 3, 3, 1] sorted_lst = counting_sort(lst) print("排序后的列表:", sorted_lst)
桶排序适用于均匀分布的浮点数。它将数据分到有限数量的桶里,对每个桶分别排序,最后合并所有桶中的数据得到有序序列。
def bucket_sort(lst): if len(lst) == 0: return [] bucket_count = 10 max_value = max(lst) buckets = [[] for _ in range(bucket_count)] for num in lst: index = int(num * bucket_count / (max_value + 1)) buckets[index].append(num) for bucket in buckets: bucket.sort() sorted_lst = [] for bucket in buckets: sorted_lst.extend(bucket) return sorted_lst # 示例 lst = [0.78, 0.17, 0.39, 0.26, 0.72, 0.94, 0.21, 0.12, 0.23, 0.68] sorted_lst = bucket_sort(lst) print("排序后的列表:", sorted_lst)
基数排序是通过按位排序的方法,首先对最低位进行排序,然后对次低位进行排序,依次进行,直到最高位。基数排序适用于整数或字符串排序。
def counting_sort_for_radix(lst, exp): n = len(lst) output = [0] * n count = [0] * 10 for num in lst: index = num // exp count[index % 10] += 1 for i in range(1, 10): count[i] += count[i - 1] for num in reversed(lst): index = num // exp output[count[index % 10] - 1] = num count[index % 10] -= 1 for i in range(n): lst[i] = output[i] def radix_sort(lst): max_val = max(lst) exp = 1 while max_val // exp > 0: counting_sort_for_radix(lst, exp) exp *= 10 return lst # 示例 lst = [170, 45, 75, 90, 802, 24, 2, 66] sorted_lst = radix_sort(lst) print("排序后的列表:", sorted_lst)
通过以上实现,可以看到这三种排序算法在不同场景下的适用性。计数排序适用于范围较小的整数排序;桶排序适用于均匀分布的浮点数排序;基数排序适用于多位数的整数排序。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。