Computer >> Computer tutorials >  >> Programming >> Javascript

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 ]