1. 程式人生 > >Python實現計數排序

Python實現計數排序

#! /usr/bin/env python
#coding=utf-8

#計數排序
def CountingSort(a, b, k):
    #c=[0]*(k+1) #let c[0...k] be an all 0 array
    #c=[0 for i in range(0,k+1)]
    c=[]
    for i in range(k+1):
        c.append(0)
    for j in range(len(a)):
        c[a[j]] = c[a[j]] + 1
    for i in range(1, k+1):
        c[i] = c[i] + c[i-1
] for j in range(len(a)-1, -1, -1): b[c[a[j]]-1] = a[j]#!!!!!減一是關鍵 c[a[j]] = c[a[j]] - 1 print b if __name__ == '__main__': a=[2, 5, 3, 0, 2, 3, 0, 3] #b=[0]*len(a) b=[None for i in range(len(a))] CountingSort(a, b, max(a))