How does JS built-in sort() method work?
- The sort method will always sort arrays in place. The items are first converted to strings, and then their sequences of UTF-16 code units values are compared to determine the default sort order, which is ascending.
Example:
The problem of the sorting is that it only works well with strings. But for sorting numbers, it becomes a disaster. For example: if numbers are sorted as strings, then "25" is bigger than "100". Because "2" is bigger than "1".
Example:
We can fix this issue if we provide a compare function in the sort function.
The Compare Function:
The purpose of the compare function is to define an alternative sort order.
function(a, b){return a - b}
When sort() function compares two values, it sends the values to the compare function, and sorts the value according to the returned (negative, zero, positive) value.
- If the result is negative, a is sorted before b.
- If the result is positive, b is sorted before a.
- If the result is 0, no changes are done with the sort order of the two values.
Sort function with compare function:
We can also use the same trick to sort an array in descending order:
Time Complexity:
- Average Case: O(nlog(n))
- Worst Case: O(n2)
Space Complexity:
- It does not require any additional storage. Thus, the space complexity is O(1).
Conclusion:
In this article, we talked about the javascript built-in sort() function and its issues. Additionally, we discussed how to solve the sorting issue using the compare function.