1
我已经在python中实现了一个计数排序算法。我看到计数排序是稳定的,因为它保留了原始数组中元素的顺序。你认为下面的实现是稳定的吗?计数排序的稳定性
def countingsort(A,n):
C = [0]*n
B = [0]*n
# the value of A[i] becomes the index for counting
# C now stores the no. of occurences of element A[i] in A
for i in A:
C[i] = C[i] + 1
print i,C
# prepare the indexes for reinsertion
# Each position in C now holds the range of array position where a value will be placed
i = 0
while i < n:
#print i
C[i] = C[i] + C[i-1]
i += 1
print "Array position for each element",C
.
# the stability part of sort ???
for j in xrange(n-1,0,-1):
print "j",j,"A[j]:",A[j]
B[C[A[j]]-1] = A[j]
print B
C[A[j]] = C[A[j]] - 1
print C
print B
return B
if __name__ == '__main__':
A =[0,2,0,1,3,4,6,1,3,2]
countingsort(A,len(A))
计数排序在真实世界中的真正用处是什么?
*“你认为下面的实现是稳定的吗?”* - 你测试过了吗?发生了什么? – jonrsharpe
让我测试字典项目。我尝试使用整数不能给出正确的图片,因为它们都是一样的。 – Tammy
计数排序是对整数数组进行排序的一种快速方法,它可以从最低有效字节到最高有效字节进行排序,对于32位整数需要4遍,对于64位整数需要8遍。如果数组包含负数有符号整数,则需要修改该算法。 – rcgldr