I realize this isn't the standard counting sort as stated in CLRS, but what does my simplified version lack that the standard counting sort has? I realize mine only sorts positive integers, but that should be pretty easy to tweak (by using maps).
def count_sort(array):
maximum = max(array)
minimum = min(0, min(array))
count_array = [0]*(maximum-minimum+1)
for val in array:
count_array[val] += 1
sorted_array = []
for i in range(minimum, maximum+1):
if count_array[i] > 0:
for j in range(0, count_array[i]):
sorted_array.append(i)
return sorted_array
array = [3,2,-1,1,5,0,10,18,25,25]
print array
print count_sort(array)
Edit: The reason why I thought this wasn't the standard counting sort was because the algorithm covered in the MIT OpenCourseware lecture seemed slightly more involved (http://youtu.be/0VqawRl3Xzs?t=34m54s).
You're doing something odd with your min and max. Try this:
def count_sort(array):
maximum = max(array)
minimum = min(array)
count_array = [0]*(maximum-minimum+1)
for val in array:
count_array[val-minimum] += 1
sorted_array = []
for i in range(minimum, maximum+1):
if count_array[i-minimum] > 0:
for j in range(0, count_array[i-minimum]):
sorted_array.append(i)
print sorted_array
array = [3,2,-1,1,5,0,10,18,25,25]
print array
count_sort(array)
I don't see problems with the way you're count-sorting, anyway some suggestions to your code come to mind that maybe can interest you.
For example the line:
minimum = min(0, min(array))
could be replaced with:
minimum = min(0, *array)
If you ran your code in python-2.x use xrange()
instead of range()
, so you could change:
for i in range(minimum, maximum+1):
with:
for i in xrange(minimum, maximum+1):
For the last loop you don't actually need range()
at all, check out the question pythonic way to do something N times , so you could change:
for j in range(0, count_array[i]):
sorted_array.append(i)
with:
for _ in itertools.repeat(None, count_array[i]):
sorted_array.append(i)
Do you mean http://en.wikipedia.org/wiki/Counting_sort ?
If yes, it's almost similar to your code. But it has one improvement: "The relative order of items with equal keys is preserved here, ie this is a stable sort.". So if you are sorting key-value dictionary order of the values will remain the same if they have equal keys.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.