Count Sort

Author: Theodore Odeluga

This is a Node command line project and Node.js can be downloaded from here

Instructions for running a command line program with Node.js can be found here

The source files for this project can be downloaded from here

As seen earlier with alphabetical characters, a sort algorithm isn’t necessarily a difficult thing to implement.

Numeric sorting is even easier.

Indeed, this adaptation of the earlier example is simpler because it works with a computer’s more “natural” way to process data – numbers.

As per sorting letters, sorting numbers has a similar requirement – including an empty array for results and an array for containing random samples.

Again, to process data for two containers, we have two variables – the reappearance of the count variable and the i iterator.

let count = 0;
let i;

We’ll also be using a nested loop again.

Let's get started.

As per the alphabetical sort algorithm, this code starts with a test for non-equality between the length of the sorted array and the length of unsorted – all inside a while loop.

while(sorted.length != unsorted.length){
count++;
for(i=0; i < unsorted.length; i++){
if(count == unsorted[i]){
sorted.push(unsorted[i]);
}
}
}

The while loop runs while the length of the sorted array is unequal to the length of the unsorted array.

In the next line, we continually increment the value of count.

After this, we open a for loop. Here we perform another test on an array’s length.

In this instance, while i is unequal to the length of unsorted, we continually test the value of count for equality with i as an index of the unsorted array.

As before, because of JavaScript’s automatic tracking of an arrays index, if the value of i is equal to count (count of course is logically sorted automatically because it’s a numeric object), the [i] element whose index is equivalent to the value of count is in turn automatically pushed into sorted.

Here’s the entire program for convenience.

let unsorted = [2,500,7,39,100,65,40];
let sorted = [];
let count = 0;
let i;

function sortit() {
while(sorted.length != unsorted.length){
count++;
for(i=0; i < unsorted.length; i++){
if(count == unsorted[i]){
sorted.push(unsorted[i]);
}
}
}
}
sortit();
console.log(sorted);

Conclusion

Job done. This is an even more straightforward system than the alphabetical sort program. I hope as a result, the code here is even clearer. See how you could extend it (say, organizing larger numbers, words and phrases for example). It would be a worthwhile exercise in one important aspect of working with data - making sure its organized before processing. Thanks for reading and all the best.