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