﻿ C# Sharp exercises: Counting sort - w3resource

# C# Sharp Searching and Sorting Algorithm Exercises: Counting sort

## C# Sharp Searching and Sorting Algorithm: Exercise-4 with Solution

Write a C# Sharp program to sort a list of elements using Counting sort

According to Wikipedia "In computer science, counting sort is an algorithm for sorting a collection of objects according to keys that are small integers; that is, it is an integer sorting algorithm. It operates by counting the number of objects that have each distinct key value, and using arithmetic on those counts to determine the positions of each key value in the output sequence. Its running time is linear in the number of items and the difference between the maximum and minimum key values, so it is only suitable for direct use in situations where the variation in keys is not significantly greater than the number of items. However, it is often used as a subroutine in another sorting algorithm, radix sort, that can handle larger keys more efficiently".

The algorithm loops over the items, computing a histogram of the number of times each key occurs within the input collection. It then performs a prefix sum computation (a second loop, over the range of possible keys) to determine, for each key, the starting position in the output array of the items having that key. Finally, it loops over the items again, moving each item into its sorted position in the output array.

Sample Solution:-

C# Sharp Code:

``````using System;
using System.Linq;
public class Counting_sort
{
public static void Main()
{
int[] array = new int[10]
{
2, 5, -4, 11, 0, 8, 22, 67, 51, 6
};

Console.WriteLine("\n"+"Original array :");
foreach (int aa in array)
Console.Write(aa + " ");

int[] sortedArray = new int[array.Length];

// find smallest and largest value
int minVal = array[0];
int maxVal = array[0];
for (int i = 1; i < array.Length; i++)
{
if (array[i] < minVal) minVal = array[i];
else if (array[i] > maxVal) maxVal = array[i];
}

// init array of frequencies
int[] counts = new int[maxVal - minVal + 1];

// init the frequencies
for (int i = 0; i < array.Length; i++)
{
counts[array[i] - minVal]++;
}

// recalculate
counts[0]--;
for (int i = 1; i < counts.Length; i++)
{
counts[i] = counts[i] + counts[i - 1];
}

// Sort the array
for (int i = array.Length - 1; i >= 0; i--)
{
sortedArray[counts[array[i] - minVal]--] = array[i];
}

Console.WriteLine("\n"+"Sorted array :");
foreach (int aa in sortedArray)
Console.Write(aa + " ");
Console.Write("\n");

}
}
```
```

Sample Output:

```Original array :
2 5 -4 11 0 8 22 67 51 6
Sorted array :
-4 0 2 5 6 8 11 22 51 67
```

Flowchart:

C# Sharp Practice online:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

﻿

New Content: Composer: Dependency manager for PHP, R Programming