Algorithm of JavaScript "sort()" Function
Posted
by
Knowledge Craving
on Stack Overflow
See other posts from Stack Overflow
or by Knowledge Craving
Published on 2010-08-06T11:40:04Z
Indexed on
2012/11/01
5:01 UTC
Read the original article
Hit count: 132
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.
© Stack Overflow or respective owner