计数排序(真实排序,相同元素位置不变)
"""
对计数数组进行变形,新元素的值是前面元素累加之和的值,相当于进行排序
即计算原始数组中的每个数字在结果数组中处于的位置。
逆序遍历原始数组,可以使相同元素的相对位置不改变
"""
def NumSort1(arr, low, high):
# low可以最为数组的偏移量,用于将数据对号入座
size = high - low + 1 # 临时数组的长度
temp = [0] * size
for i in range(len(arr)): # 遍历无序数组
# 每一个元素值减去最小值,得到在临时数组中的实际位置,偏移量计算
k = arr[i] - low
for j in range(size):
# 将值放入到对应的索引位置
if k == j:
temp[j] += 1
# 对临时数组temp进行变形,新元素的值是前面元素累加之和的值,即计算原始数组中数字在结果中的真实排序位置
for j in range(1, size):
# temp的索引:元素值
# 值:元素值对应的排序名次
temp[j] = temp[j] + temp[j - 1]
# 将计数数组temp输出到结果数组的对应排序名次中
result = [0] * len(arr)
for i in range(len(arr)-1,-1,-1): # 遍历原始数组
# 找到对应的计数数组的位置
k = arr[i] - low # 偏移之后的索引
for j in range(size): # 遍历计数数组temp
if k == j: # 匹配到计数数组对应的索引
result[temp[j] - 1] = k + low # 将对应元素的正确的排序名次写入到result
temp[j] -= 1
# 把结果数组返回
return result
if __name__ == '__main__':
a = [101, 109, 107, 103, 108, 102, 103, 110, 107, 103]
print(NumSort1(a, min(a), max(a))) # 哇,舒服了