Skip to content
This repository has been archived by the owner on Apr 29, 2020. It is now read-only.

Commit

Permalink
Add counting sort (#35)
Browse files Browse the repository at this point in the history
Add counting sort with test
  • Loading branch information
malayaleecoder authored and aktech committed Apr 14, 2016
1 parent 30f44b9 commit 92c90ce
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 1 deletion.
7 changes: 6 additions & 1 deletion docs/source/sorting.rst
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,9 @@ Quick Sort
Sleep Sort
----------

.. autofunction:: pydsa.sleep_sort
.. autofunction:: pydsa.sleep_sort

Counting Sort
----------

.. autofunction:: pydsa.counting_sort
1 change: 1 addition & 0 deletions pydsa/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,4 @@
from .binary_search import binary_search
from .linear_search import linear_search
from .queue import queue
from .counting_sort import counting_sort
24 changes: 24 additions & 0 deletions pydsa/counting_sort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Counting Sort
# Complexity : O(n + (range of input))
# https://en.wikibooks.org/wiki/Algorithm_Implementation/Sorting/Counting_sort


def counting_sort(array, maxval):
"""
Sorts the list 'array' using counting sort
>>> from pydsa import counting_sort
>>> a = [5, 6, 1, 9, 3]
>>> counting_sort(a, 9)
[1, 3, 5, 6, 9]
"""
count = [0] * (maxval + 1)
for a in array:
count[a] += 1
i = 0
for a in range(maxval + 1):
for c in range(count[a]):
array[i] = a
i += 1
return array
7 changes: 7 additions & 0 deletions pydsa/tests/test_counting_sort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from pydsa.counting_sort import counting_sort
from random import randint


def test_counting_sort():
a = b = [randint(1, 100) for i in range(100)]
assert counting_sort(a, max(a)) == sorted(b)

0 comments on commit 92c90ce

Please sign in to comment.