fork download
  1. #!/usr/bin/env python
  2.  
  3. def counting_sort(array, maxval):
  4. """in-place counting sort"""
  5. n = len(array)
  6. m = maxval + 1
  7. count = [0] * m # init with zeros
  8. for a in array:
  9. count[a] += 1 # count occurences
  10. i = 0
  11. for a in range(m): # emit
  12. for c in range(count[a]): # - emit 'count[a]' copies of 'a'
  13. array[i] = a
  14. i += 1
  15. return array
  16.  
  17. print counting_sort( [1, 4, 7, 2, 1, 3, 2, 1, 4, 2, 3, 2, 1], 7 )
  18.  
Success #stdin #stdout 0.01s 8968KB
stdin
Standard input is empty
stdout
[1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 4, 4, 7]