w3resource

C#: 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 }; // Initializing an array with values

        Console.WriteLine("\n" + "Original array :");
        foreach (int aa in array) // Loop to display the original array elements                       
            Console.Write(aa + " "); // Printing each element of the array

        int[] sortedArray = new int[array.Length]; // Initializing an array for sorted elements

        // Find smallest and largest value in the array
        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];
        }

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

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

        // Recalculate the counts
        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) // Loop to display the sorted array elements                     
            Console.Write(aa + " "); // Printing each element of the sorted array

        Console.Write("\n"); // Adding a new line at the end
    }
}

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 Searching and Sorting Algorithm Exercises: Counting sort.

C# Sharp Practice online:

Contribute your code and comments through Disqus.

Previous: Write a C# Sharp program to sort a list of elements using Bubble sort.
Next: Write a C# Sharp program to sort a list of elements using Heap sort.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/csharp-exercises/searching-and-sorting-algorithm/searching-and-sorting-algorithm-exercise-4.php