counting sort Algorithm
Bucket sort may be used for many of the same tasks as counting sort, with a like time analysis; however, compared to counting sort, bucket sort necessitates associated lists, dynamic arrays or a large amount of preallocated memory to keep the sets of items within each bucket, whereas counting sort instead stores a individual number (the count of items) per bucket.
Because counting sort uses key values as indexes into an array, it is not a comparison sort, and the Ω(n log N) Although radix sorting itself dates back far longer,
counting sort, and its application to radix sorting, were both invented by Harold H. Seward in 1954.
function ans = counting_sort(arr, k)
% countingSort : implements the counting sort algorithm
% INPUT: array of integers between 1 and k
% OUTPUT: sorted array
ans = []; % result array (sorted array)
C = zeros(k); % array for counting
C = C(1,:);
% counts the occurs of element i
for i = 1 : length(arr)
C(arr(i)) += 1;
endfor
% adress calculation
for j = 1 : k
if j > 1
C(j) += C(j-1);
endif
endfor
for m = length(arr) : -1 : 1
ans( C( arr(m) ) ) = arr(m);
C(arr(m)) -= 1;
endfor
endfunction