How to resolve the algorithm Sorting algorithms/Counting sort step by step in the Elena programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Sorting algorithms/Counting sort step by step in the Elena 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 Elena programming language

Source code in the elena programming language

import extensions;
import system'routines;
 
extension op
{
    countingSort()
        = self.clone().countingSort(self.MinimalMember, self.MaximalMember);
 
    countingSort(int min, int max)
    {
        int[] count := new int[](max - min + 1);
        int z := 0;
 
        count.populate:(int i => 0);
 
        for(int i := 0, i < self.Length, i += 1) { count[self[i] - min] := count[self[i] - min] + 1 };
 
        for(int i := min, i <= max, i += 1)
        {
            while (count[i - min] > 0)
            {
                self[z] := i;
                z += 1;
 
                count[i - min] := count[i - min] - 1
            }
        }
    }
}
 
public program()
{
    var list := new Range(0, 10).selectBy:(i => randomGenerator.nextInt(10)).toArray();
 
    console.printLine("before:", list.asEnumerable());
    console.printLine("after :", list.countingSort().asEnumerable())
}

  

You may also check:How to resolve the algorithm List comprehensions step by step in the Haskell programming language
You may also check:How to resolve the algorithm Vector step by step in the Forth programming language
You may also check:How to resolve the algorithm Comma quibbling step by step in the Kotlin programming language
You may also check:How to resolve the algorithm Sort disjoint sublist step by step in the MiniScript programming language
You may also check:How to resolve the algorithm Matrix chain multiplication step by step in the R programming language