Python Counting Sort
The core of counting sort is to convert the input values into keys stored in an additionally allocated array. As a linear-time sorting algorithm, counting sort requires the input data to be integers within a definite range.
Example
def
countSort
(
arr
)
:
output
=
[
0
for
i
in
range
(
256
)
]
count
=
[
0
for
i
in
range
(
256
)
]
ans
=
[
"
"
for
_
in
arr
]
for
i
in
arr
:
count
[
ord
(
i
)
]
+=
1
for
i
in
range
(
256
)
:
count
[
i
]
+=
count
[
i
1
]
for
i
in
range
(
len
(
arr
)
)
:
output
[
count
[
ord
(
arr
[
i
]
)
]
1
]
=
arr
[
i
]
count
[
ord
(
arr
[
i
]
)
]
-=
1
for
i
in
range
(
len
(
arr
)
)
:
ans
[
i
]
=
output
[
i
]
return
ans
arr
=
"
wwwrunoobcom
"
ans
=
countSort
(
arr
)
(
"
Character array sorted %s
"
%
(
"
"
.
join
(
ans
)
)
)
The output of the code above is:
符数组排序 bcmnoooruwww
Python3 Examples