Median and Mode using Counting Sort
Last Updated :
17 Apr, 2023
Given an n sized unsorted array, find median and mode using counting sort technique. This can be useful when array elements are in limited range.
Examples:
Input : array a[] = {1, 1, 1, 2, 7, 1}
Output : Mode = 1
Median = 1
Note: Median is average of middle two numbers (1 and 1)
Input : array a[] = {9, 9, 9, 9, 9}
Output : Mode = 9
Median = 9
Prerequisites: Count Sort, Median of Array, Mode (Most frequent element in array)
Input = [1, 4, 1, 2, 7, 1, 2, 5, 3, 6]
1. Auxiliary(count) array before summing its previous counts, c[]:
Index: 0 1 2 3 4 5 6 7 8 9 10
count: 0 3 2 1 1 1 1 1 0 0 0
2. Mode = index with maximum value of count.
Mode = 1(for above example)
3. count array is modified similarly as it is done while performing count sort.
Index: 0 1 2 3 4 5 6 7 8 9 10
count: 0 3 5 6 7 8 9 10 10 10 10
4. output array is calculated normally as in count sort, b[]:
output array b[] = {1, 1, 1, 2, 2, 3, 4, 5, 6, 7}
5. If size of array b[] is odd, Median = b[n/2]
Else Median = (b[(n-1)/2] + b[n/2])/2
6. For above example size of b[] is even hence, Median = (b[4] + b[5])/2.
Median = (2 + 3)/2 = 2.5
Basic Approach to be followed :
Assuming size of input array is n:
Step1: Take the count array before summing its previous counts into next index.
Step2: The index with maximum value stored in it is the mode of given data.
Step3: In case there are more than one indexes with maximum value in it, all are results for mode so we can take any.
Step4: Store the value at that index in a separate variable called mode.
Step5: Continue with the normal processing of the count sort.
Step6: In the resultant(sorted) array, if n is odd then median = middle-most element of the sorted array, And if n is even the median = average of two middle-most elements of the sorted array.
Step7: Store the result in a separate variable called median. Following is the implementation of problem discussed above:
Following is the implementation of problem discussed above:
C++
#include <bits/stdc++.h>
using namespace std;
void printModeMedian( int a[], int n)
{
int b[n];
int max = *max_element(a, a+n);
int t = max + 1;
int count[t];
for ( int i = 0; i < t; i++)
count[i] = 0;
for ( int i = 0; i < n; i++)
count[a[i]]++;
int mode = 0;
int k = count[0];
for ( int i = 1; i < t; i++)
{
if (count[i] > k)
{
k = count[i];
mode = i;
}
}
for ( int i = 1; i < t; i++)
count[i] = count[i] + count[i-1];
for ( int i = 0; i < n; i++)
{
b[count[a[i]]-1] = a[i];
count[a[i]]--;
}
float median;
if (n % 2 != 0)
median = b[n/2];
else
median = (b[(n-1)/2] +
b[(n/2)])/2.0;
cout << "median = " << median << endl;
cout << "mode = " << mode;
}
int main()
{
int a[] = { 1, 4, 1, 2, 7, 1, 2, 5, 3, 6 };
int n = sizeof (a)/ sizeof (a[0]);
printModeMedian(a, n);
return 0;
}
|
Java
import java.util.Arrays;
class GFG
{
static void printModeMedian( int a[], int n)
{
int [] b = new int [n];
int max = Arrays.stream(a).max().getAsInt();
int t = max + 1 ;
int count[] = new int [t];
for ( int i = 0 ; i < t; i++)
{
count[i] = 0 ;
}
for ( int i = 0 ; i < n; i++)
{
count[a[i]]++;
}
int mode = 0 ;
int k = count[ 0 ];
for ( int i = 1 ; i < t; i++)
{
if (count[i] > k)
{
k = count[i];
mode = i;
}
}
for ( int i = 1 ; i < t; i++)
{
count[i] = count[i] + count[i - 1 ];
}
for ( int i = 0 ; i < n; i++)
{
b[count[a[i]] - 1 ] = a[i];
count[a[i]]--;
}
float median;
if (n % 2 != 0 )
{
median = b[n / 2 ];
}
else
{
median = ( float ) ((b[(n - 1 ) / 2 ]
+ b[(n / 2 )]) / 2.0 );
}
System.out.println( "median = " + median);
System.out.println( "mode = " + mode);
}
public static void main(String[] args)
{
int a[] = { 1 , 4 , 1 , 2 , 7 , 1 , 2 , 5 , 3 , 6 };
int n = a.length;
printModeMedian(a, n);
}
}
|
Python3
def printModeMedian(a, n):
b = [ 0 ] * n
Max = max (a)
t = Max + 1
count = [ 0 ] * t
for i in range (n):
count[a[i]] + = 1
mode = 0
k = count[ 0 ]
for i in range ( 1 , t):
if (count[i] > k):
k = count[i]
mode = i
for i in range ( 1 , t):
count[i] = count[i] + count[i - 1 ]
for i in range (n):
b[count[a[i]] - 1 ] = a[i]
count[a[i]] - = 1
median = 0.0
if (n % 2 ! = 0 ):
median = b[n / / 2 ]
else :
median = ((b[(n - 1 ) / / 2 ] +
b[n / / 2 ]) / 2.0 )
print ( "median =" , median)
print ( "mode =" , mode)
if __name__ = = '__main__' :
arr = [ 1 , 4 , 1 , 2 , 7 , 1 , 2 , 5 , 3 , 6 ]
n = len (arr)
printModeMedian(arr, n)
|
C#
using System;
using System.Linq;
class GFG
{
static void printModeMedian( int []a, int n)
{
int [] b = new int [n];
int max = a.Max();
int t = max + 1;
int []count = new int [t];
for ( int i = 0; i < t; i++)
{
count[i] = 0;
}
for ( int i = 0; i < n; i++)
{
count[a[i]]++;
}
int mode = 0;
int k = count[0];
for ( int i = 1; i < t; i++)
{
if (count[i] > k)
{
k = count[i];
mode = i;
}
}
for ( int i = 1; i < t; i++)
{
count[i] = count[i] + count[i - 1];
}
for ( int i = 0; i < n; i++)
{
b[count[a[i]] - 1] = a[i];
count[a[i]]--;
}
float median;
if (n % 2 != 0)
{
median = b[n / 2];
}
else
{
median = ( float ) ((b[(n - 1) / 2] +
b[(n / 2)]) / 2.0);
}
Console.WriteLine( "median = " + median);
Console.WriteLine( "mode = " + mode);
}
public static void Main(String[] args)
{
int []a = {1, 4, 1, 2, 7, 1, 2, 5, 3, 6};
int n = a.Length;
printModeMedian(a, n);
}
}
|
PHP
<?php
function printModeMedian( $a , $n )
{
$b [ $n ] = array ();
$max = max( $a );
$t = $max + 1;
$count [ $t ] = array ();
for ( $i = 0; $i < $t ; $i ++)
$count [ $i ] = 0;
for ( $i = 0; $i < $n ; $i ++)
$count [ $a [ $i ]]++;
$mode = 0;
$k = $count [0];
for ( $i = 1; $i < $t ; $i ++)
{
if ( $count [ $i ] > $k )
{
$k = $count [ $i ];
$mode = $i ;
}
}
for ( $i = 1; $i < $t ; $i ++)
$count [ $i ] = $count [ $i ] + $count [ $i - 1];
for ( $i = 0; $i < $n ; $i ++)
{
$b [ $count [ $a [ $i ]] - 1] = $a [ $i ];
$count [ $a [ $i ]]--;
}
$median ;
if ( $n % 2 != 0)
$median = $b [ $n / 2];
else
$median = ( $b [( $n - 1) / 2] +
$b [( $n / 2)]) / 2.0;
echo "median = " , $median , "\n" ;
echo "mode = " , $mode ;
}
$a = array ( 1, 4, 1, 2, 7,
1, 2, 5, 3, 6 );
$n = sizeof( $a );
printModeMedian( $a , $n );
?>
|
Javascript
function printModeMedian(a, n) {
let b = new Array(n).fill(0);
let Max = Math.max(...a);
let t = Max + 1;
let count = new Array(t).fill(0);
for (let i = 0; i < n; i++) {
count[a[i]] += 1;
}
let mode = 0;
let k = count[0];
for (let i = 1; i < t; i++) {
if (count[i] > k) {
k = count[i];
mode = i;
}
}
for (let i = 1; i < t; i++) {
count[i] = count[i] + count[i - 1];
}
for (let i = n - 1; i >= 0; i--) {
b[count[a[i]] - 1] = a[i];
count[a[i]] -= 1;
}
let median = 0.0;
if (n % 2 !== 0) {
median = b[Math.floor(n / 2)];
} else {
median = (b[Math.floor((n - 1) / 2)] + b[Math.floor(n / 2)]) / 2.0;
}
console.log( "median =" , median);
console.log( "mode =" , mode);
}
let arr = [1, 4, 1, 2, 7, 1, 2, 5, 3, 6];
let n = arr.length;
printModeMedian(arr, n);
|
Output
median = 2.5
mode = 1
Time Complexity = O(N + P), where N is the time for input array and P is time for count array.
Space Complexity = O(P), where P is the size of auxiliary array.
Similar Reads
Counting Sort - Data Structures and Algorithms Tutorials
Counting Sort is a non-comparison-based sorting algorithm. It is particularly efficient when the range of input values is small compared to the number of elements to be sorted. The basic idea behind Counting Sort is to count the frequency of each distinct element in the input array and use that info
9 min read
Median and Mode using Counting Sort
Given an n sized unsorted array, find median and mode using counting sort technique. This can be useful when array elements are in limited range. Examples: Input : array a[] = {1, 1, 1, 2, 7, 1} Output : Mode = 1 Median = 1 Note: Median is average of middle two numbers (1 and 1) Input : array a[] =
12 min read
Implementing Counting Sort using map in C++
Counting Sort is one of the best sorting algorithms which can sort in O(n) time complexity but the disadvantage with the counting sort is it's space complexity, for a small collection of values, it will also require a huge amount of unused space. So, we need two things to overcome this: A data struc
2 min read
Counting Sort - Python
Counting Sort is a non-comparison-based sorting algorithm. It is particularly efficient when the range of input values is small compared to the number of elements to be sorted. The basic idea behind Counting Sort is to count the frequency of each distinct element in the input array and use that info
7 min read
C Program for Counting Sort
Counting sort is a sorting technique based on keys between a specific range. It works by counting the number of objects having distinct key values (kind of hashing). Then doing some arithmetic to calculate the position of each object in the output sequence. Algorithm: Step 1: StartStep 2 : Find Larg
3 min read
Java Program for Counting Sort
Counting sort is a sorting technique based on keys between a specific range. It works by counting the number of objects having distinct key values (kind of hashing). Then doing some arithmetic to calculate the position of each object in the output sequence. Java Code // Java implementation of Counti
2 min read
Parallel Count Sort
What is Parallel Count Sort?Parallel count sort is an efficient algorithm that sorts an array of elements in a parallel manner. It is a variation of the classic count sort algorithm which is used to sort a collection of objects based on their frequency. The algorithm is based on the idea of counting
12 min read
Problem based on Counting Sort
Find duplicates in an Array with values 1 to N using counting sort
Given a constant array of N elements which contain elements from 1 to N - 1, with any of these numbers appearing any number of times.Examples: Input: N = 5, arr[] = {1, 3, 4, 2, 2} Output: 2 Explanation: 2 is the number occurring more than once.Input: N = 5, arr[] = {3, 1, 3, 4, 2} Output: 3 Explana
11 min read
Kth smallest or largest element in unsorted Array using Counting Sort
Given an array arr[] and a number K, where K is smaller than the size of the array, we need to find the Kth smallest element in the given array. It is given that array elements can be repeated (not limited to distinct). Examples: Input: arr[] = {7, 10, 4, 3, 20, 15}, K = 3 Output: 7 Input: arr[] = {
7 min read
Sort an array of 0s, 1s and 2s (Simple Counting)
Given an array A[] consisting of 0s, 1s, and 2s, write a function that sorts A[]. The functions should put all 0s first, then all 1s, and all 2s in last. Examples: Input: {0, 1, 2, 0, 1, 2}Output: {0, 0, 1, 1, 2, 2} Input: {0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1}Output: {0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2,
11 min read
Counting Sort Visualization using JavaScript
GUI(Graphical User Interface) helps in better in understanding than programs. In this article, we will visualize Counting Sort using JavaScript. We will see how the frequencies of elements are stored and how we get the final sorted array. We will also visualize the time complexity of Counting Sort.
4 min read
Top MCQs on CountingSort Algorithm with Answers
Counting sort is a sorting technique based on keys between a specific range. It works by counting the number of objects having distinct key values (kind of hashing). Then doing some arithmetic to calculate the position of each object in the output sequence ... More on Counting Sort [mtouchquiz 180]
1 min read