Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions sorting and basics/sorting.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,38 @@ def insertionsort(a):
a[j] = item
return a

def countsort(a):
""" count sort implementation
>>> countsort([6,4,8,2,1,9,10])
[1,2,4,6,8,9,10]

Time complexity = O(n+k)
Space complexity = O(n+k)
where k is the number of elements in a particular range
n is the length of the input array
"""
#to figure out the range of numbers in the array
maxval=max(a)
minval=min(a)
numberOfElements=maxval-minval+1
countArray=[0]*numberOfElements
resultArray=[0]*len(a)

#finding count of each element in the array and storing them in count array
for item in a:
countArray[item-minval]+=1
for item in range(1,len(countArray)):
countArray[item]+=countArray[item-1]

#storing in result array
for item in range(len(a)-1,-1,-1):
resultArray[countArray[a[item]-minval]-1]=a[item]
countArray[a[item]-minval]-=1
#sorted input array
for item in range(len(a)):
a[item]=resultArray[item]
return a

if __name__ == "__main__":
import doctest
doctest.testmod(verbose=True)