Parameters: This method accepts a single parameter as mentioned above and described below:
- compareFunction: This parameter is used to sort the elements according to different attributes and in a different order.
- compareFunction(a,b) < 0
- compareFunction(a,b) > 0
- compareFunction(a,b) = 0
Return value: This method returns the reference of the sorted original array.
Example 2: In this example, the sort() method arranges the elements of the array in ascending order.
Example 3: In this example, the sort() method the elements of the array are sorted according to the function applied to each element.
Example 3: In this example, we use the sort() method on the array of numbers & observe some unexpected behavior.
Our output should be -120, 0, 5.2, 20, 30, 100 but it’s not so, why? Because as we apply the direct sort() method, it would process accordingly: 100 would be placed before 20, as ‘2’ is larger than ‘1’, and similarly in the case of 30 & 5.2, as ‘5’ is larger than ‘3’ thus, 30 would be placed before 5.2. We can resolve this unexpected error by using the sort() method for numerics using the following compare function:
- Google Chrome 1 and above
- Edge 12 and above
- Firefox 1 and above
- Internet Explorer 5.5 and above
- Opera 4 and above
- Safari 1 and above
Time Complexity: The time complexity of the sort() method varies & depends on implementation.
For example, in the Firefox web browser, it uses the merge sort implementation which gives time complexity as O(nlog n). Whereas, in Google Chrome web browser, it uses the Timsort implementation (a hybrid of merge sort and insertion sort), gives time complexity is O(nlogn).
Please Login to comment...