I'm looking to sort an array of about 200-300 objects, sorting on a specific key and a given order (asc/desc). The order of results must be consistent and stable.
What would be the best algorithm to use, and could you provide an example of it's implementation in javascript?
Thanks!
A simple one mergeSort from http://www.stoimen.com/blog/2010/07/02/friday-algorithms-javascript-merge-sort/
You can also use Timsort. This is a really complicated algorithm (400+ lines, hence no source code here), so see Wikipedia's description or use one of the existing JavaScript implementations:
GPL 3 implementation. Packaged as Array.prototype.timsort. Appears to be an exact rewrite of Java code.
Public domain implementation Meant as a tutorial, the sample code only shows its use with integers.
Timsort is a highly optimized hybrid of mergesort and shuffle sort and is the default sorting algorithm in Python and in Java (1.7+). It is a complicated algorithm, since it uses different algorithms for many special cases. But as a result it's extremely fast under a wide variety of circumstances.
Counting Sort is faster than merge sort (it performs in O(n) time) and it is intended for use on integers.
Example:
I know that this question has been answered for some time, but I happen to have a good stable merge sort implementation for Array and jQuery in my clipboard, so I'll share it in the hopes that some future searchers might find it useful.
It allows you to specify your own comparison function just like the normal
Array.sort
implementation.Implementation
Example Usage
It is possible to get a stable sorting from a non-stable sort function.
Before sorting you get the position of all the elements. In your sort condition, if both elements are equal, then you sort by the position.
Tada! You've got a stable sort.
I've written an article about it on my blog if you want to know more about this technique and how to implement it: http://blog.vjeux.com/2010/javascript/javascript-sorting-table.html
Here's how you could extend JS default Array object with a prototype method utilizing MERGE SORT. This method allows for sorting on a specific key (first parameter) and a given order ('asc'/'desc' as second parameter)
You can test this out yourself by dropping the above snippet into your browser console, then trying:
Or order based on a specific field in an array of objects: