Counting Sort Algorithm In Javascript | letsbug
Hey in this article we implementing counting sort algorithm. If you are new to Data Structures and Algorithms you might have not heard about it. Because this is not taught in the colleges like they teach other algorithms like the bubble sort.
If you want to see implement more sorting algorithms click here
So we are going to implement this algorithm in javascript. And if you want to go deep into counting sort and how it works from the basic. You can find many tutorials on the web available. But in this article we are just focused on implementing it javascript. so
Counting Sort In Javascript.
code:
//counting sort algorithmfunction countingSort(arr: number[]):number[] {let max = Math.max(...arr);let output: number[] = [];let count: number[] = [];for (let i = 0; i <= max; i++) {count.push(0);}for (let i = 0; i < arr.length; i++) {if(arr[i] > max) continuecount[arr[i]]++;}for (let i = 1; i <= max; i++) {count[i] += count[i - 1];}for (let i = arr.length - 1; i >= 0; i--) {if(arr[i] > max) continueoutput[count[arr[i]] - 1] = arr[i];count[arr[i]]--;}return output;}let arr1 = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]console.log(`Before sorting: ${arr1}After sorting: ${countingSort(arr1)}`);
output:
$ node countingSort.js
Before sorting: 10,9,8,7,6,5,4,3,2,1
After sorting: 1,2,3,4,5,6,7,8,9,10
output |
Comments
Post a Comment