ProDeveloperTutorial.com

Tutorials and Programming Solutions
Menu
  • Shell Scripting
  • System Design
  • Linux System Programming
  • 4g LTE
  • Coding questions
  • C
  • C++
  • DSA
  • GIT
  • 450 DSA Cracker
  • 5G NR
  • O-RAN

Sorting Algorithm 11: Counting Sort

prodevelopertutorial April 19, 2019

Counting sort algorithm is a linear sort algorithm. This algorithm is not based on comparing the elements but rather counting of the elements.

Usually we use this algorithm with other algorithm for example radix sort algorithm.

Below are the steps how the algorithm works:

Step 1: Find the minimum and maximum value from the array.

Step 2: Create a second array from the minimum value to maximum value.

Step 3: Increment the second array whenever we find a number from the first array.

Step 4: Once all the numbers will be written, take the sum [see in the pic below].

Step 5: Place the elements in the respective positions. You will get the sorted array.

Let us understand counting sort algorithm with help of an example:

Consider the below array, we shall sort this array using counting sort algorithm.

Counting_sort

From the image above, we know that 4 is the smallest element and 15 is the largest element.

Now create one more array to hold the elements from index 4 to 15 and also counting array to hold the count as shown below:

Counting_sort

Now, count the number of times each element is repeated. Al the elements are repeated only once. Hence write 1 in their respective index as shown below;

Counting_sort

write 0, in all the index which are empty.

Counting_sort

Now create a sum count array that will hold the sum of counts for the given index. Initially it will be as below:

Counting_sort

Now add the index and write down the sum count as shown below:

Counting_sort

Now we shave filled out sum count array, let’s sort the input with the help of counting sort.

Create an output array. Initially the output array will be as below:

Counting_sort

 

Now, check the element from input array and get the value from sumCount array and place it at its index.

For example,

First element is 14.

The value for 14 in sumCount array is 6. Hence place 14 in index 6 in output array.

Counting_sort

For 5, the value of 5 in sumCount array is 2. Hence place 5 in index 2.

Counting_sort

 

Similarly, do for all the elements we get sorted output as below:

Counting_sort

Solution for Counting Sort in C:

#include<stdio.h>
#include<string.h>

void print_array(int array[], int length)
{
	int index = 0;

	printf("The sorted array is \n");

	for(index = 0 ; index < length ; index++)
	{
		printf("%d\n",array[index] );
	}
}


void counting_sort (int array[], int length)
{


	int max_number = array[0];
	int min_number = array[0];

	int i = 0;

	// find maximum and minimum number
	for ( i = 0; i < length; ++i)
	{
		if (array[i] > max_number)
			max_number = array[i];

		if (array[i] < min_number)
			min_number = array[i];
	}

    int range = max_number - min_number + 1;

	int counting_array [range];
	memset(counting_array, 0, sizeof(counting_array));


	// initialize the occurance of each element in counting array
	for ( i = 0; i < length; ++i)
	{
		counting_array[array[i] - min_number]++;
	}

	// calculate the sum of indexes
	int j = 0;
	for (int i = 1; i < range; i++)
	{
		counting_array[i] += counting_array[i - 1];
	}

	for (int i = 0; i < range; i++)
	{
		while( j < counting_array[i])
			array[j++] = i + min_number;
	}
	
}

int main()
{
	int length = 0;
	int array[100];
	int index = 0;

	printf("Enter the length of the array\n");
	scanf("%d", &length);

	printf("Enter the array elements of length %d\n", length);

	for (index = 0; index < length; ++index)
	{
		scanf("%d", &array[index]);
	}

	counting_sort(array, length);

	print_array(array, length);


}

Output:

Enter the length of the array
4
Enter the array elements of length 4
4
3
2
1
The sorted array is
1
2
3
4

Further Reading:

AJ’s definitive guide for DS and Algorithms. Click here to study the complete list of algorithm and data structure tutorial. 85+ chapters to study from.

 

List Of Tutorials available in this website:

C Programming 20+ ChaptersC++ Programming 80+ Chapters
100+ Solved Coding QuestionsData Structures and Algorithms 85+ Chapters
System design 20+ ChaptersShell Scripting 12 Chapters
4g LTE 60+ ChaptersMost Frequently asked Coding questions
5G NR 50+ ChaptersLinux System Programming 20+ chapters
Share
Email
Tweet
Linkedin
Reddit
Stumble
Pinterest
Prev Article
Next Article

About The Author

prodevelopertutorial

Follow this blog to learn more about C, C++, Linux, Competitive Programming concepts, Data Structures.

Leave a Reply Cancel Reply

You must be logged in to post a comment.

ProDeveloperTutorial.com

Tutorials and Programming Solutions
Copyright © 2023 ProDeveloperTutorial.com
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept”, you consent to the use of ALL the cookies.
Do not sell my personal information.
Cookie SettingsAccept
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT