Median and Mode using Counting Sort in C++

Consider we have an array of size n, we have to find the Median and Mode using the counting sort technique. This technique is useful, when the array elements are in limited range. Suppose the elements are {1, 1, 1, 2, 7, 1}, then the Mode is 1, and Median is 1.5. Let us see what is Median and what is Mode −

  • Median is the middle number in a sorted list of numbers
  • Mode is the element whose occurrences are maximum in the list

To get the Median and Mode, we have to follow these steps −

  • Assume that the size of the input array is n
  • Take the count array before summing its previous counts into next index
  • The index of the max value stored in it, is the mode of the given data.
  • If there are more than one max elements are present, then we can take one of them
  • Store the value into another separate variable named mode.
  • Continue with the normal processing of the count sort.
  • In the sorted array, if n is odd, then median is the middle most element of the sorted array, and if the n is even, then take middle two elements, then find the average of them to get the median.
  • Store the value into another separate variable named median.


 Live Demo

#include <iostream>
using namespace std;
bool isRepresentedInDDigits(int num, int d, int base) {
   if (d==1 && num < base)
      return true;
   if (d > 1 && num >= base)
      return isRepresentedInDDigits(num/base, --d, base);
      return false;
bool checkNumber(int num, int d) {
   // Check for all bases one by one
   for (int base=2; base<=32; base++)
   if (isRepresentedInDDigits(num, d, base))
   return true;
   return false;
int main() {
   int num = 8;
   int dig = 2;
   if(checkNumber(num, dig))
      cout << "Can be represented";
      cout << "Can not be represented";


Can be represented