Count Sort is a non-comparison-based sorting algorithm that sorts elements by counting their occurrences. It works efficiently for small integer ranges by using an auxiliary array to store frequency counts, then computes prefix sums to place elements directly into their sorted positions.
Modify the frequency array to hold the cumulative frequency. For each index i, update freq[i] to be the sum of freq[i] and freq[i-1]. This step allows placement of elements in their correct positions later.
#countsort.pydef countSort(arr): mini=min(arr) for i in range(0,len(arr)): arr[i]=arr[i]-mini maxi=max(arr) freq=[0]*(maxi+1) for i in range(0,len(arr)): freq[arr[i]]+=1 for i in range(1,len(freq)): freq[i]=freq[i]+freq[i-1] ans=[0]*(len(arr)) for i in range(len(arr) - 1, -1, -1): freq[arr[i]] -= 1 ans[freq[arr[i]]] = arr[i] + mini return ansarr=[-10,0,1,10,-4,7]ans=countSort(arr)for ele in ans: print(ele)
Cumulative frequency in Counting Sort is an essential technique that helps the algorithm efficiently determine the correct position for each element in the sorted output.Cumulative frequency tells us the position up to which an element will be placed in the sorted array. To get the correct position for each element, we use the cumulative frequency - 1.
While storing the final sorted result in the array, we traverse from the end to maintain the stability of the algorithm. If we move from the beginning, the relative order of duplicate elements will be broken.
The above implementation of Count Sort will fail when dealing with negative indices. This is because the implementation stores the frequency of each element at its own index in the frequency array, which assumes that all values are non-negative.
To handle negative element, subtract the most negative number in the array to every element. This ensures that all elements in the array are shifted into the non-negative range, allowing the Count Sort algorithm to work correctly.While returning the answer we must add to every element to get the correct sorted array.