Advertisement
Guest User

Untitled

a guest
Aug 16th, 2017
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.72 KB | None | 0 0
  1. # Counting sort, like radix sort and bucket sort,
  2. # is an integer based algorithm (i.e. the values of the input
  3. # array are assumed to be integers). Hence counting sort is
  4. # among the fastest sorting algorithms around, in theory. The
  5. # particular distinction for counting sort is that it creates
  6. # a bucket for each value and keep a counter in each bucket.
  7. # Then each time a value is encountered in the input collection,
  8. # the appropriate counter is incremented. Because counting sort
  9. # creates a bucket for each value, a restriction is
  10. # that the maximum value in the input array be known beforehand.
  11.  
  12. # Implementation notes:
  13. # 1] Since the values range from 0 to k, create k+1 buckets.
  14. # 2] To fill the buckets, iterate through the input list and
  15. # each time a value appears, increment the counter in its
  16. # bucket.
  17. # 3] Now fill the input list with the compressed data in the
  18. # buckets. Each bucket's key represents a value in the
  19. # array. So for each bucket, from smallest key to largest,
  20. # add the index of the bucket to the input array and
  21. # decrease the counter in said bucket by one; until the
  22. # counter is zero.
  23.  
  24. # Best Case O(n+k); Average Case O(n+k); Worst Case O(n+k),
  25. # where n is the size of the input array and k means the
  26. # values range from 0 to k.
  27.  
  28. def counting_sort(some_list):
  29. max_value = 0
  30. for i in range(len(some_list)):
  31. if some_list[i] > max_value:
  32. max_value = some_list[i]
  33.  
  34. buckets = [0] * (max_value+ 1)
  35.  
  36. for i in some_list:
  37. buckets[i] += 1
  38.  
  39. i = 0
  40. for j in range(max_value + 1):
  41. counter, repetions = 1, buckets[j]
  42. while counter <= repetions:
  43. some_list[i] = j
  44. counter+=1
  45. i+=1
  46.  
  47. return some_list
  48.  
  49. print(counting_sort([1,23,4,5,6,7,8]))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement