How to resolve the algorithm Sorting algorithms/Counting sort step by step in the M4 programming language
How to resolve the algorithm Sorting algorithms/Counting sort step by step in the M4 programming language
Table of Contents
Problem Statement
Implement the Counting sort. This is a way of sorting integers when the minimum and maximum value are known.
The min and max can be computed apart, or be known a priori.
Note: we know that, given an array of integers, its maximum and minimum values can be always found; but if we imagine the worst case for an array that can hold up to 32 bit integers, we see that in order to hold the counts, an array of up to 232 elements may be needed. I.E.: we need to hold a count value up to 232-1, which is a little over 4.2 Gbytes. So the counting sort is more practical when the range is (very) limited, and minimum and maximum values are known a priori. (However, as a counterexample, the use of sparse arrays minimizes the impact of the memory usage, as well as removing the need of having to know the minimum and maximum values a priori.)
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Sorting algorithms/Counting sort step by step in the M4 programming language
Source code in the m4 programming language
divert(-1)
define(`randSeed',141592653)
define(`setRand',
`define(`randSeed',ifelse(eval($1<10000),1,`eval(20000-$1)',`$1'))')
define(`rand_t',`eval(randSeed^(randSeed>>13))')
define(`random',
`define(`randSeed',eval((rand_t^(rand_t<<18))&0x7fffffff))randSeed')
define(`set',`define(`$1[$2]',`$3')')
define(`get',`defn(`$1[$2]')')
define(`new',`set($1,size,0)')
define(`append',
`set($1,size,incr(get($1,size)))`'set($1,get($1,size),$2)')
define(`deck',
`new($1)for(`x',1,$2,
`append(`$1',eval(random%$3))')')
define(`for',
`ifelse($#,0,``$0'',
`ifelse(eval($2<=$3),1,
`pushdef(`$1',$2)$4`'popdef(`$1')$0(`$1',incr($2),$3,`$4')')')')
define(`show',
`for(`x',1,get($1,size),`get($1,x) ')')
define(`countingsort',
`for(`x',$2,$3,`set(count,x,0)')`'for(`x',1,get($1,size),
`set(count,get($1,x),incr(get(count,get($1,x))))')`'define(`z',
1)`'for(`x',$2,$3,
`for(`y',1,get(count,x),
`set($1,z,x)`'define(`z',incr(z))')')')
divert
deck(`a',10,100)
show(`a')
countingsort(`a',0,99)
show(`a')
You may also check:How to resolve the algorithm Multifactorial step by step in the C# programming language
You may also check:How to resolve the algorithm Zhang-Suen thinning algorithm step by step in the JavaScript programming language
You may also check:How to resolve the algorithm Strip comments from a string step by step in the Raku programming language
You may also check:How to resolve the algorithm Stirling numbers of the first kind step by step in the Phix programming language
You may also check:How to resolve the algorithm Concurrent computing step by step in the Standard ML programming language