Counting sort

by Anton Bagayev

JavaScript

function countingSort(array) {

	// find max value to know the range
	let maxNum = array[0];
	let helperArray = [];
	let result = [];
	for (let i = 1; i < array.length; i++) {
		if (array[i] > maxNum) {
			maxNum = array[i];
		}
	}
	
	// init counts
	for (let i = 0; i < maxNum+1; i++) {
		helperArray.push(0);
	}
	
	// count elements
	for (let i = 0; i < array.length; i++) {
		helperArray[array[i]]++;
	}
	
	// extract them in the correct order
	for (let i = 0; i < helperArray.length; i++) {
		for (let j = 0; j < helperArray[i]; j++) {
			result.push(i);
		}
	}
	
	return result;
	
}


console.log(countingSort([3,5,3,2,6,4,8,2,6,9,1]));