Recently when I was working with JavaScript “sort()” function, I found in one of the tutorials that this function does not sort the numbers properly. Instead to sort numbers, a function must be added that compares numbers, like the following code:-
<script type="text/javascript">
function sortNumber(a,b)
{
return a - b;
}
var n = ["10", "5", "40", "25", "100", "1"];
document.write(n.sort(sortNumber));
</script>
The output then comes as:-
1,5,10,25,40,100
Now what I didn’t understand is that why is this occurring & can anybody please tell in details as to what type of algorithm is being used in this “sort()” function? This is because for any other language, I didn’t find this problem where the function didn’t sort the numbers correctly.
Any help is greatly appreciated.
Well, if you are sorting the following list, it contains only strings:
So I would expect any language would compare them as strings, thus resulting in a sort order of:
Which necessitates your code to use a custom sort (as you have done) to cast the strings back to integers for the purposes of sorting.
Edit
As Pointy mentioned, by default the JavaScript sort() method sorts elements alphabetically, including numbers:
Simply amazing… so a custom sort is required even for an array of integers.