Posted By

themoosemind on 05/17/12


Tagged

sorting


Versions (?)

Counting Sort


 / Published in: Python
 

This is a python implementation of counting sort with an usage example.

  1. def countingSort(A, k):
  2. """ implementation of counting sort """
  3. B = [0 for el in A]
  4. C = [0 for el in xrange(0, k+1)]
  5.  
  6. for i in xrange(0, k +1):
  7. C[i] = 0
  8.  
  9. for j in xrange(0, len(A)):
  10. C[A[j]] += 1
  11.  
  12. for i in xrange(1, k + 1):
  13. C[i] += C[i - 1]
  14.  
  15. for j in xrange(len(A)-1, 0 - 1, -1):
  16. tmp = A[j]
  17. tmp2= C[tmp] -1
  18. B[tmp2] = tmp
  19. C[tmp] -= 1
  20. return B
  21.  
  22. """ Usage example """
  23. print countingSort([6,0,2,0,1,3,4,6,1,3,2], 6)

Report this snippet  

You need to login to post a comment.