×

Counting Sort

Counting Sort: Counting sort is a sorting algorithm that is used to sort the elements of the array within a specific range. It counts the same element number of the array, and stores these same elements in the auxiliary array. It was developed by Harold H. Seward in 1954.

Complexity table of counting sort

ComplexityBest caseAverage caseWorst case
Time? (n + k)? (n + k)O (n + k)
Space  O S(nk)

Where n is the number of the element, and k is the range of the input.

Algorithm of counting sort

Counting_Sort (array, size)  max ? find the largest element from the array.    define count array length [largest + 1].      for i ? 0 to max do       count[i] = 0 // initialize count array with all zeros.      for i ? 1 to size do       increase count of each number which has found in the array.      for i ? 1 to max do       count[i] = count[i] + count[i+1] // cumulative sum.      for i ? size to 1 decrease by 1 do       store the number in the output array.       decrease count[i]    done      return the output array End  

Example 1: Suppose we have the following array, which we have to sort.

55418223

Step 1: Find the largest element in the given array.             

Largest element is = 8   5 5 4 1 8 2 2 3  

Step 2: Initialize a new array, and the size of the new array is (Largest + 1).  

Counting Sort in DS

Step 3: Count each element in the given array, and stores the element at their respective index in the count array. For example: If 5 is assigned 2 times to the original array, then 2 will be stored at the 5th position in the count array. If 6 is assigned 0 times, then 0 will be stored at the 6th position in the count array. 

Counting Sort in DS

Step 4: Make the cumulative sum of the elements of the count array. This helps to place the elements in the correct index of the sorted array.  

Counting Sort in DS

Step 5:  This process will be implemented throughout the array.  

Counting Sort in DS
Counting Sort in DS
Counting Sort in DS
Counting Sort in DS
Counting Sort in DS

Counting sort program in C language:

  #include <stdio.h>   
void countingSort(int array[], int size)
 {   
int output[10];   
int max = array[0]; 
  for (int i = 1; i < size; i++) 
{    
 if (array[i] > max)      max = array[i];  
}     
int count[10];  
 for (int i = 0; i <= max; ++i)
{   
  count[i] = 0;  
 }    
 for (int i = 0; i < size; i++) 
{  
   count[array[i]]++;  
 }   
  for (int i = 1; i <= max; i++)
 {   
  count[i] += count[i - 1]; 
  }  
   for (int i = size - 1; i >= 0; i--) 
{    
 output[count[array[i]] - 1] = array[i]; 
    count[array[i]]--; 
  } 
   for (int i = 0; i < size; i++) 
{   
  array[i] = output[i]; 
  } 
}  
 // Function to print an array void printArray(int array[], int size)
 {  
 for (int i = 0; i < size; ++i)
 {  
   printf("%d  ", array[i]); 
  } 
  printf("\n"); 
}   // Driver code int main() 
{ 
  int array[] = {5, 5, 4, 1, 3, 8};
  int n = sizeof(array) / sizeof(array[0]);
   countingSort(array, n); 
  printArray(array, n); 
}

Related Topics

Winner tree in Data Structures

Tree Data structure A tree is a hierarchical and non-linear data structure with nodes. Each node in the Tree contains a message value and stores the name passed to another ("child")...

6 minutes read.

About Data Structures

What exactly are data structures? A data structure is a type of storage that is used to organise and store data. It is a method of organising data on a computer...

5 minutes read.

Data Structure Infix to Postfix Conversion

Infix to Postfix Conversion The infix expression is easy to read and write by humans. In present time, we use the infix expression in our daily life but the computers are...

4 minutes read.

Detect and Remove Loop in a Linked List

Create a function called detectAndRemovetheLoop() that verifies whether a given Linked List has a loop, eliminates the loop if it does, and returns true if it does. It returns false...

6 minutes read.

Bottom view of the binary tree

The bottom of the binary tree is generally defined as the number of nods present in the bottom-most part of the tree. In this article, we will see the implementation...

3 minutes read.

Binary Tree vs Binary Search Tree: Data Structure

Difference Between Binary Tree and Binary Search Tree What is Binary Tree? A tree which each node can have utmost two children called binary tree. These children are referred as the ‘left...

3 minutes read.

Find out the area between two concentric circles

You have given two values of the radius of two circles. You have to find out the area between these two circles. Let's take an example - For the above diagram,...

3 minutes read.

Given a Perfect Binary Tree, Reverse Alternate Levels

Implementation //writing a program in C++ language to see how to approach it. #include <bits/stdc++.h> using namespace std; // creating a tree node. struct Nod { char ky; struct Nod *Lft, *Rt; }; // creating a new utility function...

9 minutes read.

Operations on 1D-Arrays

One Dimensional Array Operations Basic Methods The fundamental operations enabled by an array are listed below. Traverse prints each element of the array one by one.Insert a new element at the specified index.Delete...

8 minutes read.

Quick Sort

Quicksort is a sorting algorithm that uses a divide-and-conquer strategy. A pivot element is used to divide an array into subarrays (element selected from the array).  The pivot element should be...

4 minutes read.

Bitonical Sort

Arranging an unordered collecttion of things into asignificant order. •Comparision Based Model: Bubble Sort, Selection Sort -->Non-Comparison Based. Model: Bucket Sort or on the other hand a Count Sort Bitonic Sort: Bitonic sort Algorithm was made...

5 minutes read.

Assembly Line Scheduling

If we take an example of a car factory, there are two assembly lines. In an assembly line, we can assemble and repair the parts of a car. Now, suppose...

5 minutes read.

Comb Sort

Brush sort is a fairly direct orchestrating computation at first arranged by Wlodzimierz Dobosiewicz and Artur Borowy in 1980, later rediscovered (and given the name "Combsort") by Stephen Lacey and...

5 minutes read.

Finding Rank in a Binary Search Tree

Implementation // writing a C++ program to find out the rank and element in the program.  #include <bits/stdc++.h> using namespace std; struct __nod { int record; __nod *Lft, *Rt; int LftSize; }; __nod* new__nod(int record) { __nod *temp = new __nod; temp->record...

6 minutes read.

Find Number of Minimum Insertion to Make a String Palindrome

You have been given a string. You have to find out the number of minimum insertions to make this string palindrome. The string will contain only lower case alphabets. Note:What is...

4 minutes read.

CSS Text-indent

Text-indent The Text-indent property of CSS is used to set any first line’s indentation inside a text’s block. It describes the horizontal space amount that puts establish before the text line. It...

3 minutes read.

Threaded Binary Tree

The linked form of binary trees wastes storage capacity because more than half of the connection variables have a Missing value. A binary tree has several nodes. Hence n+1 link fields...

8 minutes read.

Counts the number of times a given element occurs in a Linked List

Counts the number of times a given element occurs in a Linked List This article will explain how we can count the occurrences of a particular element in a list. Here,...

3 minutes read.

Reverse a Linked List in groups of given size

Reverse a Linked List in groups of given size This article will explain how to reverse a linked list in groups of given size. Here we have given a linked list...

2 minutes read.

Linear Search

Searching: In the data structure, searching is the process in which an element is searched in a list that satisfies one or more than one condition. Types of searching There are two...

4 minutes read.