numbers.sort(function(a, b)
{
return a - b
};
Please explain how this sorting function works in the back to sort numeric array.
numbers.sort(function(a, b)
{
return a - b
};
Please explain how this sorting function works in the back to sort numeric array.
I went through this article and found that compare function swap the values as per the return values .If +1 then it places b before a and if its -1 then a before b and if 0 then no-change. But still not getting where the code is for swap. I am very new to coding so not getting it properly. I can’t see any code where we are changing the indexes of a and b or in other words swaping values.Please help me on this.
That’s just how the sort() method works, which is part of JS. It’s part of the langauge engine behind the scenes, written in C++ and pre-compiled so you won’t really see the code.
Just like you don’t see the code of how it stores a string in a variable in memory. You don’t need to worry about that because JS handles it.
It looks like there is pseudocode for how to implement JS sort here: https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype.sort
But it sounds like you already get how it works, you just want to see the code?
Thank you so much for detailed explanation. It will help to understand future challenges as well !!!
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.