Counting Sort is a non-comparison based sorting algorithm that works efficiently when you have a limited range of input values. It counts the frequency of each element and uses that information to place them in the correct sorted position. This makes it a highly efficient sorting method for scenarios with a small range of possible values.
importjava.util.Arrays;publicclassCountingSort{publicstaticvoidcountingSort(int[]arr,intmax){int[]countArray=newint[max+1];// Create a count array to store frequencies// Step 1: Count the frequency of each elementfor(intnum:arr){countArray[num]++;}// Step 2: Calculate cumulative frequenciesfor(inti=1;i<=max;i++){countArray[i]+=countArray[i-1];}int[]outputArray=newint[arr.length];// Step 3: Place elements in output arrayfor(intnum:arr){outputArray[countArray[num]-1]=num;countArray[num]--;}// Step 4: Copy sorted array back to original arraySystem.arraycopy(outputArray,0,arr,0,arr.length);}publicstaticvoidmain(String[]args){int[]arr={4,2,2,8,3,3,1,7,6,5,7};intmax=Arrays.stream(arr).max().getAsInt();// Find maximum value in the arraycountingSort(arr,max);System.out.println("Sorted Array: "+Arrays.toString(arr));}}
defcounting_sort(arr,max_val):count_array=[0]*(max_val+1)# Step 1: Count the frequency of each elementfornuminarr:count_array[num]+=1# Step 2: Calculate cumulative frequenciesforiinrange(1,max_val+1):count_array[i]+=count_array[i-1]output_array=[0]*len(arr)# Step 3: Place elements in output arrayfornuminarr:output_array[count_array[num]-1]=numcount_array[num]-=1returnoutput_arrayarr=[4,2,2,8,3,3,1,7,6,5,7]max_val=max(arr)sorted_arr=counting_sort(arr,max_val)print(f"Sorted Array: {sorted_arr}")
packagemainimport"fmt"funccountingSort(arr[]int,maxint)[]int{countArray:=make([]int,max+1)// Step 1: Count the frequency of each element
for_,num:=rangearr{countArray[num]++}// Step 2: Calculate cumulative frequencies
fori:=1;i<=max;i++{countArray[i]+=countArray[i-1]}outputArray:=make([]int,len(arr))// Step 3: Place elements in output array
for_,num:=rangearr{outputArray[countArray[num]-1]=numcountArray[num]--}returnoutputArray}funcmain(){arr:=[]int{4,2,2,8,3,3,1,7,6,5,7}max:=8// Assuming the maximum value is known
sortedArr:=countingSort(arr,max)fmt.Printf("Sorted Array: %v\n",sortedArr)}
Complexity Analysis
The time complexity of Counting Sort is O(n + k), where n is the number of elements in the input array and k is the range of the non-negative key values in the input.
The space complexity is O(k), where k is the range of values. This additional space is used to create the count array.