Sort Count - Implementation Differences

I heard about Counting Sort and wrote my version of this based on what I understood.

public void my_counting_sort(int[] arr)
    {
        int range = 100;
        int[] count = new int[range];
        for (int i = 0; i < arr.Length; i++) count[arr[i]]++;
        int index = 0;
        for (int i = 0; i < count.Length; i++)
        {
            while (count[i] != 0)
            {
                arr[index++] = i;
                count[i]--;
            }
        }
    }

The above code works fine.

However, the algorithm specified in the CLRS is different. Below is my implementation

public int[] counting_sort(int[] arr)
    {
        int k = 100;
        int[] count = new int[k + 1];
        for (int i = 0; i < arr.Length; i++)
            count[arr[i]]++;
        for (int i = 1; i <= k; i++)
            count[i] = count[i] + count[i - 1];
        int[] b = new int[arr.Length];
        for (int i = arr.Length - 1; i >= 0; i--)
        {
            b[count[arr[i]]] = arr[i];
            count[arr[i]]--;
        }
        return b;
    }

I directly translated this from pseudo-code to C #. The code does not work and I get an IndexOutOfRange exception.

So my questions are:

  • What happened to the second piece of code?
  • What is the difference algorithm between my naive implementation and what is stated in the book?
+3
source share
3 answers

The problem with your version is that it will not work if the elements have satellite data.

The CLRS version will work and is stable.

EDIT:

CLRS Python, (, ) :

def sort(a):
  B = 101
  count = [0] * B
  for (k, v) in a:
    count[k] += 1
  for i in range(1, B):
    count[i] += count[i-1]
  b = [None] * len(a)
  for i in range(len(a) - 1, -1, -1):
    (k, v) = a[i]
    count[k] -= 1
    b[count[k]] = a[i]
  return b    


>>> print sort([(3,'b'),(2,'a'),(3,'l'),(1,'s'),(1,'t'),(3,'e')])
[(1, 's'), (1, 't'), (2, 'a'), (3, 'b'), (3, 'l'), (3, 'e')]
+2

b[count[arr[i]]-1] = arr[i];

, , : -).

, . , . , . , , . ( #, Java), , while ; - :

       for (int i = 0; i < count.Length; i++)
    {
        arrayFill(arr, index, count[i], i);
        index += count[i];
    }

Java java.util.Arrays.fill(...).

+1

The problem is that you are hardcoded the length of the array that you use up to 100. The length of the array should be m + 1where t is the maximum element on the original array. This is the first reason you think using the counting-sort method if you have information about the elements of an array, all insignificant, some constants, and this will work just fine.

0
source

Source: https://habr.com/ru/post/1765703/


All Articles