Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Counting Sort

Python Counting Sort

Document Object Reference Manual Python3 Examples

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

)

print

(

"

Character array sorted %s

"

%

(

"

"

.

join

(

ans

)

)

)

The output of the code above is:


符数组排序 bcmnoooruwww

Document Object Reference Manual Python3 Examples