0% found this document useful (0 votes)
46 views1 page

Countingsort PDF

Counting sort uses a cumulative frequency distribution to sort integers in a known range from 0 to k-1. It counts the frequency of each integer in the input array to build a distribution, then uses the cumulative distribution to place the elements in the output array in order, achieving a runtime of Θ(n+k) and space complexity of Θ(k). Counting sort is only preferable when k is much smaller than n log n due to its requirement of knowing the range of integers.

Uploaded by

Andrew Lee
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views1 page

Countingsort PDF

Counting sort uses a cumulative frequency distribution to sort integers in a known range from 0 to k-1. It counts the frequency of each integer in the input array to build a distribution, then uses the cumulative distribution to place the elements in the output array in order, achieving a runtime of Θ(n+k) and space complexity of Θ(k). Counting sort is only preferable when k is much smaller than n log n due to its requirement of knowing the range of integers.

Uploaded by

Andrew Lee
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Counting Sort

For Counting Sort, the input is n integers in some known range [0, k 1].
1

def CountingSort :
C = [0]* k , B = [0] * n
for j in [1 , n ]:
C [ A [ j ]] += 1
# C = distribution
for i in [1 , k ]:
C [ i ] = C [i -1] + C [ i ] # C = Cumulative distribution
for j in [n , 1]:
B [ C [ A [ j ]]] = A [ j ]
C [ A [ j ]] - return B

The algorithm calculates a cumulative frequency distribution for the


numbers in the input array in the first 2 passes, so that C[i] is the number
of elements less than or equal to i. In the final loop, the algorithm puts
the last element from A into B based on its position within the cumulative
distribution, then recurses (iteratively) on A[:-1].
Counting sort has (n + k) runtime and space complexity and is a stable
sort. For obvious reasons, it should only be preferred if k << n lg n.

You might also like