- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Implementing counting sort in JavaScript
We are required to write a JavaScript function that takes in an array of numbers and sorts it using the counting sort algorithm.
If we know the maximum value, we can use the counting sort algorithm to sort an array of Numbers in linear time and space. Using the maximum value create an array of that size to count the occurrence of each index value.
Then, we will extract all the indexes that have non-zero counts into our results array.
We will first use one loop to find out the greatest element of the array, once we have that we will use counting sort to sort the array.
Example
const arr = [4, 3, 1, 2, 3]; const findMaximum = arr => arr.reduce((acc, val) => val > acc ? val: acc, Number.MIN_VALUE) const countingSort = (arr = []) => { const max = findMaximum(arr); const counts = new Array(max + 1); counts.fill(0); arr.forEach(value => counts[value]++); const res = []; let resultIndex = 0; counts.forEach((count, index) => { for (let i = 0; i < count; i++) { res[resultIndex] = index; resultIndex++; }; }); return res; }; console.log(countingSort(arr));
Output
And the output in the console will be −
[ 1, 2, 3, 3, 4 ]
- Related Articles
- Implementing Priority Sort in JavaScript
- Implementing Heap Sort using vanilla JavaScript
- Counting Sort
- Implementing insertion sort to sort array of numbers in increasing order using JavaScript
- Python Program for Counting Sort
- Java Program for Counting Sort
- C++ Program to Implement Counting Sort
- Median and Mode using Counting Sort in C++
- Implementing Linear Search in JavaScript
- Implementing block search in JavaScript
- Counting matching substrings in JavaScript
- Implementing the Array.prototype.lastIndexOf() function in JavaScript
- Counting smaller and greater in JavaScript
- Counting rings in letters using JavaScript
- Implementing a Binary Search Tree in JavaScript

Advertisements