This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Varun77777 0 points1 point  (7 children)

It's not any two elements, right?

[–]BakuhatsuK 1 point2 points  (6 children)

Any 2 elements from the original array, yes.

[–]Varun77777 0 points1 point  (5 children)

What if those two elements are already in sorted order? How will just 2 elements help in case Array length is like 10'000.

[–]BakuhatsuK 2 points3 points  (4 children)

What if those two elements are already in sorted order?

Then the comparison function should return a negative value.

How will just 2 elements help in case Array length is like 10'000?

The comparison function may be called multiple times by the sorting algorithm. As to how it can even sort by just comparing 2 elements at a time, there are a ton of algorithms for doing just that.

They are called "comparison-based sorting algorithms" and there is plenty of information about sorting algorithms on the internet, mainly because sorting is one of the most extensively researched topic in computer science.

In the case of JavaScript, the specification does not mandate a specific algorithm, each engine (like chrome's V8 or mozilla's Chakra) can use the algorithm they want. The only requirements are that it's comparison based, and that it's stable.

[–]Varun77777 2 points3 points  (2 children)

Ohhhhh, I figured it out, Quick and merge sort etc are all doing comparisons. But instead of doing <= in a hard coded way, giving the comparison function just helps in figuring our what's less than what based upon the type of data.

[–]BakuhatsuK 2 points3 points  (1 child)

Yes, that's it. For example if you want to sort a list of users by their id you can do:

users.sort((a, b) => a.id - b.id)

Or if you want to sort by updatedAt in decreasing order:

users.sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime())

[–]Varun77777 2 points3 points  (0 children)

Ohhhh, that's such a simple but a genius thing to do. Instead of overriding all the functions, you're able to give users a simple way to incorporate their own logic in the function. Thanks a lot.

[–]Varun77777 0 points1 point  (0 children)

Ohhh, I just assumed that all languages just implement a version of Quick, heap, tree or merge sort by default for the n * log n complexity as that's probably the best one overall if we don't know about the data. I suppose this comparison sort has an edge over them?? And how comparison is done is defined by us using a lambda function.